How to use RemoteTokenService?

2019-03-15 17:30发布

I have a separate ResourceServer built using Spring-Security-oauth2. Here is the code RemoteTokenService.

@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;
}

When I'm accessing the resource server with AccessToken I get the following:

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

Can any one tell me what is wrong with my configuration ?

Update : My Spring security configuration.

@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
    }
}

My Auth server configuration.

@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");
        }

    }

2条回答
干净又极端
2楼-- · 2019-03-15 18:23

I have the following configuration:

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

I added the following line:

    oauthServer.checkTokenAccess("permitAll()");

into the line with "(!)" to fix the same problem.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-15 18:32

At Resource server I have a secured url e.g. "data/users" which is accessed only if "client" applicaiton has role "ROLE_CLIENT". Here I am using RemoteTokenService and I have a client configured at oauth server with role "ROLE_CLIENT" with client_credential grant.How can my client access this url ???

All requests should include authorisation with type 'Bearer' and token:

> 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

as I am using RemoteTokenService my token will be verified via "/oauth/check_token" (CheckTokenEndpoint). which dont give any information about client Role. So how can I compare Role of clients.

Spring security has all required information. All you need to do is secure your endpoint. In my case:

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

In this case only user with role 'USER_READ' can get access to my endpoint.


Feel free to ask any additional questions.

查看更多
登录 后发表回答