@PostMapping("/login")
public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
User loginUser = userService.findByUserName(username);
if (loginUser == null) {
return Result.error("用户名错误");
}
if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
Map<String, Object> claims = new HashMap<>();
claims.put("id", loginUser.getId());
claims.put("username", loginUser.getUsername());
String token = JwtUtil.genToken(claims);
return Result.success(token);
}
return Result.error("密码错误");
}
定义了一种简洁的、自包含的格式,用于通信双方以json数据格式安全的传输信息。
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.3.0</version>
</dependency>
JwtUtil
package com.heo.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.util.Date;
import java.util.Map;
public class JwtUtil {
private static final String KEY = "itheima";
//接收业务数据,生成token并返回
public static String genToken(Map<String, Object> claims) {
return JWT.create()
.withClaim("claims", claims)
.withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))
.sign(Algorithm.HMAC256(KEY));
}
//接收token,验证token,并返回业务数据
public static Map<String, Object> parseToken(String token) {
return JWT.require(Algorithm.HMAC256(KEY))
.build()
.verify(token)
.getClaim("claims")
.asMap();
}
}
ArticleController
@RestController
@RequestMapping("/article")
public class ArticleController {
@GetMapping("/list")
public Result<String> list(/*@RequestHeader(name = "Authorization") String token, HttpServletResponse response*/) {
/*try {
Map<String, Object> claims = JwtUtil.parseToken(token);
return Result.success("所有的文章。。。");
} catch (Exception e) {
response.setStatus(401);
return Result.error("未登录");
}*/
return Result.success("所有的文章。。。");
}
}
一般情况下,我们需要写成全局登录响应拦截器。
interceptor/LoginInterceptor
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
try {
Map<String, Object> claims = JwtUtil.parseToken(token);
return true;
} catch (Exception e) {
response.setStatus(401);
return false;
}
}
}
然后进行全局配置
config/WebConfig
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login", "user/register");
}
}