SpringBoot 基於JWT實現登入校驗
阿新 • • 發佈:2020-08-05
1.新增依賴
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4.0</version> </dependency>
2.新增登入介面,返回前端token
@ApiOperation(value = "使用者登入") @PassToken @PostMapping(value= "/login") @ResponseBody public Object login(@RequestParam(name = "id") @ApiParam(value = "使用者id",required = true) String id, @RequestParam(name = "password") @ApiParam(value = "使用者密碼",required = true)String password) { ValueOperations<String, Object> operations = redisTemplate.opsForValue(); User user= userService.getUser(id, password); if(user==null){ return new XPFBadRequestException("使用者不存在"); } String token=getToken(user); // operations.set(user.getId(), token, 24*60*60, TimeUnit.SECONDS); return new XPFSingleResponse(token); } public String getToken(User user) { String token=""; token= JWT.create().withAudience(user.getId()) .sign(Algorithm.HMAC256(user.getPassword())); return token; }
3.新增需要標誌需要登入的註解
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface PassToken { boolean required() default true; } @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface UserLoginToken { boolean required() default false; }
4.新增HandlerInterceptor攔截器
@Component public class AuthenticationInterceptor implements HandlerInterceptor { public AuthenticationInterceptor() { System.out.println("註冊攔截器"); } @Resource private RedisTemplate<String, Object> redisTemplate; @Resource private UserService userService; @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { httpServletResponse.addHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token,showName,phoneNum"); String token = httpServletRequest.getHeader("token");// 從 http 請求頭中取出 token String id = httpServletRequest.getHeader("keyId");// 從 http 請求頭中取出 keyid // 如果不是對映到方法直接通過 if (!(object instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) object; Method method = handlerMethod.getMethod(); //檢查是否有passtoken註釋,有則跳過認證 if (method.isAnnotationPresent(PassToken.class)) { PassToken passToken = method.getAnnotation(PassToken.class); if (passToken.required()) { return true; } } //檢查有沒有需要使用者許可權的註解 if (method.isAnnotationPresent(UserLoginToken.class)) { UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class); if (userLoginToken.required()) { // 執行認證 if (token == null) { throw new RuntimeException("無token,請重新登入"); } // 獲取 token 中的 user id String userId; try { userId = JWT.decode(token).getAudience().get(0); } catch (JWTDecodeException j) { throw new RuntimeException("401"); } System.out.println("userId=="+userId); User user = userService.getUserById(userId); if (user == null) { throw new RuntimeException("使用者不存在,請重新登入"); } // 驗證 token JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build(); try { jwtVerifier.verify(token); } catch (JWTVerificationException e) { throw new RuntimeException("401"); } return true; } } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } /* * 整個請求處理完畢回撥方法,該方法也是需要當前對應的Interceptor的preHandle()的返回值為true時才會執行, * 也就是在DispatcherServlet渲染了對應的檢視之後執行。用於進行資源清理。整個請求處理完畢回撥方法。 * 如效能監控中我們可以在此記錄結束時間並輸出消耗時間,還可以進行一些資源清理,類似於try-catch-finally中的finally,但僅呼叫處理器執行鏈中*/ @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
4.1所有的攔截器的perHandler都是先執行的 和過濾器不同
5.為springmvc新增攔截器,和攔截規則
@Configuration public class ApiConfig extends WebMvcConfigurationSupport { @Autowired private AuthenticationInterceptor authenticationInterceptor; @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(this.authenticationInterceptor).addPathPatterns("/**"); super.addInterceptors(registry); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }