1.jwt简介
2.使用jwt
2.1添加依赖
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
2.2 生成token
// 使用jwt规则生成token字符串
JwtBuilder builder = Jwts.builder();
HashMap<String,Object> map = new HashMap<>();
String token = builder.setSubject(phone) // 主题,token携带的数据
.setIssuedAt(new Date()) // 设置token的生成时间
.setId(users.get(0).getUserId() + "") // 设置用户id为tokenid
.setClaims(map) // map中存放用户的角色权限信息
.setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) // 设置token过期时间
.signWith(SignatureAlgorithm.HS256, Base64Utils.stringcode) // 设置加密方式和加密密码
.compact();
2.3 校验token
// 验证token
JwtParser parser = Jwts.parser();
// 解析token的SiginKey必须和生成token时设置密码时的一致
parser.setSigningKey(Base64Utils.stringcode);
try {
// 如果token正确(密码正确,有效期内)则正常执行,否则抛出异常
Jws<Claims> claimsJws = parser.parseClaimsJws(token);
// 获取token中用户数据
Claims body = claimsJws.getBody();
/// 获取生成token设置的subject
String subject = body.getSubject();
// 获取生成token时存储的Claim的map中的值,其中key1为map中的键
String key1 = body.get("key1", String.class);
// 验证成功,进行之后的处理
} catch (Exception e) {
// 对于密码不正确/token过期的处理
System.out.println(e);
}
2.4 拦截器校验Token
package com.computerskills.competition.interceptor;
import com.computerskills.competition.utils.Base64Utils;
import com.computerskills.competition.vo.ResStatus;
import com.computerskills.competition.vo.ResultVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.RescaleOp;
import java.io.IOException;
import java.io.PrintWriter;
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String method = request.getMethod();
// 针对于预检请求
if ("OPTIONS".equalsIgnoreCase(method)) {
return true;
}
String token = request.getHeader("token");
if(token == null) {
doResponse(response,new ResultVo(ResStatus.Err,"请先登录",null));
} else {
try {
// 验证token
JwtParser parser = Jwts.parser();
// 解析token的SiginKey必须和生成token时设置密码时的一致
parser.setSigningKey(Base64Utils.stringcode);
// 如果token正确(密码正确,有效期内)则正常执行,否则抛出异常
Jws<Claims> claimsJws = parser.parseClaimsJws(token);
return true;
} catch (ExpiredJwtException e) {
doResponse(response,new ResultVo(ResStatus.Err,"登录已过期,请重新登录",null));
} catch (UnsupportedJwtException e) {
doResponse(response,new ResultVo(ResStatus.Err,"Token不合法",null));
} catch (Exception e) {
doResponse(response,new ResultVo(ResStatus.Err,"请先登录",null));
}
}
return false;
}
private void doResponse(HttpServletResponse response, ResultVo resultVo) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
String s = new ObjectMapper().writeValueAsString(resultVo);
writer.print(s);
writer.flush();
writer.close();
}
}
package com.computerskills.competition.config;
import com.computerskills.competition.interceptor.CheckTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private CheckTokenInterceptor checkTokenInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器到mvc中
registry.addInterceptor(checkTokenInterceptor)
.addPathPatterns("/role/**") // 拦截的路径-------路径不包括:context path '/used'
.excludePathPatterns("/user/**"); // 不拦截的路径
}
}