本文主要是介绍使用jwt实现登录验证,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
jwt工具类
public class JwtUtil {public static String key="mykey";public static String genToken(String username) {JWTCreator.Builder builder = JWT.create();Map<String, Object> headers=new HashMap<>();headers.put("typ","jwt");headers.put("alg","hs256");Map<String, Object> claims=new HashMap<>();claims.put("username",username);String token=builder.withHeader(headers).withClaim("user",claims).withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))//设置失效日期,12小时后过期.sign(Algorithm.HMAC256(key));//加密时所用的密钥return token;}public static boolean parseToken(String token){JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key))//算法HMAC256要与上面的相同,mykey也要一样.build();try{DecodedJWT decodedJWT = verifier.verify(token);//验证tokenreturn true;}catch (Exception e){e.printStackTrace();return false;}}
}
用户接口中生成令牌
@RestController
@RequestMapping("/user")
public class UserController {@PostMapping("/login")public Result login(String username,String password){//参数校验//校验用户名和密码是否为5~16字符串if(username!=null &&StringUtils.hasLength(username) && username.length()>=5 && username.length()<=16&& password!=null &&StringUtils.hasLength(password) && password.length()>=5 && password.length()<=16){//验证用户名是否存在//验证密码是否正确if("******".equals(username) && "******".equals(password)){//生成tokenString token = JwtUtil.genToken(username);return Result.success(token);}else{return Result.error("用户名或密码错误");}}else{return Result.error("用户名或密码长度必须在5~16范围内");}}
}
拦截器中验证令牌
@Component//拦截器放入容器中,方便WebMvcConfig注入
public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {//判断请求头是否携带了tokenString token = request.getHeader("Authorization");if (token==null){//没有携带则拦截,并设置http状态码为401response.setStatus(401);return false;}else{//携带了令牌//验证令牌boolean isPass = JwtUtil.parseToken(token);if(isPass){//验证通过则放行return true;}else{//验证不通过也拦截response.setStatus(401);return false;}}}
}
注册拦截器,配置拦截哪些请求,不拦截哪些请求
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Autowiredprivate LoginInterceptor loginInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login","/user/register");//放行登录和注册请求}
}
文章接口
@RestController
@RequestMapping("/article")
public class ArticleController {@GetMapping("/list")public Result list(){return Result.success("所有文章列表");}
}
测试:使用postman请求文章接口
为postman的collection设置统一header
这篇关于使用jwt实现登录验证的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!