配置JWT
pom.xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
yaml
jwt:
header: Jwt
webSocketHeader: Sec-WebSocket-Protocol
secret: sqdybffsshejbh
expiration: 2000000
jwt工具类
@Data
@Configuration
@ConfigurationProperties(prefix = "jwt")
public class JwtUtil {
/**
* 密钥
*/
private String secret;
/**
* 过期时间
*/
private Long expiration;
/**
* 头部信息
*/
private String header;
/**
* 生成jwt
*
* @return jwt串
*/
public String generateJwt(Long id,String userName) {
Map<String, Object> map = new HashMap<>();
map.put("id",id);
map.put("userName", userName);
JwtBuilder builder = Jwts.builder()
.setClaims(map) //需要放在第一个,不然这个会覆盖之前所有的设置
.setHeaderParam("byt", header)
.signWith(SignatureAlgorithm.HS256, secret)
.setExpiration(new Date(System.currentTimeMillis() + expiration));
return builder.compact();
}
/**
* 解析jwt
* @param jwt
* @return
*/
public Map<String,Object> parseJwt(String jwt) {
//获得全局的response
HttpServletResponse httpServletResponse = RequestUtil.getHttpServletResponse();
Map<String,Object> map=null;
try {
map = (Map<String,Object>)Jwts.parser().setSigningKey(secret).parse(jwt).getBody();
}catch (ExpiredJwtException e){
try {
//异常时向前端推送一个json错误信息
ResultUtil.sendResponse( httpServletResponse,ResultUtil.error(ResultEnum.THE_TOKEN_EXPIRES));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return map;
}
}
过滤器
@Slf4j
@WebFilter(urlPatterns = "/**") //url路径为 /**(所有路径) 时,触发过滤器
@Component
@Order(100)
public class UserFilter implements Filter {
private final JwtUtil jwtUtil;
public UserFilter(JwtUtil jwtUtil, ) {
this.jwtUtil = jwtUtil;
}
private final List<String> url = Arrays.asList("/user/update","/addOrDelete","/user/updateUserInfo","/user/update",""); // 需要拦截的路径
/**
* 过滤需要用户登录的操作
*
* @param servletRequest
* @param servletResponse
* @param filterChain
* @throws IOException
* @throws ServletException
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (url.contains(RequestUtil.getUrl())) {
try {
jwtUtil.parseJwt(RequestUtil.getHeader("jwt"));
filterChain.doFilter(servletRequest, servletResponse);
} catch (ExpiredJwtException e) {
ResultUtil.sendResponse((HttpServletResponse) servletResponse, ResultUtil.error(ResultEnum.THE_TOKEN_EXPIRES));
} catch (JwtException e) {
ResultUtil.sendResponse((HttpServletResponse) servletResponse, ResultUtil.error(ResultEnum.THE_TOKEN_IS_NOT_LEGITIMATE));
} catch (Exception e) {
ResultUtil.sendResponse((HttpServletResponse) servletResponse, ResultUtil.error(ResultEnum.UNKNOWN_ERROR));
}
} else {
filterChain.doFilter(servletRequest, servletResponse); //直接放行
}
}