Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何使用RemoteTokenService?_Spring_Spring Security_Oauth 2.0_Access Token_Spring Security Oauth2 - Fatal编程技术网

Spring 如何使用RemoteTokenService?

Spring 如何使用RemoteTokenService?,spring,spring-security,oauth-2.0,access-token,spring-security-oauth2,Spring,Spring Security,Oauth 2.0,Access Token,Spring Security Oauth2,我使用Spring-Security-oauth2构建了一个单独的ResourceServer。这是RemoteTokenService的代码 @Bean public ResourceServerTokenServices tokenService() { RemoteTokenServices tokenServices = new RemoteTokenServices(); tokenServices.setClientId("sample_test_client_app")

我使用Spring-Security-oauth2构建了一个单独的ResourceServer。这是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;
}
当我使用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");
        }

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

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

    }

我有以下配置:

@Configuration
@EnableWebSecurity
@EnableAuthorizationServer
public class OAuthSecurityConfig extends AuthorizationServerConfigurerAdapter {
// ...
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        // (!)
        oauthServer.allowFormAuthenticationForClients();
    }
// ...
我添加了以下行:

    oauthServer.checkTokenAccess("permitAll()");
使用“(!)”插入行以解决相同的问题

在资源服务器上,我有一个安全的url,例如“数据/用户”,只有在“客户端”应用程序具有角色“角色\客户端”时才能访问该url。这里我使用的是RemoteTokenService,我在oauth服务器上配置了一个客户机,角色为“role\u client”,并授予客户机\u凭据。我的客户机如何访问此url

所有请求应包括“持票人”类型的授权和令牌:

> 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”的用户才能访问我的端点



请随时提出任何其他问题

您似乎已使用
denyAll()
保护/check\u令牌。这可能是一个错误,但要纠正它,您必须显示破坏它的代码。非常感谢这个问题,我花了几个小时找到了一个正确的解决方案:)这将是关键(我想它默认关闭)。我想建议“permistall()”可能有点过于宽容。“但这真的是你的选择。”戴维斯耶同意。但这只是一个例子;)@DaveSyer是的,默认情况下它是关闭的。@Alex这对我有用。但您能否告诉我如何在资源服务器上获取ClientDetails,以便检查客户端角色的安全性。我仍在等待您的回答@DaveSyer。谢谢您的回答。正如您所说的“在此cas中,只有角色为“user\u role”的用户才能访问我的端点”。客户端\u中的凭据授予用户不存在。它只与客户端相关。在这种情况下,当资源服务器请求授权服务器进行令牌身份验证时,outh服务器只返回客户端id、令牌过期时间和该客户端的范围。那么,在这种情况下,我如何检查hasAuthority???@prtk_shah正确,客户端信息仅包含此类信息,但令牌信息包含更多信息。谢谢。但我对你的回答有点困惑。您能否更详细地解释一下,在使用RemoteTokenService和ClientCredential grant时如何获得ClientAuthority。你从哪里得到上面的JSON?@prtk_shah抱歉,我现在还不知道。也许我在某些方面错了。。。我今天会检查一下,然后告诉你。关于你的第二个问题:我实现了TokenStore,用于在MongoDB中存储令牌。@prtk_shah我在日志中找到了以下行,这可能是对你问题的回答:“27789[http-bio-8081-exec-1]调试org.springframework.security.web.context.HttpSessionSecurityContextRepository-存储到HttpSession的SecurityContext:'org.springframework.security.core.context。SecurityContextImpl@cba196e7:身份验证:org.springframework.security.oauth2.provider。OAuth2Authentication@cba196e7:校长:;凭据:[受保护];认证:正确;详细信息:remoteAddress=127.0.0.1,tokenValue=;授予的权限:用户_READ'