首页 > 解决方案 > 在同一上下文中使用 Spring Boot 2 OAuth Client 和 Resourcesserver

问题描述

我希望我的 Spring Boot 应用程序服务于受保护的前端,同时作为所述前端的 API 资源服务器,但我无法让 oauth 的东西正常工作。

我想要的是当浏览器在没有令牌的情况下请求 index.html 时,spring boot 应用程序将 302 重定向返回到 oauth 服务器(在我的情况下为 gitlab),因此用户被发送到登录表单。但我也希望 API 在没有令牌的情况下调用 API 时返回 401,因为我认为 302 重定向到登录页面在那里不是很有用。

在伪代码中:

if document_url == /index.html and token not valid
  return 302 https//gitlab/loginpage
if document_url == /api/restcall and token not valid
  return 401
server document_url

我正在使用 spring boot 2.1,关于 oauth 我的 pom.xml 包含

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>

这是我在 SecurityConfig 中的天真尝试

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests().antMatchers("/index.html").authenticated()
        .and()
            .oauth2Login().loginPage("/oauth2/authorization/gitlab")

        .and()
            .authorizeRequests().antMatchers("/api/restcall").authenticated()
        .and()
            .oauth2ResourceServer().jwt();
    }
}

两种配置(oauth2Login 和 oauth2ResourceServer)都可以正常工作。但是一旦我将它们结合起来,最后一个就获胜了(所以在上面的例子中没有 302 并且浏览器也会看到 index.html 的 401)。我认为他们共享一些配置对象,所以最后一次写入获胜。

有没有(简单的)方法可以得到我想要的东西?我知道 spring 几乎可以做任何事情,但我非常不想最终手动配置一个 gazillion bean ...

更新:

我在这里做了一个我的代码的最小示例(包括@dur的建议)

标签: javaspring-bootspring-securityoauth-2.0

解决方案


您需要创建多个配置并使用requestMatcher. 根据您的示例,您的配置应如下所示:

安全配置HTML

public class SecurityConfigHTML extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().antMatchers("/index.html")
                .and()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .oauth2Login().loginPage("/oauth2/authorization/gitlab");
    }
}

安全配置API

public class SecurityConfigAPI extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().antMatchers("/api/call")
                .and()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .oauth2ResourceServer().jwt();
    }
}

推荐阅读