代码之家  ›  专栏  ›  技术社区  ›  jker

Webflux Spring中的OAuth2认证

  •  0
  • jker  · 技术社区  · 7 年前

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

    这是我的安全网络过滤器链:

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

    this article 我发现我应该配置资源服务器。请告诉我怎么做。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Matt Raible    7 年前

    您需要使用SpringBoot2.1的一个里程碑版本来实现这一点。M3或更高的应该可以。为SpringSecurity5.1OIDC支持添加必要的依赖项:

    <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>
    

    然后创建一个OktaOidc“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以登录。输入有效凭据,成功登录后将重定向回应用程序。

    要基于角色限制访问,需要为用户创建组。

    创建角色管理和角色用户组( 用户 > > 添加组 )并向其中添加用户。您可以使用已注册的帐户,或创建新用户( 用户 > 添加人员 ). 引导到 美国石油学会 > 授权服务器 ,单击 授权服务器 选项卡并编辑默认值。单击 声称 标签和 添加索赔 . 将其命名为组或角色,并将其包含在ID令牌中。将值类型设置为Groups,并将筛选器设置为一个“.*”(包括所有值)的正则表达式。

    那么你应该能够使用类似于:

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

    你也应该能够使用 @PreAuthorize 如中所述 this blog post .