1.在cfg(configration)包中增加JwtCfg 类,它声明了一个@Bean ,用于生成一个过滤器类,并且对/user 链接下的所有资源访问进行JWT的验证。
@Configuration public class JwtCfg { @Bean public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new JwtFilter()); registrationBean.addUrlPatterns("/secure/*"); return registrationBean; } }2.在entity包中写一个JwtFilter 类,它声明了一个JWT过滤器类,从Http请求中提取JWT的信息,并使用了”secretkey”这个密匙对JWT进行验证。
public class JwtFilter extends GenericFilterBean { public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { // Change the req and res to HttpServletRequest and HttpServletResponse final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; // Get authorization from Http request final String authHeader = request.getHeader("authorization"); // If the Http request is OPTIONS then just return the status code 200 // which is HttpServletResponse.SC_OK in this code if ("OPTIONS".equals(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); chain.doFilter(req, res); } // Except OPTIONS, other request should be checked by JWT else { // Check the authorization, check if the token is started by "Bearer " if (authHeader == null || !authHeader.startsWith("Bearer ")) { throw new ServletException("Missing or invalid Authorization header"); } // Then get the JWT token from authorization final String token = authHeader.substring(7); try { // Use JWT parser to check if the signature is valid with the Key "secretkey" final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody(); // Add the claim to request header request.setAttribute("claims", claims); } catch (final SignatureException e) { throw new ServletException("Invalid token"); } chain.doFilter(req, res); } } }3.在controller中的登陆方法中,登陆完成后自动生成token作为返回。
@PostMapping public String login(@RequestBody() ReqPerson reqPerson) throws ServletException { // Check if username and password is null if (reqPerson.getUsername() == "" || reqPerson.getUsername() == null || reqPerson.getPassword() == "" || reqPerson.getPassword() == null) throw new ServletException("Please fill in username and password"); // Check if the username is used if(personService.findPersonByUsername(reqPerson.getUsername()) == null || !reqPerson.getPassword().equals(personService.findPersonByUsername(reqPerson.getUsername()).getPassword())){ throw new ServletException("Please fill in username and password"); } // Create Twt token String jwtToken = Jwts.builder().setSubject(reqPerson.getUsername()).claim("roles", "member").setIssuedAt(new Date()) .signWith(SignatureAlgorithm.HS256, "secretkey").compact(); return jwtToken; }