将OAuth2资源服务器与身份验证服务器

时间:2017-11-17 09:35:28

标签: rest spring-security oauth-2.0 access-token spring-security-oauth2

我正在尝试制作样本OAuth2 Spring授权和资源服务器。我的目的是实现两个独立的应用程序 - 一个代表授权服务器,另一个代表资源服务器。由于我是Spring Security的初学者,我想我需要一些指导来完成我的任务。

我已经设法使用内存令牌存储(app名为" OAuth")实现一个简单的授权服务器。

AuthServerOAuth2Config.java

@Configuration
@EnableAuthorizationServer
public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter {
    private static final String RESOURCE_ID = "myResource";

    @Autowired
    private UserApprovalHandler handler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
         // @formatter:off
         clients.inMemory()
                 .withClient("test")
                    .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                    .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                    .scopes("read", "write", "trust")
                    .resourceIds(RESOURCE_ID)
                    .secret("test")
                    .accessTokenValiditySeconds(300).//invalid after 5 minutes.
                    refreshTokenValiditySeconds(600);//refresh after 10 minutes.
         // @formatter:on
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore()).userApprovalHandler(handler).authenticationManager(authManager);
    }

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

}

OAuth2SecurityConfig.java

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfig extends WebSecurityConfigurerAdapter {
    private static final Logger LOG = LoggerFactory.getLogger(OAuth2SecurityConfig.class);

    @Autowired
    private ClientDetailsService clientService;

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        // @formatter:off
        auth.inMemoryAuthentication()
        .withUser("javabycode").password("123456").roles("USER")
        .and()
        .withUser("admin").password("admin123").roles("ADMIN");
        // @formatter:on
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
         http
         .csrf().disable()
         .anonymous().disable()
            .authorizeRequests()
            .antMatchers("/oauth/token").permitAll();
        // @formatter:on
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientService));
        handler.setClientDetailsService(clientService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

}

访问http://localhost:9081/OAuth/oauth/token?grant_type=password&username=admin&password=admin123会按预期返回令牌,因此我猜测授权服务器配置正常。

现在有一个资源服务器部分(app名为" RestTest")。我设法找到了一些使用RemoteTokenServices来访问驻留在另一个应用中的令牌服务的示例。所以到目前为止,这是我的资源服务器。

OAuth2ResourceConfig.java

@Configuration
@EnableResourceServer
@EnableWebSecurity
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "myResource";

    private TokenExtractor tokenExtractor = new BearerTokenExtractor();

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.
        anonymous().disable()
        .requestMatchers().antMatchers("/v1/**")
        .and().authorizeRequests()
        .antMatchers("/v1/**").access("hasRole('ADMIN')")
        .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
        // @formatter:on
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws 
        Exception {
         resources.tokenServices(tokenService()).resourceId(RESOURCE_ID).stateless(true);
    }

    @Primary
    @Bean
    public RemoteTokenServices tokenService() {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("http://localhost:9081/OAuth/oauth/check_token/");
        tokenService.setClientId("test");
        tokenService.setClientSecret("test");
        return tokenService;
    }
}

我试图保护我的REST API(http://localhost:9081/RestTest/v1/foobar),所以我相信上面的配置是正确的,对吧?问题是,当我访问v1/foobar端点(通过Postman)时,它可以在没有任何身份验证的情况下访问。所以我认为我只是错过了部分配置,但我无法弄清楚如何正确连接授权服务器。还有一件事要提 - 我没有使用Spring Boot!

我真的很感激我的一些指导,让我的样本有效。谢谢!

EDIT1:我已将resourceId添加到身份验证和资源服务器 - 没有运气。 resourceId甚至是强制性的吗?

1 个答案:

答案 0 :(得分:1)

您应该以{{1​​}}和RESOURCE_ID的方式添加ResourceServer,(您使用该代码段更新了问题)

AuthorizationServer

在您的身份验证服务器中

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources.tokenServices(tokenService()).resourceId(RESOURCE_ID).stateless(true);
}

.scopes("read", "write", "trust").resourceIds(RESOURCE_ID) 中遗漏了您已在评论中说过的springSecurityFilterChain

web.xml

来自spring docs

  

它创建一个称为 springSecurityFilterChain 的Servlet过滤器,它负责应用程序中的所有安全性(保护应用程序URL,验证提交的用户名和密码,重定向到登录表单等)