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

bes*_*art 0 spring spring-security spring-security-oauth2

我正在尝试用授权代码流保护我的休息api,但我不明白为什么我收到消息:

User must be authenticated with Spring Security before authorization can be completed.
Run Code Online (Sandbox Code Playgroud)

我有一个具有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);
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我的资源服务器配置

@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());
        }
}
Run Code Online (Sandbox Code Playgroud)

最后,这是一般的安全性

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

}
Run Code Online (Sandbox Code Playgroud)

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

这就是我正在寻找用POSTMAN获取令牌的方法

POSTMAN OAUTH2令牌请求

但我得到了例外

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.
Run Code Online (Sandbox Code Playgroud)

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

响应

编辑 检查日志我还发现在我的安全过滤器链中没有任何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
Run Code Online (Sandbox Code Playgroud)

Luk*_*ada 5

代码的问题在于以下部分SecurityConfiguration:

.and().formLogin().loginPage("/")
Run Code Online (Sandbox Code Playgroud)

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

解决方案是将其更改为:

.and().formLogin()
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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