Spring oauth2授权代码授权 - Impossibile to reach / oauth / authorize

时间:2017-04-05 21:15:45

标签: spring spring-security spring-security-oauth2

我试图通过授权代码流程保护我的休息API,但我不明白为什么我会收到消息:

User must be authenticated with Spring Security before authorization can be completed.

我有一个具有User和Admin访问权限的应用程序的Web部分,以及带有2个不同授权的REST api部分,/ api / **授权代码和带有client_credentials的/ oauth2 / **。

client_credential流程工作,但授权代码nope ...

所以,这是我的授权服务器配置

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

}

这是我的资源服务器配置

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

    @Autowired
    DataSource dataSource;

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

           http
    .requestMatchers()
    .antMatchers("/api/**")
    .antMatchers("/oauth2/**")
    .and().authorizeRequests()
    .antMatchers("/api/**").access("hasRole('USER')")
    .antMatchers("/oauth2/**").authenticated()
    .and().httpBasic();
        }

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

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

            resources.tokenStore(tokenStore());
        }
}

最后,这是一般的安全性

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configureGlobalService(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

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

        http.authorizeRequests()

                .antMatchers("/", "/registration", "/registrationConfirm", "/resendRegistrationToken")
                .permitAll()

                .antMatchers("/edit/**", "/payment/**", "/plate/**", "/book/**", "/home", "/stop/**",
                        "/notification/**", "/include/**")
                .access("hasRole('USER') or hasRole('ADMIN') or hasRole('PARK')").antMatchers("/admin/**")
                .access("hasRole('ADMIN') or hasRole('PARK')").antMatchers("/updatePassword")
                .hasAuthority("CHANGE_PASSWORD_PRIVILEGE")

                .and().formLogin().loginPage("/")
                .successHandler(customSuccessHandler).failureHandler(customAuthenticationFailureHandler)
                .usernameParameter("email").passwordParameter("password").and().rememberMe()
                .rememberMeParameter("remember-me").tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(86400).and().exceptionHandling().accessDeniedPage("/Access_Denied").and()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/?logout=true").invalidateHttpSession(false).deleteCookies("JSESSIONID");

        http.csrf().disable();

    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource);
        return db;
    }

}

oauth_client_details 表中的用户将ROLE_USER作为权限,client_id和client_secret是test / test

我正在寻找使用POSTMAN获取令牌的方式

POSTMAN OAUTH2 Token request

但是我得到了例外

ERROR i.b.e.e.RestResponseEntityExceptionHandler[66] - 500 Status Code org.springframework.security.authentication.InsufficientAuthenticationException: User must be authenticated with Spring Security before authorization can be completed.

编辑这是我按下“请求令牌”按钮时看到的内容

Response

修改 检查日志我还发现在我的安全过滤器链中没有Oauth2的任何过滤器的迹象......在提出获取授权令牌的请求时,我看到:

2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 8 of 12 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[325] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback&response_type=code at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-04-07 22:50:34 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy[310] - /oauth/authorize?client_id=test&scope=&state=7220832&redirect_uri=https%3A%2F%2Fwww.getpostman

1 个答案:

答案 0 :(得分:5)

您的代码存在的问题是SecurityConfiguration内部的这一部分:

.and().formLogin().loginPage("/")

Spring没有检测到您的登录页面,因此您无法重定向到以用户身份对其进行身份验证。

解决方案是将其更改为:

.and().formLogin()

然后,您将使用Spring的默认登录页面,授权代码流应该可以使用。在此之后,您需要调试为什么没有检测到'/'的登录页面。

修改

真正的问题是RestResponseEntityExceptionHandler.class是一个@ControllerAdvice注释类,它正在弄乱ExceptionTranslationFilter中发布的重定向。这是因为它捕获异常并将其抛到前端而不允许ExceptionTranslationFilter向登录页面发出重定向。删除RestResponseEntityExceptionHandler.class的使用可以解决问题,并且验证代码流可以正常工作。