需求: 原接口返回的直接是用户信息json串 现在要改成jwt进行加密 获取信息接口放行 其他接口拦截校验jwtToken是否有效
jwtTokenUtil
package com.hzt.intellect.utils;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class JwtUtil {
public static String createJWT(String jwtSec, long ttlMillis, String userInfo) {
JSONObject jsonObject = JSONUtil.parseObj(userInfo);
if (!jsonObject.getBool("success")) {
return userInfo;
}
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder builder = Jwts.builder()
.setId(UUID.randomUUID().toString())
.setIssuedAt(now)
.setSubject(userInfo)
.signWith(signatureAlgorithm, jwtSec.getBytes(StandardCharsets.UTF_8));
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
jsonObject.set("token", builder.compact());
return JSONUtil.toJsonStr(jsonObject);
}
public static Claims parseJWT(String jwtSec, String token) {
Claims claims = Jwts.parser()
.setSigningKey(jwtSec.getBytes(StandardCharsets.UTF_8))
.parseClaimsJws(token).getBody();
return claims;
}
}
过滤器LindTokenAuthenticationFilter
package com.hzt.intellect.filter;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.hzt.intellect.utils.JwtUtil;
import com.risen.base.frame.constant.ResultEnum;
import com.risen.base.frame.model.Result;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.thymeleaf.util.StringUtils;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Component
public class LindTokenAuthenticationFilter extends OncePerRequestFilter {
@Value("${jwt.jwtSec}")
private String jwtSec;
@Value("${jwt.tokenName}")
private String tokenName;
@Value("${jwt.releasePath}")
private String releasePath;
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
List<String> releasePathList = new ArrayList<>(Arrays.asList(releasePath.split(",")));
String path = URLUtil.getPath(request.getRequestURI());
String result = path.substring(path.indexOf("/", path.indexOf("/") + 1));
if (releasePathList.contains(result)) {
filterChain.doFilter(request, response);
return;
}
String token = request.getHeader(tokenName);
if (StringUtils.isEmpty(token)) {
token = request.getParameter(tokenName);
}
if (StringUtils.isEmpty(token)) {
response.setStatus(501);
response.setContentType(ContentType.JSON.getValue());
Result<String> resultMsg = Result.buildResult(ResultEnum.PERMISSION_NO_ACCESS, "token不能为空");
response.getWriter().write(JSONUtil.toJsonStr(resultMsg));
return;
}
try {
JwtUtil.parseJWT(jwtSec, token);
} catch (ExpiredJwtException e) {
log.error("jwtToken过期:{}", token);
response.setStatus(501);
response.setContentType(ContentType.JSON.getValue());
Result<String> resultMsg = Result.buildResult(ResultEnum.TOKEN_ILLEGAL, "token过期");
response.getWriter().write(JSONUtil.toJsonStr(resultMsg));
return;
} catch (Exception e) {
log.error("jwtToken解析异常token:{}, 异常原因:{}", token, e);
response.setStatus(501);
response.setContentType(ContentType.JSON.getValue());
Result<String> resultMsg = Result.buildResult(ResultEnum.AUTHENTICATION_NO_SUCCESS, "token异常");
response.getWriter().write(JSONUtil.toJsonStr(resultMsg));
return;
}
filterChain.doFilter(request, response);
}
}
配置
|