【问题标题】:How to configure oAuth2 when Authorization Server is also the Resource server当授权服务器也是资源服务器时如何配置 oAuth2
【发布时间】:2019-02-22 06:33:28
【问题描述】:

我正在尝试使用 授权码授权隐式授权 在 spring boot 2.xx 中设置一个非常基本的 oAuth2 身份验证,但我似乎无法访问获取令牌后的资源服务器(与授权服务器位于同一个 spring boot 应用中)。

以下是WebSecurityConfigurerAdapter的配置

@EnableWebSecurity
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String[] IGNORE_URIS = {
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/v2/api-docs",
            "/webjars/**",
            "/resources/**",
            "/h2-console/**",
            "/common/**",
            "/configuration/ui",
            "/configuration/security",
            "/error"
    };

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


    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(IGNORE_URIS);
    }

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

        http.authorizeRequests()
                .antMatchers("/product/**")
                .hasAnyRole("ADMIN").and()
                .httpBasic().and().formLogin().and().authorizeRequests().anyRequest().authenticated();

    }

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

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

还有AuthorizationServerConfigurerAdapter

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;

    @Autowired
    public AuthorizationServerConfiguration(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("my-client-id")
                .authorizedGrantTypes("authorization_code", "implicit")
                .authorities("ADMIN")
                .scopes("all")
                .resourceIds("product_api")
                .secret("{noop}secret").redirectUris("https://google.com").accessTokenValiditySeconds(0);
    }

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

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

到目前为止一切顺利。我可以通过在浏览器中输入以下 URL 来访问默认的 Spring 登录页面。

http://localhost:8080/oauth/authorize?response_type=token&client_id=my-client-id&redirect_uri=https://google.com

然后登录页面出现,我输入我的凭据。

登录后,我可以授予对 "my-client-id" 应用程序的访问权限。

最终在我批准应用程序后,我可以在浏览器的 URL 栏中看到新生成的访问令牌,类似于这样。

https://www.google.com/#access_token=f2153498-6a26-42c6-93f0-80825ef03b16&token_type=bearer&scope=all

我的问题是,当我还配置资源服务器时,所有这些流程都不起作用。

@EnableResourceServer
@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId("product_api");
    }


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers()
                .antMatchers("/**")
                .and().authorizeRequests()
                .antMatchers("/**").permitAll();
    }
}

我做错了什么?当我尝试访问 oauth/authorize 网址时,我得到以下信息:

为什么?如何访问登录页面并检索令牌?我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    你需要使用

    @Order 
    

    为 WebMvc 和 ResourceServer 类指定顺序的注解

    @EnableWebSecurity
    @Configuration
    @Order(1)
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    ...
    }
    

    对于资源服务器

    @EnableResourceServer
    @Configuration
    @Order(2)
    public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    ...
    }
    

    如果你想看可行的例子,你可以在这里查看https://github.com/alex-petrov81/stackoverflow-answers/tree/master/auth-server-also-resource 我已经从您的代码示例中创建了它。

    【讨论】:

    • 那些 Spring 魔术注释再次解决了我的问题。感谢您的工作示例!
    • 首先非常感谢这个例子!我目前正在实施类似的东西。我遵循了您的可行示例,并且能够获取令牌,但是当我想使用令牌访问我的资源时,我得到了 401 未经授权的响应。你知道为什么会发生这种情况吗?对我来说,似乎 WebSecurityConfiguration 捕获了所有请求,并且不让 ResourceServerConfiguration 处理任何事情,因此我得到了 401
    • @grahan 我也有同样的问题,你解决了吗?
    猜你喜欢
    • 2019-10-27
    • 2015-11-19
    • 2016-05-21
    • 2014-07-09
    • 2018-08-29
    • 2015-05-14
    • 2022-08-03
    • 2017-11-10
    • 2022-11-23
    相关资源
    最近更新 更多