首页 > 解决方案 > 如何在 Spring Security Oauth2 客户端中定义自定义授权类型?

问题描述

我有一个基于spring-boot 2.2构建的工作api-gateway应用程序,这是一个支持授权码授予流程的Oauth2 客户端。它是使用spring-boot @EnableOAuth2Sso 构建的,一旦用户成功登录,它将创建一个 spring 会话和 oauth2 上下文。对资源服务器的每个请求都将被这个 api-gateway 拦截,并验证用户会话也是 oauth2来自会话上下文的令牌。所有资源服务器均受 Oauth2 保护。

我还需要通过此网关支持SAML2 登录。我已将WSO2 设置为 Identity provider ,一旦用户通过 IDP 启动的登录流程成功登录,它将SAML 响应作为 POST 请求提供给 api-gateway 中的端点。现在,当我提交带有 SAML 断言和 SAML 授权类型的令牌请求时,WSO2 IDP 能够为我提供 Oauth2 令牌。我需要的是当 SAML POST 请求来自 WSO2 IDP 到 api-gateway 时,它应该使用 SAML 断言和 SAML 授权类型从 WSO2 创建一个 Oauth2 令牌,还应该使用这个收到的 Oauth2 令牌创建一个 Spring 会话和 Oauth2 上下文.

目前我有两种可能的选择,

1) 在 api-gateway Oauth2 客户端中定义一个自定义的 spring security Oauth2 grant-type,并使用 spring-security 以及 Spring session 和 Oauth2 context 处理 SAML 响应以生成 Oauth2 令牌。

2)手动编写代码使用 SAML 响应生成 Oauth2 令牌,还手动创建一个新的 Spring 会话和 Oauth2 上下文,这将是一个丑陋的方法。

下面给出了当前的安全配置类。

@Configuration
@EnableOAuth2Sso
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String ROOT_PATH = "/";
    private static final String SUFFIX = "**";
    private static final String ANY_OTHER = "/webjars";

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .antMatcher(ROOT_PATH + SUFFIX)
            .authorizeRequests()
              .antMatchers(LOGIN_PATH.value() + SUFFIX, ERROR_PATH.value() + SUFFIX, ANY_OTHER + SUFFIX, "/saml**").permitAll()
              .antMatchers(HttpMethod.POST, "/saml**").permitAll()
            .anyRequest()
              .authenticated()
            .and().csrf().ignoringAntMatchers("/saml**")
            .and().logout().logoutSuccessUrl(LOGOUT_SUCCESS_PATH.value()).permitAll();

        }

        @Bean
        public OAuth2RestOperations restTemplate(OAuth2ClientContext clientContext, OAuth2ProtectedResourceDetails resourceDetails) {
            return new OAuth2RestTemplate(resourceDetails, clientContext);
        }

        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Bean
        public FilterRegistrationBean oauth2ClientFilterRedirectRegistration(OAuth2ClientContextFilter filter) {
          FilterRegistrationBean registration = new FilterRegistrationBean();
          registration.setFilter(filter);
          registration.setOrder(-100);
          return registration;
        }
}

Yml配置如下

security:
  basic:
    enabled: false
  oauth2:
    client:
      clientId: xxxx
      clientSecret: xxxxx
      accessTokenUri: http://localhost:9763/oauth2/token
      userAuthorizationUri: http://localhost:9763/oauth2/authorize
      scope: openid,email,name
    resource:
      userInfoUri: http://localhost:9763/oauth2/userinfo
      jwk: 
        key-set-uri: http://localhost:9763/oauth2/jwks

有人可以建议我们如何在 Oauth2 客户端中定义自定义 Spring Security Oauth2 授权类型吗?是否有任何可用于配置的文档?spring-security 是否支持此要求?

还有其他解决方案可以处理这种情况吗?请有任何建议。

标签: spring-bootspring-securityspring-security-oauth2spring-samlspring-session

解决方案


推荐阅读