15

我有一个使用 Spring-Security-oauth2 构建的单独的 ResourceServer。这是代码远程令牌服务。

@Bean
public ResourceServerTokenServices tokenService() {
   RemoteTokenServices tokenServices = new RemoteTokenServices();
   tokenServices.setClientId("sample_test_client_app");
   tokenServices.setClientSecret("secret");
   tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
   return tokenServices;
}

当我使用 AccessToken 访问资源服务器时,我得到以下信息:

FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /oauth/check_token; Attributes: [denyAll()]
FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@c3f3b25: Principal: org.springframework.security.core.userdetails.User@3c0cd8e: Username: sample_test_client_app; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities
AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@6172e10, returned: -1
ExceptionTranslationFilter - Access is denied (user is not anonymous); delegating to AccessDeniedHandler

谁能告诉我我的配置有什么问题?

更新: 我的 Spring 安全配置。

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().withUser("developer").password("developer").roles("USER");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/webjars/**", "/images/**", "/oauth/uncache_approvals", "/oauth/cache_approvals");
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
                 http
            .authorizeRequests().antMatchers("/login.jsp").permitAll().and()
            .authorizeRequests().antMatchers("/oauth/check_token").permitAll().and()
            .authorizeRequests()
                .anyRequest().hasRole("USER")
                .and()
            .exceptionHandling()
                .accessDeniedPage("/login.jsp?authorization_error=true")
                .and()
            .logout()
                .logoutSuccessUrl("/index.jsp")
                .logoutUrl("/logout.do")
                .and()
            .formLogin();
        // @formatter:on
    }
}

我的身份验证服务器配置。

@Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private TokenStore tokenStore;

        @Autowired
        private UserApprovalHandler userApprovalHandler;

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

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients
                .inMemory()
                .withClient("sample_test_client_app")
                .secret("secret")
                .authorizedGrantTypes("client_credentials","authorization_code")
                .authorities("ROLE_CLIENT")
                .resourceIds(CHANAKYA_RESOURCE_ID)
                .scopes("read","write");

            // @formatter:on
        }

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

        @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("resource_server/client");
        }

    }
4

2 回答 2

14

我有以下配置:

@Configuration
@EnableWebSecurity
@EnableAuthorizationServer
public class OAuthSecurityConfig extends AuthorizationServerConfigurerAdapter {
// ...
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        // (!)
        oauthServer.allowFormAuthenticationForClients();
    }
// ...

我添加了以下行:

    oauthServer.checkTokenAccess("permitAll()");

进入带有“(!)”的行以解决相同的问题。

于 2014-10-08T16:26:12.353 回答
1

在资源服务器上,我有一个安全的 url,例如“数据/用户”,只有当“客户端”应用程序具有角色“ROLE_CLIENT”时才能访问它。在这里,我正在使用 RemoteTokenService,并且我在 oauth 服务器上配置了一个客户端,其角色为“ROLE_CLIENT”和 client_credential 授权。我的客户端如何访问此 url ???

所有请求都应包括类型为“Bearer”和令牌的授权:

> curl "https://localhost:8080/users/me" -H "Pragma: no-cache" -H "Origin:
> http://localhost:8080" -H "Accept-Encoding: gzip,deflate" -H
> "Accept-Language: en-US,en;q=0.8,es;q=0.6" -H "Authorization: Bearer
> f07abd25-af1f-44e2-XXXX-ba5071168XXX" -H "Accept: */*" -H
> "Cache-Control: no-cache" -H "User-Agent: Mozilla/5.0 (Windows NT 6.1;
> WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124
> Safari/537.36" -H "Connection: keep-alive" -H "Referer:
> http://localhost:8080/test.html" --compressed

当我使用 RemoteTokenService 时,我的令牌将通过“/oauth/check_token”(CheckTokenEndpoint)进行验证。其中不提供有关客户角色的任何信息。那么我如何比较客户的角色。

Spring security 具有所有必需的信息。您需要做的就是保护您的端点。就我而言:

@PreAuthorize("hasAnyAuthority('USER_READ')")

在这种情况下,只有角色为“USER_READ”的用户才能访问我的端点。


随时提出任何其他问题。

于 2014-10-09T12:12:06.947 回答