如何使用Spring-Boot和OAuth2限制特定域登录

我已经使用spring boot和Google成功完成了OAuth2登录,但我想限制登录到特定域(我们正在使用Google Apps for Work)。

我认为我应该通过扩展类OAuth2ClientAuthenticationProcessingFilter( 在此线程中指定)来处理,但我不知道如何做到这一点。

基本上,我想使用Google OAuth 2.0作为身份提供商,但只能接受公司用户(@ company.com)。

根据Stéphane的建议,我参加了本教程 ,最后实现了这个,这对我来说适用于Google+个人资料:

 @Configuration @EnableOAuth2Sso public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String GOOGLE_PLUS_DOMAIN_ATTRIBUTE = "domain"; private static final String CSRF_COOKIE_NAME = "XSRF-TOKEN"; private static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN"; @Bean public AuthoritiesExtractor authoritiesExtractor( @Value("#{'${security.allowed-domains}'.split(',')}") final List allowedDomains) { return new AuthoritiesExtractor() { @Override public List extractAuthorities(final Map map) { if (map != null && map.containsKey(GOOGLE_PLUS_DOMAIN_ATTRIBUTE)) { final String domain = (String) map.get(GOOGLE_PLUS_DOMAIN_ATTRIBUTE); if (!allowedDomains.contains(domain)) { throw new BadCredentialsException("Not an allowed domain"); } return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"); } return null; } }; } @Override protected void configure(final HttpSecurity http) throws Exception { // @formatter:off http.antMatcher("/**") .authorizeRequests() .antMatchers("/logout", "/api/mappings/**", "/public/**").permitAll() .anyRequest().hasAuthority("ROLE_USER") .and().logout().logoutUrl("/api/logout").logoutSuccessUrl("/logout") .and().csrf().csrfTokenRepository(csrfTokenRepository()).ignoringAntMatchers("/api/mappings/**") .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class); // @formatter:on } private Filter csrfHeaderFilter() { return new OncePerRequestFilter() { @Override protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (csrf != null) { Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME); final String token = csrf.getToken(); if (cookie == null || token != null && !token.equals(cookie.getValue())) { cookie = new Cookie(CSRF_COOKIE_NAME, token); cookie.setPath("/"); response.addCookie(cookie); } } filterChain.doFilter(request, response); } }; } private CsrfTokenRepository csrfTokenRepository() { final HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); repository.setHeaderName(CSRF_HEADER_NAME); return repository; } } 

我的application.yml文件包含有关oauth的以下条目:

 security: oauth2: client: access-token-uri: https://www.googleapis.com/oauth2/v3/token user-authorization-uri: https://accounts.google.com/o/oauth2/auth client-authentication-scheme: form scope: profile,email resource: user-info-uri: https://www.googleapis.com/plus/v1/people/me prefer-token-info: false 

使用Google+个人资料时,地图中提供的资源服务器响应包含域名条目。 我只是将此值与已配置的允许域进行了比较。

希望这可以帮助。