作者:手机用户2502905381 | 来源:互联网 | 2023-09-01 12:30
目录1jwt验证流程2token组成3代码实现1jwt验证流程首先,前端通过Web表单将自己的用户名和密码发送到后端的接口。这一过程--般是一个HTTPPOST请
1 jwt验证流程 首先,前端通过Web 表单将自己的用户名和密码发送到后端的接口。这一过程- - 般是一 个HTTP POST请求。建议的方式是通过SSL加密的传输( https协议) ,从而避免敏感信息被嗅探。后端核对用户名和密码成功后,将用户的id等其他信息作为JWT Payload ( 负载) ,将其与头部分别进行Base64 编码拼接后签名,形成一个JWT ( Token ) 。 形成的JWT就是一个形同11. zzz. xxx的字符串。token head . payload . singurater后端将JWT字符串作为登录成功的返回结果返回给前端。 前端可以将返回的结果保存在localStorage或sessionStorage上, 退出登录时前端删除保存的JWT即可。前端在每次请求时将JWT放入HTTP Header 中的Authorization 位。 ( 解决XSS和XSRF问题) 后端检查是否存在,如存在验证JWT的有效性。例如,检查签名是否正确; 检查Token 是否过期; 检查Token 的接收方是否是自己( 可选) 验证通过后后端使用JWT中包含的用户信息进行其他逻辑操作, 返回相应结果。
2 token组成
3 代码实现 1 在我们的springboot项目里面,加入jar包
< ! -- 引入jwt-- > < dependency> < groupId> com. auth0< / groupId> < artifactId> java- jwt< / artifactId> < version> 3.10 .3 < / version> < / dependency>
2 工具类
package com. chilly. utils ; import com. auth0. jwt. JWT ; import com. auth0. jwt. JWTCreator ; import com. auth0. jwt. algorithms. Algorithm ; import com. auth0. jwt. interfaces. DecodedJWT ; import java. util. Calendar ; import java. util. Map ; public class JWTUtils { private static String SECRET &#61; "token!Q&#64;W#E$R" ; public static String getToken ( Map < String , String > map) { JWTCreator. Builder builder &#61; JWT. create ( ) ; map. forEach ( ( k, v) -> { builder. withClaim ( k, v) ; } ) ; Calendar instance &#61; Calendar . getInstance ( ) ; instance. add ( Calendar . DATE, 7 ) ; builder. withExpiresAt ( instance. getTime ( ) ) ; String token &#61; builder. sign ( Algorithm . HMAC256 ( SECRET) ) ; return token; } public static DecodedJWT verify ( String token) { DecodedJWT decodedJWT &#61; JWT. require ( Algorithm . HMAC256 ( SECRET) ) . build ( ) . verify ( token) ; return decodedJWT; } }
3 写拦截器
&#64;Slf4j public class JWTInterceptor implements HandlerInterceptor { &#64;Override public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token &#61; request. getHeader ( "token" ) ; log. info ( "当前token为&#xff1a;{}" , token) ; Map < String , Object > map &#61; new HashMap < > ( ) ; try { JWTUtils . verify ( token) ; return true ; } catch ( SignatureVerificationException e) { e. printStackTrace ( ) ; map. put ( "msg" , "签名不一致" ) ; } catch ( TokenExpiredException e) { e. printStackTrace ( ) ; map. put ( "msg" , "令牌过期" ) ; } catch ( AlgorithmMismatchException e) { e. printStackTrace ( ) ; map. put ( "msg" , "算法不匹配" ) ; } catch ( InvalidClaimException e) { e. printStackTrace ( ) ; map. put ( "msg" , "失效的payload" ) ; } catch ( Exception e) { e. printStackTrace ( ) ; map. put ( "msg" , "token无效" ) ; } map. put ( "state" , false ) ; String json &#61; new ObjectMapper ( ) . writeValueAsString ( map) ; response. setContentType ( "application/json;charset&#61;UTF-8" ) ; response. getWriter ( ) . println ( json) ; return false ; } }
4 写配置类&#xff0c;就是对哪些请求进行拦截
&#64;Configuration public class InterceptorConfig implements WebMvcConfigurer { &#64;Override public void addInterceptors ( InterceptorRegistry registry) { registry. addInterceptor ( new JWTInterceptor ( ) ) . addPathPatterns ( "/user/test" ) . excludePathPatterns ( "/user/login" ) ; } }
5 写controller
&#64;RestController &#64;Slf4j public class UserController { &#64;Resource private UserService userService; &#64;GetMapping ( "/user/login" ) public Map < String , Object > login ( User user) { log. info ( "用户名&#xff1a;{}" , user. getName ( ) ) ; log. info ( "password: {}" , user. getPassword ( ) ) ; Map < String , Object > map &#61; new HashMap < > ( ) ; try { User userDB &#61; userService. login ( user) ; Map < String , String > payload &#61; new HashMap < > ( ) ; payload. put ( "id" , userDB. getId ( ) ) ; payload. put ( "name" , userDB. getName ( ) ) ; String token &#61; JWTUtils . getToken ( payload) ; map. put ( "state" , true ) ; map. put ( "msg" , "登录成功" ) ; map. put ( "token" , token) ; return map; } catch ( Exception e) { e. printStackTrace ( ) ; map. put ( "state" , false ) ; map. put ( "msg" , e. getMessage ( ) ) ; map. put ( "token" , "" ) ; } return map; } &#64;PostMapping ( "/user/test" ) public Map < String , Object > test ( HttpServletRequest request) { String token &#61; request. getHeader ( "token" ) ; DecodedJWT verify &#61; JWTUtils . verify ( token) ; String id &#61; verify. getClaim ( "id" ) . asString ( ) ; String name &#61; verify. getClaim ( "name" ) . asString ( ) ; log. info ( "用户id&#xff1a;{}" , id) ; log. info ( "用户名: {}" , name) ; Map < String , Object > map &#61; new HashMap < > ( ) ; map. put ( "state" , true ) ; map. put ( "msg" , "请求成功" ) ; return map; } }
以后在请求头里面加上token才可以请求成功