SpringSecurity+OAuth2.0 搭建认证中心和资源服务中心
以下是一个简化的Spring Security和OAuth2.0搭配使用的示例,用于搭建一个认证中心和资源服务中心。
认证中心(Authorization Server):
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("resource-server")
.secret("secret")
.authorizedGrantTypes("client_credentials")
.scopes("read", "write")
.resourceIds("oauth2-resource");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
资源服务中心(Resource Server):
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("oauth2-resource");
}
}
安全配置(Security Configuration):
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").authorities("USER");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
启动类(Application):
@SpringBootApplication
public class AuthServerApplication {
publ
评论已关闭