使用 OAuth2 SSO 在 spring-boot 应用程序中禁用 CSRF

dan*_*nze 6 java csrf oauth-2.0 spring-boot okta-api

我有一个 spring-boot 服务,它使用 OpenID Connect/OAuth2 通过 Okta Platform API 对用户进行身份验证。当用户尝试访问我的服务时,他们被重定向到 Okta 登录页面并进行身份验证,然后 Okta 将他们重定向回我的服务。

这是我的 pom.xml 的相关部分

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Run Code Online (Sandbox Code Playgroud)

这是我的控制器代码:

@RestController
@EnableOAuth2Sso
@SpringBootApplication
public class Application {

    @RequestMapping(path = "/", method = RequestMethod.GET)
    public String home(Authentication auth) {
        return "Home: " + auth.getName();
    }

    @RequestMapping(path = "/app", method = RequestMethod.POST)
    public String app(Authentication auth) {
        return "App: " + auth.getName();
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

这对于第一个 GET 控制器方法非常有效,但对于第二个 POST 方法,我的服务要求我提供 CSRF 令牌。我想完全禁用 CSRF 检查,所以我将它添加到我的应用程序中

@Configuration
@EnableOAuth2Sso
public class Config extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,添加上述配置后,我的服务停止使用 Okta 对用户进行身份验证(不再将未经身份验证的请求重定向到 Okta)。它直接调用带有空参数的 home() 方法。

我按照这篇博文创建了我的服务https://developer.okta.com/blog/2017/03/21/spring-boot-oauth

如何在仍然使用 Okta 的 OAuth2 SSO 身份验证的同时完全禁用 CSRF?

小智 0

您只需为 /app 端点禁用 CSRF 令牌。尝试用这个:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.mvcMatcher("/app").csrf().disable();
}
Run Code Online (Sandbox Code Playgroud)