Spring Boot如何配置并启用JWT支持?
时间: 2024-10-15 22:24:30 浏览: 53
踩坑整理1
在Spring Boot中配置JWT支持通常涉及以下几个步骤:
1. 添加依赖:首先,你需要将JWT库添加到项目的依赖中。如果使用的是`jjwt`,你可以在pom.xml文件中加入这个依赖,示例如下:
```xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.11.8</version> <!-- 或者最新稳定版 -->
</dependency>
```
2. 配置Spring Security:Spring Security提供了一个`WebSecurityConfigurerAdapter`的扩展点`HttpSecurity.oauth2()`,在那里添加JWT认证配置。这里是一个基本的示例:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.configurers.web.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.core.configurers.oidc.OidcAuthorizationServicesProviderConfigurer;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationService;
import org.springframework.security.oauth2.jose.JoseException;
import org.springframework.security.oauth2.provider.ClientDetails;
@Configuration
public class JwtConfig extends AuthorizationServerConfigurerAdapter {
private static final String SECRET_KEY = "your-secret-key";
@Autowired
private ClientDetailsService clientDetailsService;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// 注册客户端信息
clients.inMemory()
.withClient("client_id")
.secret(SECRET_KEY)
.authorizedGrantTypes("password", "refresh_token")
.scopes("read", "write");
}
@Override
public void configure(OidcAuthorizationServicesProviderConfigurer oauth) throws JoseException {
OAuth2AuthorizationService authorizationService = new InMemoryOAuth2AuthorizationServiceImpl();
authorizationService.setAuthorizedParties(Collections.singletonList("http://localhost"));
oauth.authorizationEndpoint().authorizationServices(authorizationService);
}
}
```
这里设置了基础的客户端信息,并创建了授权服务。
3. 认证过滤器:还需要在WebMvcConfigurer接口上注册JWT过滤器,检查请求头中的Bearer token:
```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/login");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter(clientDetailsService, SECRET_KEY);
}
}
```
4. 自定义令牌验证:最后,创建一个JWT验证类(JwtAuthenticationFilter),负责解析token并验证其有效性。
阅读全文