JwtUtil
package com.lin.springboot01.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 = "liner2332";
//接受业务数据,生成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();
}
}
UserController
@PostMapping("/login")
public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
//根据用户名查询用户
User loginUser = userService.findByName(username);
//判断该用户是否存在
if (loginUser==null){
return Result.error("用户名错误");
}
//判断密码是否正确
if (MD5Utils.string2MD5(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("密码错误");
}