1. token jwt配置
1.1. pom
<!-- token验证 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
1.2. 代码
1.2.1. 生成token
@Configuration
public class JwtToken {
/**
* 生成jwt token
*/
public Token generateToken(Long userId) {
Date date = new Date();
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Date expiration = DateUtils.addDays(new Date(), 3);
String token = Jwts.builder()
// 设置header
.setHeaderParam("typ", "JWT")
// 设置签发时间
.setHeaderParam("alg", "HS256").setIssuedAt(date)
.setExpiration(expiration)
// 设置内容
.claim("userId", String.valueOf(userId))
// 设置签发人
.setIssuer("lll")
// 签名,需要算法和key
.signWith(signatureAlgorithm, "xxxxx").compact();
return new Token().setExpireTime(expiration).setToken(token).setUserId(userId);
}
}
1.2.2. token拦截器
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private ITokenService tokenService;
@Autowired
private JwtToken jwtToken;
private Map<Long, Token> tokenMap = new ConcurrentHashMap<>();
public Set<String> passPath = new HashSet<>();
/**
* 添加token
*
* @param userId
* @return
*/
public Token addToken(Long userId) {
Token token = jwtToken.generateToken(userId);
tokenMap.put(userId, token);
Token tk = tokenService.getById(userId);
if (tk != null) {
tokenService.updateById(token);
} else {
tokenService.save(token);
}
return token;
}
public TokenInterceptor() {
init();
}
@Value("${token.enabled:false}")
public boolean openToken;
/**
* token开关
*
* @param openToken
*/
public void setOpenToken(boolean openToken) {
this.openToken = openToken;
}
@PostConstruct
private void init() {
passPath.add("/fund/user/");
passPath.add("/fund/user/login");
}
private boolean isFilter(String uri) {
if (!openToken) {
return true;
}
return passPath.stream().anyMatch(s -> s.equals(uri));
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
//普通路径放行
if (isFilter(request.getRequestURI())) {
return true;
}
//权限路径拦截
response.setCharacterEncoding("UTF-8");
final String headerToken = request.getHeader("x-access-token");
//判断请求信息
if (null == headerToken || "".equals(headerToken.trim())) {
response.getWriter().write("用户未登录,请先登录");
return false;
}
//解析Token信息
try {
Claims claims = Jwts.parser().setSigningKey("beikbank@fund").parseClaimsJws(headerToken).getBody();
String tokenUserId = (String) claims.get("userId");
Long itokenUserId = Long.parseLong(tokenUserId);
//根据客户Token查找缓存Token
Token myToken = tokenMap.get(itokenUserId);
//缓存没有Token记录
if (null == myToken) {
Token token = tokenService.getById(itokenUserId);
if (token != null) {
if (judgeToken(response, headerToken, claims, itokenUserId, token)) {
return false;
}
}
return true;
}
if (judgeToken(response, headerToken, claims, itokenUserId, myToken)) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
response.getWriter().write("发生异常,请重新登录");
return false;
}
//最后才放行
return true;
}
private boolean judgeToken(HttpServletResponse response, String headerToken, Claims claims, Long itokenUserId, Token myToken) throws IOException {
//缓存Token与客户Token比较
if (!headerToken.equals(myToken.getToken())) {
response.getWriter().write("token不正确,请重新登录");
return true;
}
//判断Token过期
Date tokenDate = claims.getExpiration();
if (tokenDate.before(new Date())) {
tokenMap.remove(itokenUserId);
tokenService.removeById(itokenUserId);
response.getWriter().write("token过期,请重新登录");
return true;
}
return false;
}
}
1.2.3. 设置token
- token设置,在登录时设置
@Autowired
private TokenInterceptor tokenInterceptor;
@ApiOperation(value = "用户登录", notes = "用户登录")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity login( @RequestBody @ApiParam(name = "user", value = "用户", required = true) @Valid User user) {
boolean result = userService.vaildLogin(user);
Token token = tokenInterceptor.addToken(user.getUserId());
return ResponseEntity.ok(result ? ok(token) : error("登录失败,请检查用户名和密码"));
}