在同一上下文中使用 Spring Boot 2 OAuth Client 和 Resourceserver

sch*_*rom 7 java spring-security oauth-2.0 spring-boot

我希望我的 Spring Boot 应用程序能够为受保护的前端提供服务,并同时作为所述前端的 API 资源服务器,但我无法让 oauth 工作。

我想要的是 Spring Boot 应用程序在浏览器请求 index.html 而不带令牌时将 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
Run Code Online (Sandbox Code Playgroud)

我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

这是我在 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

两种配置(oauth2Login 和 oauth2ResourceServer)都适合自己。但是一旦我将它们组合起来,最后一个就会获胜(因此在上面的示例中,将没有 302,并且浏览器也会看到 index.html 的 401)。我认为他们共享一些配置对象,因此最后一次写入获胜。

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

更新:

我做了一个小例子(包括@杜尔的建议),我的代码在这里

Ana*_*nov 7

您需要创建多个配置并使用 将它们限制为特定的 URL 模式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");
    }
}
Run Code Online (Sandbox Code Playgroud)

安全配置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();
    }
}
Run Code Online (Sandbox Code Playgroud)