文章目录 1.JWT依赖 2.JWT工具类TokenUtils.java 3.token示例 4.拦截器JwtInterceptor.java 5.拦截器设置InterceptorConfig.java 6.统一接口WebConfig.java 7.设置自定义头配置 CorsConfig .java 8.GlobalExceptionHandler.java 9.ServiceException.java 10.设置token: 11.最终效果:
1.JWT依赖
< dependency> < groupId> com.auth0</ groupId> < artifactId> java-jwt</ artifactId> < version> 3.10.3</ version> </ dependency>
< dependency> < groupId> cn.hutool</ groupId> < artifactId> hutool-all</ artifactId> < version> 5.7.20</ version>
</ dependency>
< dependency> < groupId> org.apache.poi</ groupId> < artifactId> poi-ooxml</ artifactId> < version> 4.1.2</ version>
</ dependency>
2.JWT工具类TokenUtils.java
package com. example. springboot. utils ; import cn. hutool. core. date. DateUtil ;
import cn. hutool. core. util. StrUtil ;
import com. auth0. jwt. JWT;
import com. auth0. jwt. algorithms. Algorithm ;
import com. example. springboot. entity. User ;
import com. example. springboot. service. IUserService ;
import org. springframework. stereotype. Component ;
import org. springframework. web. context. request. RequestContextHolder ;
import org. springframework. web. context. request. ServletRequestAttributes ; import javax. annotation. PostConstruct ;
import javax. annotation. Resource ;
import javax. servlet. http. HttpServletRequest ;
import java. util. Date ; @Component
public class TokenUtils { private static IUserService staticUserService; @Resource private IUserService userService; @PostConstruct public void setUserService ( ) { staticUserService = userService; } public static String genToken ( String userId, String sign) { return JWT. create ( ) . withAudience ( userId) . withExpiresAt ( DateUtil . offsetHour ( new Date ( ) , 2 ) ) . sign ( Algorithm . HMAC256 ( sign) ) ; } public static User getCurrentUser ( ) { try { HttpServletRequest request = ( ( ServletRequestAttributes ) RequestContextHolder . getRequestAttributes ( ) ) . getRequest ( ) ; String token = request. getHeader ( "token" ) ; if ( StrUtil . isNotBlank ( token) ) { String userId = JWT. decode ( token) . getAudience ( ) . get ( 0 ) ; return staticUserService. getById ( Integer . valueOf ( userId) ) ; } } catch ( Exception e) { return null ; } return null ; }
}
3.token示例
{ "username" : "admin" ,"password" : "admin" ,"nickname" : "管理员11111" ,"avatarUrl" : "https://img-blog.csdnimg.cn/c6d0ece75d3f4833bd820b8aa2eb952b.png" ,"token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjQ0MzgxMDI4fQ.87nwS8ENDOu6RY-4PTLBBzXfDv6-5TiQLQhBXrYGb700" }
4.拦截器JwtInterceptor.java
package com. example. springboot. config. interceptor ; import cn. hutool. core. util. StrUtil ;
import com. auth0. jwt. JWT;
import com. auth0. jwt. JWTVerifier ;
import com. auth0. jwt. algorithms. Algorithm ;
import com. auth0. jwt. exceptions. JWTDecodeException ;
import com. auth0. jwt. exceptions. JWTVerificationException ;
import com. example. springboot. common. Constants ;
import com. example. springboot. entity. User ;
import com. example. springboot. exception. ServiceException ;
import com. example. springboot. service. IUserService ;
import org. springframework. beans. factory. annotation. Autowired ;
import org. springframework. web. method. HandlerMethod ;
import org. springframework. web. servlet. HandlerInterceptor ; import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ; public class JwtInterceptor implements HandlerInterceptor { @Autowired private IUserService userService; @Override public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler) { String token = request. getHeader ( "token" ) ; if ( ! ( handler instanceof HandlerMethod ) ) { return true ; } if ( StrUtil . isBlank ( token) ) { throw new ServiceException ( Constants . CODE_401, "无token,请重新登录" ) ; } String userId; try { userId = JWT. decode ( token) . getAudience ( ) . get ( 0 ) ; } catch ( JWTDecodeException j) { throw new ServiceException ( Constants . CODE_401, "token验证失败,请重新登录" ) ; } User user = userService. getById ( userId) ; if ( user == null ) { throw new ServiceException ( Constants . CODE_401, "用户不存在,请重新登录" ) ; } JWTVerifier jwtVerifier = JWT. require ( Algorithm . HMAC256 ( user. getPassword ( ) ) ) . build ( ) ; try { jwtVerifier. verify ( token) ; } catch ( JWTVerificationException e) { throw new ServiceException ( Constants . CODE_401, "token验证失败,请重新登录" ) ; } return true ; }
}
5.拦截器设置InterceptorConfig.java
package com. example. springboot. config ; import com. example. springboot. config. interceptor. JwtInterceptor ;
import org. springframework. context. annotation. Bean ;
import org. springframework. context. annotation. Configuration ;
import org. springframework. web. servlet. config. annotation. InterceptorRegistry ;
import org. springframework. web. servlet. config. annotation. WebMvcConfigurer ; @Configuration
public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors ( InterceptorRegistry registry) { registry. addInterceptor ( jwtInterceptor ( ) ) . addPathPatterns ( "/**" ) . excludePathPatterns ( "/api/user/login" , "/api/user/register" , "/**/export" , "/**/import" ) ; } @Bean public JwtInterceptor jwtInterceptor ( ) { return new JwtInterceptor ( ) ; }
}
6.统一接口WebConfig.java
package com. example. springboot. config ;
import org. springframework. context. annotation. Configuration ;
import org. springframework. web. bind. annotation. RestController ;
import org. springframework. web. servlet. config. annotation. PathMatchConfigurer ;
import org. springframework. web. servlet. config. annotation. WebMvcConfigurer ; @Configuration
public class WebConfig implements WebMvcConfigurer { @Override public void configurePathMatch ( PathMatchConfigurer configurer) { configurer. addPathPrefix ( "/api" , clazz -> clazz. isAnnotationPresent ( RestController . class ) ) ; }
}
7.设置自定义头配置 CorsConfig .java
import org. springframework. context. annotation. Bean ;
import org. springframework. context. annotation. Configuration ;
import org. springframework. web. cors. CorsConfiguration ;
import org. springframework. web. cors. UrlBasedCorsConfigurationSource ;
import org. springframework. web. filter. CorsFilter ; @Configuration
public class CorsConfig { @Bean public CorsFilter corsFilter ( ) { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource ( ) ; CorsConfiguration corsConfiguration = new CorsConfiguration ( ) ; corsConfiguration. addAllowedOrigin ( "*" ) ; corsConfiguration. addAllowedHeader ( "*" ) ; corsConfiguration. addAllowedMethod ( "*" ) ; source. registerCorsConfiguration ( "/**" , corsConfiguration) ; return new CorsFilter ( source) ; }
}
8.GlobalExceptionHandler.java
package com. example. springboot. exception ; import com. example. springboot. common. Result ;
import org. springframework. web. bind. annotation. ControllerAdvice ;
import org. springframework. web. bind. annotation. ExceptionHandler ;
import org. springframework. web. bind. annotation. ResponseBody ;
@ControllerAdvice
public class GlobalExceptionHandler { @ExceptionHandler ( ServiceException . class ) @ResponseBody public Result handle ( ServiceException se) { return Result . error ( se. getCode ( ) , se. getMessage ( ) ) ; }
}
9.ServiceException.java
package com. example. springboot. exception ; import lombok. Getter ;
@Getter
public class ServiceException extends RuntimeException { private String code; public ServiceException ( String code, String msg) { super ( msg) ; this . code= code; }
}
10.设置token:
String token= TokenUtils . genToken ( one. getId ( ) . toString ( ) , one. getPassword ( ) ) ;
userDTO. setToken ( token) ;
11.最终效果: