pom.xml
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
com.jwt.config
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public JwtInterceptor jwtInterceptor(){
return new JwtInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration registration = registry.addInterceptor(jwtInterceptor());
registration
.addPathPatterns("/jwt/**")
.excludePathPatterns("/jwt/login","/jwt/parse");
}
}
com.jwt.utils
@Slf4j
public class JwtUtils {
private static String headKey = "token";
private static String secret = "lzxTestSecret";
private static long expireTime = 1800L;
public static String generateToken(Map<String, Object> userInfoMap) {
if (Objects.isNull(userInfoMap)) {
userInfoMap = new HashMap<>(16);
}
Date expireDate = new Date(System.currentTimeMillis() + expireTime * 1000);
return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setExpiration(expireDate)
.setClaims(userInfoMap)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
public static Claims verifyAndGetClaimsByToken(String token) {
try {
return Jwts.parser().setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getHeadKey(){
return headKey;
}
}
public class JwtInterceptor extends HandlerInterceptorAdapter {
public static final String USER_INFO_KEY = "user_info_key";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader(JwtUtils.getHeadKey());
if (StringUtils.isEmpty(token)) {
token = request.getParameter(JwtUtils.getHeadKey());
}
if (StringUtils.isEmpty(token)) {
this.writerErrorMsg("401", JwtUtils.getHeadKey() + " can not be blank", response);
return false;
}
Claims claims = JwtUtils.verifyAndGetClaimsByToken(token);
if (null == claims) {
this.writerErrorMsg("401", JwtUtils.getHeadKey() + " 失效,请重新登录", response);
return false;
}
request.setAttribute(USER_INFO_KEY, claims);
return true;
}
private void writerErrorMsg(String code, String msg, HttpServletResponse response) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", msg);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JSON.toJSONString(result));
}
}
@RestController
@RequestMapping("jwt")
public class TestJwtController {
@PostMapping("login")
public String login(@RequestBody User dto) {
if ("wsl".equals(dto.getUserName()) && "123456".equals(dto.getPassword())) {
Map<String, Object> userInfoMap = new HashMap<>();
for (int i = 0; i < 10; i++) {
userInfoMap.put("userName"+i, "隔壁老王" + i);
}
String token = JwtUtils.generateToken(userInfoMap);
return token;
} else {
System.out.println("用户名或密码错误");
}
return null;
}
@GetMapping("/parse")
public Claims parse(String token){
return JwtUtils.verifyAndGetClaimsByToken(token);
}
@GetMapping("test")
public String test(HttpServletRequest request) {
Claims claims = (Claims) request.getAttribute(JwtInterceptor.USER_INFO_KEY);
if (null != claims) {
return (String) claims.get("userName");
} else {
return "fail";
}
}
}