springboot 项目实现 token 校验
时间: 2023-08-05 08:05:56 浏览: 124
在Spring Boot项目中实现Token校验,可以通过以下步骤:
1. 在项目中引入相应的依赖,如JWT库等。
2. 创建Token的生成和校验工具类,其中生成Token的方法可以使用JWT库中的方法,校验Token的方法可以解析Token中的信息并进行校验。
3. 在需要进行Token校验的接口中,添加一个拦截器,用于拦截请求并进行Token校验。在拦截器中获取请求头中的Token信息,然后调用Token校验工具类进行校验。
4. 如果Token校验通过,则放行请求;如果Token校验失败,则返回相应的错误信息。
以下是一个简单的示例代码:
(1)pom.xml中添加JWT库的依赖:
```xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
```
(2)创建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;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtTokenUtil {
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;
public String generateToken(String username) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, username);
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
private String generateToken(Map<String, Object> claims) {
Date expirationDate = new Date(System.currentTimeMillis() + expiration * 1000);
return Jwts.builder()
.setClaims(claims)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsernameFromToken(String token) {
String username;
try {
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
}
return username;
}
public boolean validateToken(String token, String username) {
String usernameFromToken = getUsernameFromToken(token);
return usernameFromToken.equals(username) && !isTokenExpired(token);
}
private Claims getClaimsFromToken(String token) {
Claims claims;
try {
claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
claims = null;
}
return claims;
}
private boolean isTokenExpired(String token) {
Date expirationDate = getExpirationDateFromToken(token);
return expirationDate.before(new Date());
}
private Date getExpirationDateFromToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims.getExpiration();
}
}
```
(3)创建Token拦截器:
```java
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 JwtTokenInterceptor implements HandlerInterceptor {
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
String username = jwtTokenUtil.getUsernameFromToken(token);
if (username != null && jwtTokenUtil.validateToken(token, username)) {
return true;
} else {
response.getWriter().write("Token is invalid");
return false;
}
}
}
```
(4)在需要进行Token校验的接口中添加拦截器:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class MyController {
@Autowired
private JwtTokenInterceptor jwtTokenInterceptor;
@RequestMapping("/test")
public String test() {
return "Hello, world!";
}
@RequestMapping("/test2")
public String test2() {
return "Hello, world 2!";
}
@RequestMapping("/test3")
public String test3() {
return "Hello, world 3!";
}
@RequestMapping("/test4")
public String test4() {
return "Hello, world 4!";
}
@RequestMapping("/test5")
public String test5() {
return "Hello, world 5!";
}
}
```
在Spring Boot项目中实现Token校验,可以通过以上步骤实现。
阅读全文