【问题标题】:Authentication with OAuth2 in Webflux Spring在 Webflux Spring 中使用 OAuth2 进行身份验证
【发布时间】:2019-03-18 10:49:08
【问题描述】:

我正在开发一个应用程序,我想在其中进行基于角色的访问控制,不幸的是我没有找到任何使用 spring webflux 的好例子。 我的 oauth2.client.provider 是 Okta。

这是我的 SecurityWebFilterChain:

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        return http
                .authorizeExchange()
                .pathMatchers("/*").permitAll()
                .pathMatchers("/admin").hasRole("admins");
}

this article我发现我应该配置资源服务器。请给我一个提示如何做到这一点。

【问题讨论】:

标签: spring spring-boot oauth spring-webflux okta


【解决方案1】:

您需要使用 Spring Boot 2.1 的里程碑版本才能使其工作。 M3 或更高版本应该可以解决问题。为 Spring Security 5.1 OIDC 支持添加必要的依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-jose</artifactId>
</dependency>

然后创建一个 Okta OIDC“Web”应用程序并将您的设置复制到 src/main/resources/application.yml

spring:
  security:
    oauth2:
      client:
        provider:
          okta:
            issuer-uri: https://dev-737523.oktapreview.com/oauth2/default
        registration:
          login:
            okta:
              client-id: {clientId}
              client-secret: {clientSecret}
              scope: openid email profile

重新启动您的应用程序,转到http://localhost:8080,您应该会被重定向到 Okta 进行登录。输入有效的凭据,成功登录后您将被重定向回您的应用程序。

要根据角色限制访问权限,您需要为您的用户创建组。

创建一个 ROLE_ADMIN 和 ROLE_USER 组(Users > Groups > Add Group)并向其中添加用户。您可以使用您注册的帐户,也可以创建一个新用户(Users > Add Person)。导航到 API > Authorization Servers,点击 Authorization Servers 选项卡并编辑默认选项。点击声明标签和添加声明。将其命名为“组”或“角色”,并将其包含在 ID 令牌中。将值类型设置为“组”,并将过滤器设置为“.*”的正则表达式(以包括所有这些)。

那么你应该可以使用类似的东西:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    return http
            .authorizeExchange()
            .pathMatchers("/*").permitAll()
            .pathMatchers("/admin").hasAuthority("ROLE_ADMIN");
}

您还应该能够使用@PreAuthorize 中提到的this blog post

【讨论】:

  • 我做到了,但不是基于角色的访问控制
  • 我更新了答案以包括基于角色的访问控制。
  • 我以前试过。当我尝试加载“/admin”时,出现“需要身份验证”弹出窗口。我想被重定向到 okta 登录页面。
  • 您可能需要将@EnableWebFluxSecurity 添加到您的配置类中。也可能是.and().oauth2Login()。看这个类的例子:github.com/oktadeveloper/okta-spring-webflux-react-example/blob/…
猜你喜欢
  • 1970-01-01
  • 2017-10-01
  • 2017-12-26
  • 2014-09-15
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多