【问题标题】:Authorization code grant授权码授予
【发布时间】:2018-01-12 13:02:49
【问题描述】:

我正在开发一个 REST API,它在 localhost 上侦听,我想包含 Spring Security。密码授予和客户端凭据授予完美运行,我可以检查 /smarthouse 和 /smarthouse2 中的安全数据。

虽然,当我尝试通过邮递员使用授权码授予时,它给了我同样的错误,我到处检查。我的项目在这里:https://github.com/sharjak/Smarthouse。操作都发生在 demoapplication 文件夹中。

Authorization code in Postman

我的授权和资源服务器代码:

@Configuration
public class OAuth2ServerConfig {

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .anonymous().disable()
                    .csrf().disable()
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated().and()
                    .formLogin();
            }
        }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private TokenStore tokenStore;

        @Autowired
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

            clients.inMemory().withClient("my-trusted-client")
                    .authorizedGrantTypes("password","authorization_code","refresh_token", "implicit")
                    .authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT","ROLE_USER")
                    .scopes("read", "write", "trust")
                    .resourceIds("oauth2-resource")
                    .secret("secret")
                    .accessTokenValiditySeconds(6000)
                    .and()

                    .withClient("my-client")
                    .authorizedGrantTypes("authorization_code", "implicit")
                    .authorities("ROLE_CLIENT", "ROLE_USER")
                    .scopes("read","trust", "write")
                    .resourceIds("oauth2-resource")
                    .accessTokenValiditySeconds(6000)
                    .and()

                    .withClient("my-client-with-secret")
                    .authorizedGrantTypes("client_credentials","password")
                    .authorities("ROLE_CLIENT", "ROLE_USER")
                    .scopes("read", "trust", "write")
                    .resourceIds("oauth2-resource")
                    .secret("secret")
                    .accessTokenValiditySeconds(6000);
        }

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

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                    .authenticationManager(authenticationManager)
                    .tokenStore(tokenStore);
        }

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

网络安全服务器代码:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ClientDetailsService clientDetailsService;

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

        http
                .anonymous().disable()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/smarthouse", "smarthouse2", "/user").permitAll()
                .and()
                .formLogin();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("password").roles("ADMIN")
                .and()
                .withUser("sander").password("Sander123").roles("USER");
    }

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

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

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }
}

当我尝试使用用户登录时的堆栈跟踪:

    org.springframework.security.authentication.InsufficientAuthenticationException: User must be authenticated with Spring Security before authorization can be completed.
        at org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(AuthorizationEndpoint.java:138)

我是一个初学者,但这似乎是一个需要解决的小问题。谁能帮帮我?

【问题讨论】:

  • 那么你想要的是使用 Postman 获取访问令牌?
  • 是的,问题是,当我用用户登录时,它没有给我授权码,而是告诉我用户必须经过身份验证。如果我尝试从浏览器登录,它会给我一个错误 Authentication object is not found in the security context.

标签: rest authentication spring-boot authorization spring-security-oauth2


【解决方案1】:

您只需将 configure 方法从 WebSecurityConfig 更改为以下内容:

http
    .authorizeRequests()
        .antMatchers("/login", "/favicon.ico",
            "/oauth/confirm_access", "/oauth/token", "/smarthouse",
            "smarthouse2", "/user").permitAll()
        .anyRequest().authenticated().and()
    .csrf().disable();

为什么要禁用匿名访问? 另一点是声明匹配器的顺序很重要。

我已经克隆了你的 repo 并且对我有用。

【讨论】:

  • 当我不禁用匿名时,它会给我一个错误访问被拒绝,用户是匿名的。我试过了,但它仍然给我同样的错误:在 SecurityContext 中找不到身份验证对象。这似乎是一个无限循环,用户通过身份验证,然后重定向到授权页面,但无法检索用户名和密码,然后重定向回登录页面。
  • 刚刚找到解决方案,我在application.yml中配置错误。必须删除 security.oauth2.resource.filer-order:3 然后它才起作用!
猜你喜欢
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-31
  • 2020-09-08
相关资源
最近更新 更多