依赖
<!-- security依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- jwt依赖-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
生成令牌(荷载)
package com.itbignyi.server.config.security;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: itbignyi
* @Date: 2024-01-22-21:07
* @Description: JwtTokenUtil
*/
@Component
public class JwtTokenUtil {
/**
* 荷载的token信息
*/
private static final String CLAIM_KEY_USERNAME = "sub";
private static final String CLAIM_KEY_CREATED = "created";
/**
* 密钥及失效时间
*/
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
/**
* 根据用户信息生成token
* @param userDetails
* @return
*/
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
/**
* 从token中获取用户信息
* @param token
* @return
*/
public String getUsernameFromToken(String token) {
String username;
try {
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
}
return username;
}
/**
* 从token中获取荷载
* @param token
* @return
*/
private Claims getClaimsFromToken(String token) {
Claims claims = null;
try {
claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
e.printStackTrace();
}
return claims;
}
/**
* 校验token
* @param token
* @param userDetails
* @return
*/
public boolean validateToken(String token, UserDetails userDetails) {
String username = getUsernameFromToken(token);
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
/**
* 判断token是否过期
* @param token
* @return
*/
private boolean isTokenExpired(String token) {
Date expireDate = getExpiredDateFromToken(token);
return expireDate.before(new Date());
}
/**
* 从token中获取过期时间
* @param token
* @return
*/
private Date getExpiredDateFromToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims.getExpiration();
}
/**
* 判断token是否可以刷新
* @param token
* @return
*/
public boolean canRefresh(String token) {
return !isTokenExpired(token);
}
/**
* 生成新的token(刷新)
* @param token
* @return
*/
public String refreshToken(String token) {
Claims claims = getClaimsFromToken(token);
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
/**
* 根据荷载生成token
* @param claims
* @return
*/
private String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.ES512, secret)
.compact();
}
/**
* 生成token失效时间
* @return
*/
private Date generateExpirationDate() {
return new Date(System.currentTimeMillis() + expiration * 1000);
}
}
配置
#jwt
jwt:
tokenHeader: Authorization
# 密钥
secret: yeb-secret
# 超限制时间
expiration: 604800
# 负载开头
tokenHead: Bearer
返回公共对象
package com.itbignyi.server.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author: itbignyi
* @Date: 2024-01-23-11:25
* @Description: 公共返回对象
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RespBean {
private Long code;
private String message;
private Object data;
/**
* 成功返回
*
* @param message
* @return
*/
public static RespBean success(String message) {
return new RespBean(200L, message, null);
}
/**
* 成功返回
*
* @param message
* @param data
* @return
*/
public static RespBean success(String message, Object data) {
return new RespBean(200L, message, data);
}
/**
* 失败返回
*
* @param message
* @return
*/
public static RespBean error(String message) {
return new RespBean(500L, message, null);
}
/**
* 失败返回
*
* @param message
* @param data
* @return
*/
public static RespBean error(String message, Object data) {
return new RespBean(500L, message, data);
}
}
用户登录描述实体类
package com.itbignyi.server.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @Author: itbignyi
* @Date: 2024-01-23-14:07
* @Description: 用户登录描述实体类
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="AdminLogin对象", description="")
public class AdminLoginParam {
@ApiModelProperty(value = "用户名",required = true)
private String username;
@ApiModelProperty(value = "密码",required = true)
private String password;
}