java实现oauto2.0
时间: 2023-11-28 21:06:37 浏览: 139
java实现oauth2.0服务端+客户端(含JWT)
OAuth 2.0是一种授权协议,用于在客户端和资源所有者之间授权第三方应用程序访问资源。Java可以使用不同的库和框架来实现OAuth 2.0。
以下是使用Spring Security实现OAuth 2.0的步骤:
1.添加Spring Security OAuth 2.0依赖项。在Maven中,可以使用以下依赖项:
```
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
```
2.配置OAuth 2.0客户端。在Spring Security中,可以使用OAuth2RestTemplate或OAuth2AuthorizedClient来访问资源服务器。您需要配置客户端ID,客户端秘密,授权服务器URL和资源服务器URL。
```
@Configuration
@EnableOAuth2Client
public class OAuth2ClientConfig {
@Value("${oauth2.clientId}")
private String clientId;
@Value("${oauth2.clientSecret}")
private String clientSecret;
@Value("${oauth2.accessTokenUri}")
private String accessTokenUri;
@Value("${oauth2.userAuthorizationUri}")
private String userAuthorizationUri;
@Value("${oauth2.redirectUri}")
private String redirectUri;
@Value("${oauth2.resource.userInfoUri}")
private String userInfoUri;
@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext) {
OAuth2ProtectedResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
((ClientCredentialsResourceDetails) resourceDetails).setClientId(clientId);
((ClientCredentialsResourceDetails) resourceDetails).setClientSecret(clientSecret);
((ClientCredentialsResourceDetails) resourceDetails).setAccessTokenUri(accessTokenUri);
return new OAuth2RestTemplate(resourceDetails, oauth2ClientContext);
}
@Bean
public OAuth2AuthorizedClientService authorizedClientService() {
return new InMemoryOAuth2AuthorizedClientService(new ClientRegistration());
}
private class ClientRegistration implements OAuth2ClientRegistration {
@Override
public String getRegistrationId() {
return "oauth2-client";
}
@Override
public ClientRegistration.ProviderDetails getProviderDetails() {
return new ClientRegistration.ProviderDetails("oauth2-provider", accessTokenUri, userAuthorizationUri);
}
@Override
public ClientRegistration.ClientCredentials getClientCredentials() {
return new ClientRegistration.ClientCredentials(clientId, clientSecret, null);
}
@Override
public ClientRegistration.RedirectUri getRedirectUri() {
return new ClientRegistration.RedirectUri(redirectUri, null);
}
@Override
public OAuth2AccessToken getAccessToken() {
DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken("");
accessToken.setTokenType("Bearer");
accessToken.setExpiration(null);
accessToken.setScope(Collections.emptySet());
return accessToken;
}
@Override
public OAuth2RefreshToken getRefreshToken() {
return null;
}
@Override
public Map<String, Object> getAdditionalParameters() {
return null;
}
}
}
```
3.配置OAuth 2.0资源服务器。您需要配置资源服务器URL和OAuth2AuthorizedClientService。
```
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Value("${oauth2.resource.userInfoUri}")
private String userInfoUri;
@Autowired
private OAuth2AuthorizedClientService authorizedClientService;
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().oauth2ResourceServer().jwt();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(userInfoUri).tokenServices(tokenServices());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
accessTokenConverter.setVerifier(new RsaVerifier("-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmx0K/9PdWtY8Nt1uKjzN\n" +
"7q3jK0u/vpK+vJSR5iV7XH5r5j5g1rRwRZzH6G4fQ4zF1kKjE1eU6XoU6yVp6Dwz\n" +
"8TzZJxGZDfzQvv+X9jJcVCsC7obnO/VfRmJd4Q2m4G1Ox6kwOj6XeU6y+oOyVUqu\n" +
"TzZ1lN6Dx0J2Q0VLG9i/4JfobPav/2Qwv8bD7zJnmZnKJxwpdYvY8WtF1JyweJh7\n" +
"RGV7iLZKxGx7fRVRv9XVg5Q5i5H5r1cCwq3zV0ZTTjKLZ7VvKEvRb9oV2yC5mJ7O\n" +
"18gWZ58UCzPjxV0cBNB8YtW1jbxJyN0K0nJh8T7TJbUZDf+ZGJvA8nxJKWuLsJ32\n" +
"RwIDAQAB\n" +
"-----END PUBLIC KEY-----"));
return accessTokenConverter;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverterConfigurer jwtAccessTokenConverterConfigurer() {
return new JwtAccessTokenConverterConfigurer();
}
private class JwtAccessTokenConverterConfigurer implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof JwtAccessTokenConverter) {
((JwtAccessTokenConverter) bean).setAccessTokenConverter(accessTokenConverter());
}
return bean;
}
}
@Bean
public JwtTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setTokenEnhancer(accessTokenConverter());
tokenServices.setSupportRefreshToken(true);
tokenServices.setReuseRefreshToken(false);
return new JwtTokenServices(tokenServices, authorizedClientService);
}
}
```
4.配置OAuth 2.0授权服务器。您需要配置授权服务器URL和OAuth2AuthorizedClientService。
```
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Value("${oauth2.clientId}")
private String clientId;
@Value("${oauth2.clientSecret}")
private String clientSecret;
@Value("${oauth2.accessTokenValiditySeconds}")
private int accessTokenValiditySeconds;
@Value("${oauth2.refreshTokenValiditySeconds}")
private int refreshTokenValiditySeconds;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private OAuth2AuthorizedClientService authorizedClientService;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(clientId)
.secret(clientSecret)
.authorizedGrantTypes("password", "refresh_token")
.scopes("read", "write")
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.refreshTokenValiditySeconds(refreshTokenValiditySeconds);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.tokenServices(tokenServices());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
accessTokenConverter.setSigningKey("secret");
return accessTokenConverter;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverterConfigurer jwtAccessTokenConverterConfigurer() {
return new JwtAccessTokenConverterConfigurer();
}
private class JwtAccessTokenConverterConfigurer implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof JwtAccessTokenConverter) {
((JwtAccessTokenConverter) bean).setAccessTokenConverter(accessTokenConverter());
}
return bean;
}
}
@Bean
public JwtTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setTokenEnhancer(accessTokenConverter());
tokenServices.setSupportRefreshToken(true);
tokenServices.setReuseRefreshToken(false);
return new JwtTokenServices(tokenServices, authorizedClientService);
}
}
```
5.在应用程序中使用OAuth 2.0。您可以使用OAuth2RestTemplate或OAuth2AuthorizedClient来访问资源服务器。
```
@RestController
public class ResourceController {
@Autowired
private OAuth2RestTemplate restTemplate;
@GetMapping("/resource")
public String getResource() {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/user", String.class);
return response.getBody();
}
}
```
```
@RestController
public class UserController {
@GetMapping("/user")
public String getUser(Principal principal) {
return principal.getName();
}
}
```
以上是使用Spring Security实现OAuth 2.0的步骤。您可以根据您的需求使用其他OAuth 2.0库和框架。
阅读全文