1.登陆注册校验token,jwt校验
< dependency> < groupId> com.auth0</ groupId> < artifactId> java-jwt</ artifactId> < version> 4.4.0</ version> </ dependency>
< dependency> < groupId> org.springframework.boot</ groupId> < artifactId> spring-boot-starter-test</ artifactId> </ dependency>
2.jwt测试
@Test public void test ( ) { Map < String , Object > map = new HashMap < > ( ) ; map. put ( "id" , 1 ) ; map. put ( "username" , "zhangsan" ) ; String token = JWT . create ( ) . withClaim ( "user" , map) . withExpiresAt ( new Date ( System . currentTimeMillis ( ) + 1000 * 60 * 60 * 12 ) ) . sign ( Algorithm . HMAC256 ( "ivan" ) ) ; System . out. println ( token) ; } @Test public void testParse ( ) { String token= "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6InpoYW5nc2FuIn0sImV4cCI6MTcyMDU4NzIzN30." + "_kprHQuQJZgeMS9yuNBYIi2xfT26Xk3goLNg1lStHGo" ; JWTVerifier j = JWT . require ( Algorithm . HMAC256 ( "ivan" ) ) . build ( ) ; DecodedJWT verify = j. verify ( token) ; Map < String , Claim > claims = verify. getClaims ( ) ; Claim user = claims. get ( "user" ) ; System . out. println ( user) ; }
3.封装工具函数
public class JwtUtil { private static final String KEY = "ivan" ; public static String genToken ( Map < String , Object > claims) { return JWT . create ( ) . withClaim ( "claims" , claims) . withExpiresAt ( new Date ( System . currentTimeMillis ( ) + 1000 * 60 * 60 * 12 ) ) . sign ( Algorithm . HMAC256 ( KEY ) ) ; } public static Map < String , Object > parseToken ( String token) { return JWT . require ( Algorithm . HMAC256 ( KEY ) ) . build ( ) . verify ( token) . getClaim ( "claims" ) . asMap ( ) ; }
}
4.拦截器设置
@Component
public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request. getHeader ( "Authorization" ) ; try { Map < String , Object > map = JwtUtil . parseToken ( token) ; return true ; } catch ( Exception e) { response. setStatus ( 401 ) ; return false ; } }
}
5.将拦截器注册到注册中心
@Configuration
public class WebConfig implements WebMvcConfigurer { @Autowired private LoginInterceptor loginInterceptor; @Override public void addInterceptors ( InterceptorRegistry registry) { registry. addInterceptor ( loginInterceptor) . excludePathPatterns ( "user/login" , "/user/register" ) ; } }