在Spring Boot中实现登录接口、Token和拦截器的步骤如下:
- 引入依赖(pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
- 配置JWT(JwtUtil.java):
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.util.Date;
public class JwtUtil {
private static final String SECRET = "your_secret_key";
public static String generateToken(String username) {
return JWT.create()
.withSubject(username)
.withIssuedAt(new Date())
.sign(Algorithm.HMAC_SHA_256(SECRET));
}
public static String getUsernameFromToken(String token) {
return JWT.require(Algorithm.HMAC_SHA_256(SECRET))
.build()
.verify(token)
.getSubject();
}
}
- 创建拦截器(JwtInterceptor.java):
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JwtInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
final String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
try {
String username = JwtUtil.getUsernameFromToken(token);
// 验证token有效性,例如检查是否过期等
// ...
return true;
} catch (Exception e) {
// 无效token处理
// ...
return false;
}
}
return false;
}