【问题标题】:Spring Oauth2 Authorization_Grant - cannot access resources after token - User AnonymousSpring Oauth2 Authorization_Grant - 令牌后无法访问资源 - 用户匿名
【发布时间】:2017-09-01 18:18:48
【问题描述】:

我正在尝试使用 spring 的授权授予流程来保护我的 REST Api。

我可以(使用 Postman)获取访问令牌,我将授权放入带有 Bearer 的标头中,但我无法访问资源,因为 Spring Security 告诉我:

    2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository[186] - HttpSession returned null object for SPRING_SECURITY_CONTEXT
    2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository[116] - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@6e24700e. A new one will be created.
    2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.s.w.h.writers.HstsHeaderWriter[130] - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@3e385c64
    2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.security.web.FilterChainProxy[325] - /api/user at position 11 of 14 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
    2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter[100] - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9057bc48: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@2cd90: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: B1FF11055AA4F347AB8AA7B6E467D93F; Granted Authorities: ROLE_ANONYMOUS'
2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor[219] - Secure object: FilterInvocation: URL: /api/user; Attributes: [authenticated]
    2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor[348] - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9057bc48: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@2cd90: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: B1FF11055AA4F347AB8AA7B6E467D93F; Granted Authorities: ROLE_ANONYMOUS
    2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.s.access.vote.AffirmativeBased[66] - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@53b3549c, returned: -1
    2017-04-06 17:36:33 [http-nio-8080-exec-9] DEBUG o.s.s.w.a.ExceptionTranslationFilter[173] - Access is denied (user is anonymous); redirecting to authentication entry point
    org.springframework.security.access.AccessDeniedException: Access is denied

所以基本上,在获得访问令牌后,如果我使用它,我将成为匿名用户,主要是因为 SPRING_SECURITY_CONTEXT 为空......

这是我的资源服务器配置

@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{

    private final Logger logger = LoggerFactory.getLogger(ResourceServerConfig.class);

    @Autowired
    DataSource dataSource;

     @Override
    public void configure(HttpSecurity http) throws Exception {
                logger.debug("Api security configured");
                http    
                .antMatcher("/api/**")
               .authorizeRequests()
               .anyRequest().access("hasRole('USER')")
               .and().exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint())
               .and().httpBasic();
            }

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

     @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

            resources.tokenStore(tokenStore());
        }
}

这个是认证服务器

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    DataSource dataSource;

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

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.tokenStore(tokenStore()).authenticationManager(authManager);

    }

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

}

我正在尝试使用此身份验证 Bearer 77a226bf-74a4-4a89-b2a6-e130c215566b 访问 /api/user,该身份验证来自以用户身份登录后的身份验证服务器令牌请求...

怎么了?

【问题讨论】:

  • 我也有同样的问题,你的问题没有解决吗?

标签: java spring spring-security oauth-2.0


【解决方案1】:

在将 spring boot 从 1.4 更新到 1.5 后,我遇到了完全相同的问题。该问题已通过禁用引导的自动配置黑魔法解决。

@EnableAutoConfiguration(exclude = {OAuth2AutoConfiguration.class})

我相信他们已经添加了一些新的 ~~bug~~ 破坏旧应用配置的功能。

【讨论】:

    【解决方案2】:

    我认为用户角色没有从数据库中获取。 必须定义角色列吗?

    这将帮助您: https://dzone.com/articles/spring-security-4-authenticate-and-authorize-users

    【讨论】:

    • 用户可以登录Web应用程序,所以我认为它的角色是正确的,只有在尝试通过OAUTH流程访问时才会出现问题
    • 你能告诉我存储在数据库中的角色列数据吗?
    • ID |类型 -> 1 |用户
    • 更新配置方法如下: public void configure(HttpSecurity http) throws Exception { http.requestMatchers() .antMatchers("/api/**").and()。 authorizeRequests().antMatchers("/api/**") .access("hasRole('USER')") .and().exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()) .and().httpBasic() ; }
    • 总是得到相同的东西.. SecurityContext 为空或内容是匿名的 - 上下文不会存储在 HttpSession 中
    猜你喜欢
    • 2015-06-05
    • 2016-08-12
    • 2015-10-11
    • 2017-07-08
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2020-12-29
    • 2019-03-13
    相关资源
    最近更新 更多