当前位置: 首页 > 知识库问答 >
问题:

在Spring OAuth2中配置安全性:拒绝身份验证请求的访问

史逸春
2023-03-14

我想使用OAuth2实现Spring Security。我尝试了以下安全配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/users/authorize").permitAll()
            .antMatchers("/users/reset_request").permitAll()
            .antMatchers("/users/reset_token").permitAll()
            .antMatchers("/users/reset_password").permitAll()
            .antMatchers("/users/confirmation_token").permitAll()
            .antMatchers("/users/reset_user_password").permitAll()
            .anyRequest().authenticated()
            .and().formLogin().permitAll()
            .and().csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

完整代码:Github

但是我总是得到:

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

我向身份验证终结点发出 POST 请求:

localhost:8080/engine/users/authorize

回应:

    01:57:19.237 [http-nio-8080-exec-5] DEBUG ExceptionTranslationFilter[sendStartAuthentication:211] - Calling Authentication entry point.
01:57:19.239 [http-nio-8080-exec-5] DEBUG HstsHeaderWriter[writeHeaders:169] - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@69e77584
01:57:19.251 [http-nio-8080-exec-5] DEBUG DefaultOAuth2ExceptionRenderer[writeWithMessageConverters:101] - Written [error="unauthorized", error_description="Full authentication is required to access this resource"] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@4fe0c045]
01:57:19.252 [http-nio-8080-exec-5] DEBUG SecurityContextPersistenceFilter[doFilter:119] - SecurityContextHolder now cleared, as request processing completed
09:07:01.012 [PRODUCTION_HIKARICP_CONNECTION_POOL housekeeper] WARN  HikariPool[run:787] - PRODUCTION_HIKARICP_CONNECTION_POOL - Thread starvation or clock leap detected (housekeeper delta=6h6m24s237ms51╡s500ns).
09:07:02.931 [WAREHOUSE_HIKARICP_CONNECTION_POOL housekeeper] WARN  HikariPool[run:787] - WAREHOUSE_HIKARICP_CONNECTION_POOL - Thread starvation or clock leap detected (housekeeper delta=6h6m24s237ms408╡s400ns).
11:16:17.556 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:65] - Trying to match using Ant [pattern='/oauth/token']
11:16:27.735 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/oauth/token'
11:16:27.754 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:65] - Trying to match using Ant [pattern='/oauth/token_key']
11:16:27.754 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/oauth/token_key'
11:16:27.754 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:65] - Trying to match using Ant [pattern='/oauth/check_token']
11:16:27.754 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/oauth/check_token'
11:16:27.754 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:72] - No matches found
11:16:27.756 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
11:16:27.757 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
11:16:27.758 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
11:16:27.770 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
11:16:27.771 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:65] - Trying to match using Ant [pattern='/logout', GET]
11:16:27.773 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:157] - Request 'POST /users/authorize' doesn't match 'GET /logout'
11:16:27.773 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:65] - Trying to match using Ant [pattern='/logout', POST]
11:16:27.773 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/logout'
11:16:27.773 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:65] - Trying to match using Ant [pattern='/logout', PUT]
11:16:27.774 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:157] - Request 'POST /users/authorize' doesn't match 'PUT /logout'
11:16:27.774 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:65] - Trying to match using Ant [pattern='/logout', DELETE]
11:16:27.774 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:157] - Request 'POST /users/authorize' doesn't match 'DELETE /logout'
11:16:27.774 [http-nio-8080-exec-7] DEBUG OrRequestMatcher[matches:72] - No matches found
11:16:27.774 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
11:16:27.775 [http-nio-8080-exec-7] DEBUG BearerTokenExtractor[extractToken:54] - Token not found in headers. Trying request parameters.
11:16:27.782 [http-nio-8080-exec-7] DEBUG BearerTokenExtractor[extractToken:57] - Token not found in request parameters.  Not an OAuth2 request.
11:16:27.783 [http-nio-8080-exec-7] DEBUG OAuth2AuthenticationProcessingFilter[doFilter:141] - No token in request, will continue chain.
11:16:27.783 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
11:16:27.783 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
11:16:27.784 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
11:16:27.787 [http-nio-8080-exec-7] DEBUG AnonymousAuthenticationFilter[doFilter:100] - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@461b50c6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
11:16:27.788 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
11:16:27.789 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
11:16:27.789 [http-nio-8080-exec-7] DEBUG FilterChainProxy[doFilter:328] - /users/authorize at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
11:16:27.791 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/*'
11:16:27.799 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/v1/swagger.**'
11:16:27.800 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:157] - Request 'POST /users/authorize' doesn't match 'GET /v2/api-docs'
11:16:27.800 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:157] - Request 'POST /users/authorize' doesn't match 'GET /swagger-resources/**'
11:16:27.800 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:157] - Request 'POST /users/authorize' doesn't match 'GET /swagger-ui.html**'
11:16:27.801 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:157] - Request 'POST /users/authorize' doesn't match 'GET /webjars/**'
11:16:27.802 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:157] - Request 'POST /users/authorize' doesn't match 'GET favicon.ico'
11:16:27.802 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/v1/application.wadl'
11:16:27.803 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/v1/admin/**'
11:16:27.803 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/v1/dev/**'
11:16:27.803 [http-nio-8080-exec-7] DEBUG AntPathRequestMatcher[matches:177] - Checking match of request : '/users/authorize'; against '/v1/pages/**'
11:16:27.805 [http-nio-8080-exec-7] DEBUG FilterSecurityInterceptor[beforeInvocation:219] - Secure object: FilterInvocation: URL: /users/authorize; Attributes: [#oauth2.throwOnError(authenticated)]
11:16:27.805 [http-nio-8080-exec-7] DEBUG FilterSecurityInterceptor[authenticateIfRequired:348] - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@461b50c6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
11:16:27.835 [http-nio-8080-exec-7] DEBUG AffirmativeBased[decide:66] - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@2938ceb8, returned: -1
11:16:27.842 [http-nio-8080-exec-7] DEBUG ExceptionTranslationFilter[handleSpringSecurityException:180] - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
        at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
        at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)

由于某种原因,此安全配置未被应用。你知道我该如何解决这个问题吗?

共有1个答案

屈昊天
2023-03-14

您可能错过了endpoint中的/engine。如下

使用configure(HttpSecurity.http)在antMatchers中添加/engine

改变

.antMatchers("/users/authorize").permitAll()

.antMatchers("/engine/users/authorize").permitAll()

配置(HttpSecurity http)

@Override
protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/engine/users/authorize").permitAll()
            .antMatchers("/engine/users/reset_request").permitAll()
            .antMatchers("/engine/users/reset_token").permitAll()
            .antMatchers("/engine/users/reset_password").permitAll()
            .antMatchers("/engine/users/confirmation_token").permitAll()
            .antMatchers("/engine/users/reset_user_password").permitAll()
            .anyRequest().authenticated()
            .and().formLogin().permitAll()
            .and().csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

使用configure(WebSecurity-web)方法,您可以使用<code>configure(websecurety-web)</code>方法完全避免Spring Security过滤器。

@Override
public void configure(WebSecurity web) throws Exception {
    web.
        ignoring()
            .antMatchers("/engine/users/authorize")
            .antMatchers("/engine/users/reset_request")
            .antMatchers("/engine/users/reset_token")
            .antMatchers("/engine/users/reset_password")
            .antMatchers("/engine/users/confirmation_token")
            .antMatchers("/engine/users/reset_user_password");
}

注意:如果您同时使用 configure(WebSecurity web) 和 configure(HttpSecurity http),则保持配置(WebSecurity web) 上面的 configure(HttpSecurity HTTP),如此处所述

@Override
public void configure(WebSecurity web) throws Exception {
    ...
}

@Override
protected void configure(HttpSecurity http) throws Exception {
     ...
}
 类似资料:
  • 我正在尝试向登录Spotify发送身份验证请求。 这是由javascript XMLHttpRequest通过本地主机运行的。然而,我收到的只是一条错误消息,指出: XMLHttpRequest无法加载https://accounts.spotify.com/authorize/?q=undefined 请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许

  • 通过使用以下curl命令,我能够访问令牌并获得以下响应curl用户名:password@machinename:11002/appName/oauth/token-d grant\u type=password-d username=loginFormUserID-d password=loginFormUserPassword 响应:{“实体\ id”:9,“实体\类型”:“刷新\标记”:“ey

  • 昨天我在编码,当我做提交到一个回购,我不能这样做,因为,gitlab给我发送了两个消息。 这条消息出现在我试图promise的时刻 null

  • “Git push origin MyBranchName”抛出错误“HTTP Basic:拒绝访问” 我在GitLab中配置了密码。 我有SSL密钥创建后,项目是在GitLab上。

  • 我正在开发REST webService,我的一些客户机将使用我的webservices,所以为了识别真正的客户机,我决定给每个真正的客户机一个唯一的应用程序令牌。客户机将对这个令牌进行编码,他们将把这个令牌放在请求头中,我已经在我的REST webservices中配置了一个REST过滤器来验证令牌。我不想使用https。我的问题是,任何人都可以从我的客户端站点获取该令牌,并可以使用我的REST