springboot集成jwt代码
时间: 2023-05-22 17:07:14 浏览: 122
springboot结合jwt
5星 · 资源好评率100%
很高兴回答您的问题。以下是Spring Boot集成JWT的代码示例:
1. 首先,您需要在pom.xml文件中添加以下依赖项:
```
<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>
```
2. 创建JWT工具类,该类的作用是生成JWT Token,验证JWT Token是否有效,以及获取JWT Token中存储的信息:
```
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtUtils {
private static final String secretKey = "yourSecretKey";
private static final long expiration = 3600000L;
public static String generateToken(String subject) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder builder = Jwts.builder()
.setSubject(subject)
.setIssuedAt(now)
.setExpiration(new Date(nowMillis + expiration))
.signWith(SignatureAlgorithm.HS256, secretKey);
return builder.compact();
}
public static boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
return true;
} catch (Exception ex) {
return false;
}
}
public static String getUsernameFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
}
}
```
3. 创建JWT拦截器,该拦截器的作用是验证请求的JWT Token是否有效:
```
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) throws Exception {
String token = request.getHeader("Authorization");
if (token != null && JwtUtils.validateToken(token)) {
return true;
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}
}
```
4. 在Spring Boot应用程序中添加JWT拦截器:
```
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
public class Application implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor()).addPathPatterns("/**");
}
}
```
现在您可以在应用程序中使用`JwtUtils`类来生成和验证JWT Token。请注意,此示例仅用于演示目的,即使是使用JWT进行身份验证,也需要更多的安全措施。
阅读全文