目录
这一系列课程将包含Spring Boot 许多关键的技术和工具,包括 Mybatis-Plus、Redis、Mongodb、MinIO、Kafka、MySQL、消息队列(MQ)、OAuth2 等相关内容。
使用 Spring Boot + Hutool 实现 JWT Token 生成及拦截功能
在使用 Spring Boot 和 Hutool 实现 JWT Token 生成及拦截功能时,首先需要在项目中配置相关的依赖和属性。以下是一个简单的示例,包括了pom.xml的配置、application.properties的属性配置以及页面显示和处理逻辑代码。
添加 Maven 依赖
在 pom.xml
文件中添加 Spring Boot 和 Hutool 的相关依赖:
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Hutool工具类库 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.10</version> <!-- 使用时请替换为最新版本 -->
</dependency>
<!-- JWT依赖 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version> <!-- 使用时请替换为最新版本 -->
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
配置application.properties
在 application.properties
中配置 JWT 相关属性:
# JWT配置
jwt.secret=your-secret-key
jwt.expiration=3600 # Token过期时间,单位秒
编写核心代码
JWT Token 生成及拦截功能
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 JwtUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private long expiration;
public String generateToken(String username) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + expiration * 1000);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsernameFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
}
// 添加其他JWT验证和解析方法...
}
拦截器
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JwtInterceptor implements HandlerInterceptor {
private final JwtUtil jwtUtil;
public JwtInterceptor(JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 从请求头中获取token
String token = request.getHeader("Authorization");
if (token != null && token.startsWith("Bearer ")) {
// 去除Bearer前缀
token = token.substring(7);
// 验证token并设置用户信息到请求中
String username = jwtUtil.getUsernameFromToken(token);
// 这里可以将用户信息设置到请求中,以便后续使用
// request.setAttribute("user", userService.findByUsername(username));
return true;
}
// 没有token或token格式错误,拦截请求
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}
配置拦截器
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 WebMvcConfig implements WebMvcConfigurer {
private final JwtUtil jwtUtil;
public WebMvcConfig(JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/api/**"); // 配置需要拦截的路径
}
@Bean
public JwtInterceptor jwtInterceptor() {
return new JwtInterceptor(jwtUtil);
}
}
编写控制器和页面
控制器
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello, 受保护的API!";
}
}
页面
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spring Boot JWT 演示/title>
</head>
<body>
<h1>Spring Boot JWT 演示</h1>
<button onclick="callSecuredApi()">调用受保护的API</button>
<script>
function callSecuredApi() {
fetch('/api/hello', {
method: 'GET',
headers: {
'Authorization': 'Bearer JWT令牌'
}
})
.then(response => response.text())
.then(data => alert(data))
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
在上述代码中,需要替换以下部分:
-
your-secret-key
:在application.properties
中配置的 JWT 密钥。 -
your-jwt-token
:实际生成的 JWT Token。
请注意,这只是一个简单的示例,实际项目中可能需要根据具体需求进行更复杂的配置和处理。