Spring Security OAuth2 Provider 之 整合JWT

本文介绍了如何在Spring Security框架中集成OAuth2和JWT(JSON Web Tokens),包括Maven依赖配置、签名证书生成、认证服务端及资源服务端的设置等关键步骤,并提供了确认测试过程。
OAuth2 是认证框架、JWT (JSON Web Tokens) 是认证协议。

相关文章:
[url=http://rensanning.iteye.com/blog/2384996]Spring Security OAuth2 Provider 之 最小实现[/url]
[url=http://rensanning.iteye.com/blog/2385162]Spring Security OAuth2 Provider 之 数据库存储[/url]
[url=http://rensanning.iteye.com/blog/2386309]Spring Security OAuth2 Provider 之 第三方登录简单演示[/url]
[url=http://rensanning.iteye.com/blog/2386553]Spring Security OAuth2 Provider 之 自定义开发[/url]
[url=http://rensanning.iteye.com/blog/2386766]Spring Security OAuth2 Provider 之 整合JWT[/url]

[b](1)Maven依赖[/b]

Authorization Server 和 Resource Server都需要添加依赖。

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<optional>true</optional>
</dependency>


[b](2)生成签名证书[/b]

生成证书
[quote]# keytool -genkeypair -alias jwt-test -keyalg RSA -dname "CN=jwt,OU=ren,O=ren,L=china,S=china,C=CN" -keypass my_pass -keystore jwt-test.jks -storepass my_pass[/quote]
把.jks文件放到Authorization Server 的 src/main/resources/jwt-test.jks

导出公钥
[quote]# keytool -list -rfc --keystore jwt-test.jks | openssl x509 -inform pem -pubkey[/quote]
把PUBLIC KEY部分复制到Resource Server 的 src/main/resources/public.txt

[b](3)认证服务端设置[/b]

@Bean
protected JwtAccessTokenConverter jwtTokenEnhancer() {
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt-test.jks"), "my_pass".toCharArray());
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt-test"));
return converter;
}

@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}


[b](4)资源服务端设置[/b]

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
Resource resource = new ClassPathResource("public.txt");
String publicKey = null;
try {
publicKey = IOUtils.toString(resource.getInputStream());
} catch (final IOException e) {
throw new RuntimeException(e);
}
converter.setVerifierKey(publicKey);
return converter;
}

@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}


[b](5)确认测试[/b]

获取Token:
[img]http://dl2.iteye.com/upload/attachment/0126/2337/d424cf2c-c042-3f74-8027-5a454e1e4fd4.png[/img]

通过jwt.io确认Token:
[img]http://dl2.iteye.com/upload/attachment/0126/2339/bc39afcd-2ea9-311c-b207-c5e97735e655.png[/img]

通过access_token访问资源API:
[img]http://dl2.iteye.com/upload/attachment/0126/2341/ea6ee272-4b3b-35ff-a72a-06682c616236.png[/img]

[b](6)算法HS256[/b]
把Authorization Server 和 Resource Server的配置改成:
@Bean
protected JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("rensanning");
return converter;
}


获取Token:
[img]http://dl2.iteye.com/upload/attachment/0126/2343/28039be9-a2bc-36db-b5ad-3821d884acd4.png[/img]

通过jwt.io确认Token:
[img]http://dl2.iteye.com/upload/attachment/0126/2345/f0d1156f-13ee-3ad8-8a3e-6af901dcde9b.png[/img]

通过access_token访问资源API:
[img]http://dl2.iteye.com/upload/attachment/0126/2347/8e664893-73c0-33f7-9c19-3374a2927424.png[/img]

参考:
http://www.baeldung.com/spring-security-oauth-jwt
https://github.com/dynamind/spring-boot-security-oauth2-minimal
### Spring Security OAuth2 JWT 整合教程 #### 1. 添加依赖 为了在项目中使用 Spring SecurityOAuth2 的功能,需要引入必要的 Maven 或 Gradle 依赖项。以下是基于 Maven 的配置示例: ```xml <properties> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- Spring Cloud Starter OAuth2 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <!-- 数据库连接支持 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- Druid 数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> </dependencies> ``` 以上代码片段展示了如何通过 `pom.xml` 文件添加所需的依赖[^4]。 --- #### 2. 创建自定义 Token Enhancer 为了让生成的 JWT 包含额外的信息(如用户角色或其他元数据),可以创建一个自定义的 `TokenEnhancer` 类并将其注册到 Spring 容器中。 ```java import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; public class JwtTokenEnhancer implements TokenEnhancer { @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Map<String, Object> additionalInfo = new HashMap<>(); // 增加自定义字段 additionalInfo.put("custom_field", "example_value"); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; } } ``` 此部分实现了对令牌增强的功能[^2]。 --- #### 3. 配置 JWT 支持 接下来,在项目的配置类中启用 JWT 并注入自定义的 `TokenEnhancer` 实现。 ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsService userDetailsService; @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("your_signing_key"); // 设置签名密钥 return converter; } @Bean public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) { return new JwtTokenStore(jwtAccessTokenConverter); // 使用 JWT 存储方式 } @Bean public JwtTokenEnhancer jwtTokenEnhancer() { return new JwtTokenEnhancer(); // 注册自定义 Token Enhancer } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { TokenEnhancerChain enhancerChain = new TokenEnhancerChain(); List<TokenEnhancer> delegates = Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()); enhancerChain.setTokenEnhancers(delegates); endpoints.authenticationManager(authenticationManager) .tokenStore(tokenStore(jwtAccessTokenConverter())) .accessTokenConverter(jwtAccessTokenConverter()) .tokenEnhancer(enhancerChain); } } ``` 这段代码完成了对 JWT 的初始化以及与 OAuth2 流程的集成[^1]。 --- #### 4. 资源服务器配置 资源服务器负责解析传入请求中的 JWT,并验证其有效性。 ```java @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/public/**").permitAll() // 公开接口无需认证 .anyRequest().authenticated(); // 所有其他请求都需要认证 } } ``` 该配置确保只有经过身份验证的客户端才能访问受保护的 API 接口[^3]。 --- #### 5. 总结 通过上述步骤,可以在 Spring Boot 应用程序中成功整合 OAuth2JWT 技术栈,从而实现安全的身份验证和授权机制。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值