簡體   English   中英

Spring Security OAuth - 訪問此資源需要完全身份驗證

[英]Spring Security OAuth - Full authentication is required to access this resource

以下是我的授權服務器配置:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("acme").secret("acmesecret")
                .authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
                .autoApprove(true);
    }

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

}

和Web安全配置:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@Order(-20) // Very important
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.parentAuthenticationManager(authenticationManager);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin().loginPage("/login.html").permitAll().and().requestMatchers()
                .antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access").and().authorizeRequests()
                .anyRequest().authenticated();

    }
}

現在,從客戶端應用程序,當我嘗試訪問安全資源時,它會重定向到授權服務器,但是我收到以下錯誤:

<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>

在基本身份驗證的情況下,相同的設置運行良好。 當我切換到表單登錄時,我遇到了問題。

更新

以下Web安全設置有效。

http.formLogin().loginPage("/login.html").loginProcessingUrl("/login").permitAll().and().authorizeRequests()
                .antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access","/oauth/token").permitAll().anyRequest()
                .authenticated().and().csrf().disable();

現在,我能夠看到登錄頁面,我也可以登錄,但是登錄后,客戶端無法獲得oauth令牌。

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Jul 11 17:39:46 IST 2016
There was an unexpected error (type=Unauthorized, status=401).
Authentication Failed: Could not obtain access token

我能夠看到以下服務器日志

2016-07-11 17:39:46.119 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/css/**'
2016-07-11 17:39:46.119 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/js/**'
2016-07-11 17:39:46.119 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/images/**'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/**/favicon.ico'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/error'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@13bb1f26
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/logout'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/login'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2016-07-11 17:39:46.120 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/login'
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/oauth/authorize'
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/oauth/confirm_access'
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/oauth/token'
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /oauth/token; Attributes: [permitAll]
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@6780c4c7, returned: 1
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
2016-07-11 17:39:46.121 DEBUG 12502 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /oauth/token reached end of additional filter chain; proceeding with original chain
2016-07-11 17:39:46.122 DEBUG 12502 --- [nio-9999-exec-2] .s.o.p.e.FrameworkEndpointHandlerMapping : Looking up handler method for path /oauth/token
2016-07-11 17:39:46.122 DEBUG 12502 --- [nio-9999-exec-2] .s.o.p.e.FrameworkEndpointHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException]
2016-07-11 17:39:46.123  INFO 12502 --- [nio-9999-exec-2] o.s.s.o.provider.endpoint.TokenEndpoint  : Handling error: InsufficientAuthenticationException, There is no client authentication. Try adding an appropriate authentication filter.
2016-07-11 17:39:46.125 DEBUG 12502 --- [nio-9999-exec-2] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2016-07-11 17:39:46.126 DEBUG 12502 --- [nio-9999-exec-2] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2016-07-11 17:39:46.126 DEBUG 12502 --- [nio-9999-exec-2] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

更新2

以下是我的客戶端配置。

security:
  oauth2:
    client:
      accessTokenUri: http://localhost:9999/uaa/oauth/token
      userAuthorizationUri: http://localhost:9999/uaa/oauth/authorize
      clientId: acme
      clientSecret: acmesecret
    resource:
      userInfoUri: http://localhost:9999/uaa/user
logging:
  level:
    org.springframework.security: DEBUG

更新3

該代碼可在以下倉庫中找到

https://github.com/pavan496/insol-test

您需要公開/login端點(未授權),用戶需要能夠登錄而不必登錄。

必須保護/oauth端點。

請嘗試以下方法

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/login.html", "/logout.do").permitAll()
            .antMatchers("/**").authenticated()
        .and()
        .formLogin()
            .loginProcessingUrl("/login")
            .loginPage("/login.html");
 }

我在github上有一個spring-security-oauth示例項目,你可以在這里查看https://github.com/FrontierPsychiatrist/spring-oauth-example/

我想我弄清楚問題是什么。

我在github上看到了以下示例,其中使用了基於表單的身份驗證機制(這是我正在尋找的)。

https://github.com/spring-guides/tut-spring-security-and-angular-js/

如果我使用非HTML頁面作為我的登錄頁面,確切的代碼工作正常。 例如,JSP或FTL。 該示例使用Freemarker。 如果我使用ftl頁面,我的設置一切正常。 但是.html頁面的情況也是如此。

首先,我正在嘗試impl。 使用grand_type = implicit授權OAuth

我建議您嘗試按照以下步驟解決與Spring中OAuth2相關的問題:

  1. 必要時嘗試指定現有的redirect_uri參數; 在OAuth2規范中它不是必需的參數,但在春季應用程序中它應該存在;
  2. 在WebSecurityConfigurerAdapter中打開了對Spring Secure登錄頁面的OAuth2訪問權限(您已經這樣做了)是必需的:
  3. 嘗試進行forvard排序: @Order(-1)用於擴展WebSecurityConfigurerAdapter 它解決了我在這個問題上的大多數問題;

WebSecurityConfigurerAdapter擴展器中的Ovveriden方法:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin()
                .permitAll()
                .loginPage("/common/login.html")
                .loginProcessingUrl("/login")
                .failureUrl("/common/error.html")
                .defaultSuccessUrl("/oauth/authorize")
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/common/**", "/v2/api-docs", "/configuration/ui", "/swagger-resources",
                "/configuration/security", "/swagger-ui.html", "/webjars/**");
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM