JWT--实现登录态
解析token
https://jwt.io/
https://blog.csdn.net/cxmengxin/article/details/119279848
maven依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
测试
package com;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.text.SimpleDateFormat;
import java.util.Date;
@SpringBootTest
class JjwtdemoApplicationTests {
// 创建token
@Test
public void testCreateToken(){
//当前系统时间
long now =System.currentTimeMillis();
// 过期时间一分钟
long exp =now+60*1000;
//创建JwtBuilder对象
JwtBuilder jwtBuilder = Jwts.builder()
//声明的标识{"jti":"8888"}
.setId("8888")
//主体,用户{"sub":"Rose"}
.setSubject("Rose")
//创建日期{"ita":"xxxxxx"}
.setIssuedAt(new Date())
// xxxx是盐
.signWith(SignatureAlgorithm.HS256,"xxxx")
//设置过期时间
.setExpiration(new Date(exp))
//自定义申明
.claim("roles","admin")
.claim("logo","xxx.jpg");
// 另外一种方法,直接传入map
// .addClaims(map)
//获取jwt的token
String token = jwtBuilder.compact();
System.out.println(token);
// //解析token
// System.out.println("=================");
// String[] splist =token.split("\\.");
// System.out.println(splist);
// System.out.println(Base64Codec.BASE64.decodeToString(splist[0]));
// System.out.println(Base64Codec.BASE64.decodeToString(splist[1]));
//// 签名部分
// System.out.println(Base64Codec.BASE64.decodeToString(splist[2]));
}
// 解析token
@Test
public void testParseToken(){
String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODg4Iiwic3ViIjoiUm9zZSIsImlhdCI6MTY0OTIzNDg3OSwiZXhwIjoxNjQ5MjM0OTM5LCJyb2xlcyI6ImFkbWluIiwibG9nbyI6Inh4eC5qcGcifQ.y3OQjS4kxRXU3NOcdNaCWT9_1M5sagQoUCqyfZc9_sU";
//解析token
Claims claims = Jwts.parser()
.setSigningKey("xxxx")
.parseClaimsJws(token)
.getBody();
System.out.println("id:"+claims.getId());
System.out.println("subject:"+claims.getSubject());
System.out.println("issuedAt:"+claims.getIssuedAt());
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("签发时间:"+simpleDateFormat.format(claims.getIssuedAt()));
System.out.println("过期时间:"+simpleDateFormat.format(claims.getExpiration()));
System.out.println("当前时间:"+simpleDateFormat.format(new Date()));
//获取自定义
System.out.println("roles:"+claims.get("roles"));
System.out.println("logo:"+claims.get("logo"));
}
程序员青戈 教的 https://www.bilibili.com/video/BV1U44y1W77D?p=16&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea
<!-- JWT -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
目录:
control. ----
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/login")
public Result login(@RequestBody UserDTO userDTO) {
String username = userDTO.getUsername();
String password = userDTO.getPassword();
if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
return Result.error(Constants.CODE_400, "参数错误");
}
UserDTO dto = userService.login(userDTO);
return Result.success(dto);
}
}
login的实现类代码 --------这里涉及统一规范接口返回信息: https://www.cnblogs.com/kaibindirver/p/16358813.html
@Override
public UserDTO login(UserDTO userDTO) {
User one = getUserInfo(userDTO);
if (one != null) {
BeanUtil.copyProperties(one, userDTO, true);
// 设置token
String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
userDTO.setToken(token);
String role = one.getRole(); // ROLE_ADMIN
// 设置用户的菜单列表
List<Menu> roleMenus = getRoleMenus(role);
userDTO.setMenus(roleMenus);
return userDTO;
} else {
throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
}
}
TokenUtils
package com.qingge.springboot.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.qingge.springboot.entity.User;
import com.qingge.springboot.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
public class TokenUtils {
private static IUserService staticUserService;
@Resource
private IUserService userService;
@PostConstruct
public void setUserService() {
staticUserService = userService;
} //静态方法不可使用非静态属性 所以要有这一步
/**
* 生成token
*
* @return
*/
public static String genToken(String userId, String sign) {
return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
.withExpiresAt(DateUtil.offsetHour(new Date(), 60)) // 2小时后token过期
.sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
}
/**
* 获取当前登录的用户信息
*
* @return user对象
*/
public static User getCurrentUser() {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
if (StrUtil.isNotBlank(token)) {
String userId = JWT.decode(token).getAudience().get(0);
return staticUserService.getById(Integer.valueOf(userId));
}
} catch (Exception e) {
return null;
}
return null;
}
}
InterceptorConfig
package com.qingge.springboot.config;
import com.qingge.springboot.config.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
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 {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**") // 拦截所有请求,通过判断token是否合法来决定是否需要登录
.excludePathPatterns("/user/login", "/user/register", "/**/export", "/**/import", "/file/**",
"/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/api", "/api-docs", "/api-docs/**")
.excludePathPatterns( "/**/*.html", "/**/*.js", "/**/*.css", "/**/*.woff", "/**/*.ttf"); // 放行静态文件
}
@Bean
public JwtInterceptor jwtInterceptor() {
return new JwtInterceptor();
}
}
JwtInterceptor ---------前端获取的token是存在localStorage里面 参考: https://www.cnblogs.com/kaibindirver/p/13674893.html
package com.qingge.springboot.config.interceptor;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.qingge.springboot.common.Constants;
import com.qingge.springboot.config.AuthAccess;
import com.qingge.springboot.entity.User;
import com.qingge.springboot.exception.ServiceException;
import com.qingge.springboot.service.IUserService;
import com.qingge.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private IUserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String token = request.getHeader("token");
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
} else {
HandlerMethod h = (HandlerMethod) handler;
AuthAccess authAccess = h.getMethodAnnotation(AuthAccess.class);
if (authAccess != null) {
return true;
}
}
// 执行认证
if (StrUtil.isBlank(token)) {
throw new ServiceException(Constants.CODE_401, "无token,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录");
}
// 根据token中的userid查询数据库
User user = userService.getById(userId);
if (user == null) {
throw new ServiceException(Constants.CODE_401, "用户不存在,请重新登录");
}
// 用户密码加签验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token); // 验证token
} catch (JWTVerificationException e) {
throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录");
}
// 获取用户信息,调用TokenUtils类里面的静态方法
System.out.println(TokenUtils.getCurrentUser().getNickname()+"++++++++++++++++++++++");
return true;
}
}
上面的例子是用用户的密码做盐! 其实可以写死一个,然后生产的令牌 其实可以再存一份到redis 然后,然后可以查询是否存在啥的,可以加了一层控制有效时间(手动删掉,查到不存在逼退) 和 单点多点登陆等操作(单点,存在这个user_id的token,再登陆就干掉重新写入一个)