1、新建一个拦截类
@Component public class LoginInterceptor implements HandlerInterceptor { @Autowired private JwtUtil jwtUtil; @Value("${oaTokenKeyword}") private String oaTokenKeyword; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String urlStr = request.getRequestURI(); if(urlStr.endsWith("getToken")){ return true; } String errorMessage; String token = request.getHeader("token"); if(StringUtils.isEmpty(token)){ errorMessage = "请求缺失token"; }else{ String validateTokenMessage = jwtUtil.validateToken(token,oaTokenKeyword); if(StringUtils.isEmpty(validateTokenMessage)){ return true; }else{ errorMessage = "身份验证失败!"+validateTokenMessage; } } // 返回无权限访问的消息 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized // 设置响应内容类型及字符编码 response.setContentType("text/plain; charset=UTF-8"); response.getWriter().write(errorMessage); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("2----------postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("3----------afterCompletion"); } }
2、添加一个Web MVC 配置类
注意:configure方法的http.cors().and().csrf().disable();是一定要有的,不会所有的请求,都是报401
@Configuration @EnableWebSecurity public class WebMvcConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer { @Autowired private LoginInterceptor loginInterceptor; @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(); } @Override public void addInterceptors(InterceptorRegistry registry) { //1、拦截器注册 registry.addInterceptor(loginInterceptor) .addPathPatterns("/**") ; } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.TEXT_PLAIN); } }
3、工具类JwtUtil
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.Date; @Component public class JwtUtil { private final long EXPIRATION_TIME = 30 * 60 * 1000; // 30分钟 @Value("${SECRET_KEY}") private String SECRET_KEY; public String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS256, SECRET_KEY) .compact(); } public Claims extractClaims(String token) { return Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody(); } public String extractUsername(String token) { return extractClaims(token).getSubject(); } public boolean isTokenExpired(String token) { return extractClaims(token).getExpiration().before(new Date()); } public String validateToken(String token,String userName) { try{ if(!extractUsername(token).equals(userName)){ return "token无效!"; } if(isTokenExpired(token)){ return "token超时!"; } return null; }catch (Exception e){ e.printStackTrace(); String message = e.getMessage(); if(message.contains("Current time")){ return "token超时!"; } return "token无效!"; } } }
标签:return,String,校验,springframework,token,import,public,springboot From: https://www.cnblogs.com/wwssgg/p/18458832