SpringBoot 使用jwt进行身份验证的方法示例
这里只供参考,比较使用jwt方式进行身份验证感觉不好,最不行的就是不能退出
登陆时设定多长过期时间,只能等这个时间过了以后才算退出,服务端只能验证请求过来的token是否通过验证
Code:
/** *Createdbyqhongon2018/6/715:34 *标注该注解的,就不需要登录 **/ @Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public@interfaceAuthIgnore{ }
LoginUser:
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public@interfaceLoginUser{ }
JwtUtil:
@ConfigurationProperties(prefix="jwt") @Component publicclassJwtUtils{ privateLoggerlogger=LoggerFactory.getLogger(getClass()); privateStringsecret; privatelongexpire; privateStringheader; /** *生成jwttoken */ publicStringgenerateToken(longuserId){ DatenowDate=newDate(); //过期时间 DateexpireDate=newDate(nowDate.getTime()+expire*1000); returnJwts.builder() .setHeaderParam("typ","JWT") .setSubject(userId+"") .setIssuedAt(nowDate) .setExpiration(expireDate) .signWith(io.jsonwebtoken.SignatureAlgorithm.HS512,secret) .compact(); } publicClaimsgetClaimByToken(Stringtoken){ try{ returnJwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); }catch(Exceptione){ logger.debug("validateistokenerror",e); returnnull; } } /** *token是否过期 *@returntrue:过期 */ publicbooleanisTokenExpired(Dateexpiration){ returnexpiration.before(newDate()); } publicStringgetSecret(){ returnsecret; } publicvoidsetSecret(Stringsecret){ this.secret=secret; } publiclonggetExpire(){ returnexpire; } publicvoidsetExpire(longexpire){ this.expire=expire; } publicStringgetHeader(){ returnheader; } publicvoidsetHeader(Stringheader){ this.header=header; } }
application.properties配置:
#加密秘钥 jwt.secret=f4e2e52034348f86b67cde581c0f9eb5 #token有效时长,单位秒 jwt.expire=60000 jwt.header=token
拦截器:
/** *Createdbyqhongon2018/6/715:36 **/ @Component publicclassAuthorizationInterceptorextendsHandlerInterceptorAdapter{ @Autowired privateJwtUtilsjwtUtils; publicstaticfinalStringUSER_KEY="userId"; @Override publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{ AuthIgnoreannotation; if(handlerinstanceofHandlerMethod){ annotation=((HandlerMethod)handler).getMethodAnnotation(AuthIgnore.class); }else{ returntrue; } //如果有@AuthIgnore注解,则不验证token if(annotation!=null){ returntrue; } //获取用户凭证 Stringtoken=request.getHeader(jwtUtils.getHeader()); if(StringUtils.isBlank(token)){ token=request.getParameter(jwtUtils.getHeader()); } //token凭证为空 if(StringUtils.isBlank(token)){ thrownewAuthException(jwtUtils.getHeader()+"不能为空",HttpStatus.UNAUTHORIZED.value()); } Claimsclaims=jwtUtils.getClaimByToken(token); if(claims==null||jwtUtils.isTokenExpired(claims.getExpiration())){ thrownewAuthException(jwtUtils.getHeader()+"失效,请重新登录",HttpStatus.UNAUTHORIZED.value()); } //设置userId到request里,后续根据userId,获取用户信息 request.setAttribute(USER_KEY,Long.parseLong(claims.getSubject())); returntrue; } }
注解拦截:
@Component publicclassLoginUserHandlerMethodArgumentResolverimplementsHandlerMethodArgumentResolver{ @Autowired privateUserServiceuserService; @Override publicbooleansupportsParameter(MethodParameterparameter){ returnparameter.getParameterType().isAssignableFrom(User.class)&¶meter.hasParameterAnnotation(LoginUser.class); } @Override publicObjectresolveArgument(MethodParameterparameter,ModelAndViewContainercontainer, NativeWebRequestrequest,WebDataBinderFactoryfactory)throwsException{ //获取用户ID Objectobject=request.getAttribute(AuthorizationInterceptor.USER_KEY,RequestAttributes.SCOPE_REQUEST); if(object==null){ returnnull; } //获取用户信息 Useruser=userService.selectById((Long)object); returnuser; } }
WebConfig:
@Configuration publicclassWebConfigextendsWebMvcConfigurerAdapter{ @Autowired privateAuthorizationInterceptorauthorizationInterceptor; @Autowired privateLoginUserHandlerMethodArgumentResolverloginUserHandlerMethodArgumentResolver; @Override publicvoidaddInterceptors(InterceptorRegistryregistry){ registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**"); } @Override publicvoidaddArgumentResolvers(ListargumentResolvers){ argumentResolvers.add(loginUserHandlerMethodArgumentResolver); } }
Login:
@PostMapping("/login") @AuthIgnore publicRlogin2(@RequestBodyUseru){ //用户登录 longuserId=userService.addUser(u); //生成token Stringtoken=jwtUtils.generateToken(userId); Mapmap=newHashMap<>(); map.put("token",token); map.put("expire",jwtUtils.getExpire()); returnR.ok(map); }
LoginUser注解使用:
@RequestMapping(value="/query2",method=RequestMethod.POST) publicUserQuery2(@LoginUserUseru){ returnu; }
https://www.nhooo.com/article/153172.htm
https://gitee.com/renrenio/renren-fast
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。