Spring MVC同一应用如何按域名配置不同OAuth2 SSO登录
按域名自动分流SSO登录实现方案
核心逻辑:通过Spring Security多过滤链机制,给不同域名绑定独立的安全规则,直接指定对应域名固定使用的SSO客户端,从流程上跳过默认的登录选项选择页。
前置准备
先给两个SSO客户端设置固定的registrationId,后续直接通过ID指定使用的客户端:
- Microsoft SSO 客户端registrationId设为
microsoft - Google SSO 客户端registrationId设为
google
你原有的ClientRegistrationRepository注册两个客户端的Bean可以直接保留,不需要修改。
配置步骤
删除原有的全局configure(HttpSecurity http)配置,改为编写两个独立的、带优先级的安全配置类,分别匹配对应域名:
admin子域名配置(Microsoft SSO)
配置优先级设为最高,仅匹配admin.abc.com域名的请求,直接绑定Microsoft SSO的授权入口:@Configuration @Order(1) // 高优先级,优先匹配admin域名请求 public class AdminSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatchers() .requestMatchers(req -> "admin.abc.com".equals(req.getServerName())) .and() .authorizeRequests() .antMatchers("/login.htm").authenticated() .anyRequest().permitAll() .and() .logout() .logoutSuccessHandler(oauthLogoutSuccessHandler()) .invalidateHttpSession(true) .logoutUrl("/logout") .and() .oauth2Login() // 直接指定登录入口为Microsoft SSO授权地址,跳过选择页 .loginPage("/oauth2/authorization/microsoft") .failureHandler(new CustomAuthenticationFailureHandler()) .tokenEndpoint() .accessTokenResponseClient(authorizationCodeTokenResponseClient()) .and() // 原有自定义AuthorizationRequestResolver需要保留的话,在这里配置即可 // .authorizationEndpoint().authorizationRequestResolver(customResolver) .and() .headers() .frameOptions().sameOrigin() .and() .csrf().disable(); } // 注入项目中已有的相关Bean即可:oauthLogoutSuccessHandler、authorizationCodeTokenResponseClient等 }主域名配置(Google SSO)
配置优先级低于admin域名配置,仅匹配abc.com域名的请求,直接绑定Google SSO的授权入口:@Configuration @Order(2) public class MainSiteSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatchers() .requestMatchers(req -> "abc.com".equals(req.getServerName())) .and() .authorizeRequests() .antMatchers("/login.htm").authenticated() .anyRequest().permitAll() .and() .logout() .logoutSuccessHandler(oauthLogoutSuccessHandler()) .invalidateHttpSession(true) .logoutUrl("/logout") .and() .oauth2Login() // 直接指定登录入口为Google SSO授权地址,跳过选择页 .loginPage("/oauth2/authorization/google") .failureHandler(new CustomAuthenticationFailureHandler()) .tokenEndpoint() .accessTokenResponseClient(authorizationCodeTokenResponseClient()) .and() // 自定义AuthorizationRequestResolver按需保留 .and() .headers() .frameOptions().sameOrigin() .and() .csrf().disable(); } }
注意事项
- 不要保留原有的全局安全配置类,否则会出现过滤链匹配冲突,导致规则不生效。
- 本地调试时如果需要测试,可以在域名判断逻辑里加上
localhost、127.0.0.1等本地地址的匹配规则,方便开发环境调试。 - 两个域名的回调地址需要分别在对应SSO服务商后台配置正确:
- Microsoft Azure后台配置回调地址为
https://admin.abc.com/login/oauth2/code/microsoft - Google Cloud后台配置回调地址为
https://abc.com/login/oauth2/code/google
- Microsoft Azure后台配置回调地址为
内容的提问来源于stack exchange,提问作者nps
相关产品推荐
相关产品推荐

