springboot实现token
时间: 2023-10-23 12:12:41 浏览: 92
Spring Boot 可以很方便地实现 Token 鉴权,具体可以按照以下步骤来实现:
1. 在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
2. 创建一个 TokenUtil 工具类,用于生成 Token 和解析 Token:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class TokenUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
// 生成 Token
public String generateToken(String username) {
Date now = new Date();
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(new Date(now.getTime() + expiration * 1000))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
// 解析 Token
public Claims getClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
}
```
3. 创建一个 TokenInterceptor 拦截器,用于拦截需要鉴权的请求:
```java
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private TokenUtil tokenUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
if (token == null) {
throw new RuntimeException("未登录,请先登录");
}
Claims claims = tokenUtil.getClaimsFromToken(token);
String username = claims.getSubject();
if (username == null) {
throw new RuntimeException("未登录,请先登录");
}
return true;
}
}
```
4. 在需要鉴权的接口上添加 @Interceptor 注解,指定 TokenInterceptor 拦截器:
```java
@RestController
public class UserController {
@GetMapping("/user")
@Interceptor(TokenInterceptor.class)
public User getUser() {
return userService.getUser();
}
}
```
以上就是 Spring Boot 实现 Token 鉴权的基本步骤。当然,具体实现还需要根据实际需求进行调整。
阅读全文