springboot集成oauth2
时间: 2023-11-03 16:01:13 浏览: 32
Spring Boot 集成 OAuth2 可以实现授权和认证功能,可以为我们的应用程序提供更加安全的访问控制。
下面是实现 Spring Boot 集成 OAuth2 的步骤:
1. 添加依赖
```
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
```
2. 配置 Spring Security
在 `WebSecurityConfigurerAdapter` 类中配置 OAuth2 安全配置。
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("password1").roles("USER")
.and()
.withUser("admin1").password("password2").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/api/**").authenticated()
.and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
@Bean
@Autowired
public AuthorizationCodeServices authorizationCodeServices(TokenStore tokenStore) {
return new JdbcAuthorizationCodeServices(dataSource());
}
@Bean
@Autowired
public OAuth2RequestFactory requestFactory(ClientDetailsService clientDetailsService) {
return new DefaultOAuth2RequestFactory(clientDetailsService);
}
@Bean
@Autowired
public OAuth2AuthenticationEntryPoint authenticationEntryPoint(ClientDetailsService clientDetailsService) {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setRealmName("oauth/client");
entryPoint.setClientDetailsService(clientDetailsService);
return entryPoint;
}
@Bean
@Autowired
public OAuth2AccessDeniedHandler accessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
@Autowired
private DataSource dataSource;
@Bean
public JdbcTokenStore tokenStore(DataSource dataSource) {
return new JdbcTokenStore(dataSource);
}
@Bean
public JdbcClientDetailsService clientDetailsService(DataSource dataSource) {
return new JdbcClientDetailsService(dataSource);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
}
```
3. 配置 OAuth2
在 `AuthorizationServerConfigurerAdapter` 类中配置 OAuth2 安全配置。
```
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private ClientDetailsService clientDetailsService;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("clientapp")
.secret("123456")
.authorizedGrantTypes("password", "refresh_token")
.authorities("USER")
.scopes("read", "write")
.resourceIds("oauth2-resource")
.accessTokenValiditySeconds(600)
.refreshTokenValiditySeconds(6000);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.realm("oauth/client");
}
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
@Bean
@Autowired
public OAuth2RequestFactory requestFactory(ClientDetailsService clientDetailsService) {
return new DefaultOAuth2RequestFactory(clientDetailsService);
}
}
```
4. 配置资源服务器
在 `ResourceServerConfigurerAdapter` 类中配置资源服务器。
```
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("oauth2-resource");
}
}
```
5. 测试
启动应用程序并访问 `http://localhost:8080/oauth/token`,使用 `clientapp` 和 `123456` 进行身份验证。如果身份验证成功,应该会收到一个访问令牌。
然后,访问 `http://localhost:8080/api/hello`,应该会看到一个受保护的资源的欢迎消息。