Add support for OAuth 2.0 Login
Fixes gh-3907
This commit is contained in:
@@ -77,6 +77,10 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
|
||||
order += STEP;
|
||||
put(LogoutFilter.class, order);
|
||||
order += STEP;
|
||||
filterToOrder.put(
|
||||
"org.springframework.security.oauth2.client.authentication.AuthorizationCodeRequestRedirectFilter",
|
||||
order);
|
||||
order += STEP;
|
||||
put(X509AuthenticationFilter.class, order);
|
||||
order += STEP;
|
||||
put(AbstractPreAuthenticatedProcessingFilter.class, order);
|
||||
@@ -84,6 +88,10 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
|
||||
filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter",
|
||||
order);
|
||||
order += STEP;
|
||||
filterToOrder.put(
|
||||
"org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationProcessingFilter",
|
||||
order);
|
||||
order += STEP;
|
||||
put(UsernamePasswordAuthenticationFilter.class, order);
|
||||
order += STEP;
|
||||
put(ConcurrentSessionFilter.class, order);
|
||||
|
||||
@@ -61,6 +61,7 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer;
|
||||
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
import org.springframework.security.web.PortMapper;
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
@@ -896,6 +897,158 @@ public final class HttpSecurity extends
|
||||
return getOrApply(new FormLoginConfigurer<HttpSecurity>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures authentication against an external <i>OAuth 2.0</i> or <i>OpenID Connect 1.0</i> Provider.
|
||||
* <br>
|
||||
* <br>
|
||||
*
|
||||
* The <i>"authentication flow"</i> is realized using the <b>Authorization Code Grant</b>,
|
||||
* as specified in the <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">OAuth 2.0 Authorization Framework</a>.
|
||||
* <br>
|
||||
* <br>
|
||||
*
|
||||
* As a prerequisite to using this feature, the developer must register a <i>Client</i> with an <i>Authorization Server</i>.
|
||||
* The output of the <i>Client Registration</i> process results in a number of properties that are then used for configuring
|
||||
* an instance of a {@link org.springframework.security.oauth2.client.registration.ClientRegistration}.
|
||||
* Properties specific to a <i>Client</i> include: <i>client_id</i>, <i>client_secret</i>, <i>scope</i>, <i>redirect_uri</i>, etc.
|
||||
* There are also properties specific to the <i>Provider</i>, for example,
|
||||
* <i>Authorization Endpoint URI</i>, <i>Token Endpoint URI</i>, <i>UserInfo Endpoint URI</i>, etc.
|
||||
* <br>
|
||||
* <br>
|
||||
*
|
||||
* Multiple client support is provided for use cases where the application provides the user the option
|
||||
* for <i>"Logging in"</i> against one or more Providers, for example, <i>Google</i>, <i>GitHub</i>, <i>Facebook</i>, etc.
|
||||
* <br>
|
||||
* <br>
|
||||
*
|
||||
* {@link org.springframework.security.oauth2.client.registration.ClientRegistration}(s) are composed within a
|
||||
* {@link org.springframework.security.oauth2.client.registration.ClientRegistrationRepository}.
|
||||
* An instance of {@link org.springframework.security.oauth2.client.registration.ClientRegistrationRepository} is <b>required</b>
|
||||
* and may be supplied via the {@link ApplicationContext} or configured using
|
||||
* {@link OAuth2LoginConfigurer#clients(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository)}.
|
||||
* <br>
|
||||
* <br>
|
||||
*
|
||||
* The default configuration provides an auto-generated login page at <code>"/login"</code> and
|
||||
* redirects to <code>"/login?error"</code> when an authentication error occurs.
|
||||
* The login page will display each of the clients (composed within the
|
||||
* {@link org.springframework.security.oauth2.client.registration.ClientRegistrationRepository})
|
||||
* with an anchor link to <code>"/oauth2/authorization/code/{clientAlias}"</code>.
|
||||
* Clicking through the link will initiate the <i>"Authorization Request"</i> flow
|
||||
* redirecting the end-user's user-agent to the <i>Authorization Endpoint</i> of the <i>Provider</i>.
|
||||
* Assuming the <i>Resource Owner</i> (end-user) grants the <i>Client</i> access, the <i>Authorization Server</i>
|
||||
* will redirect the end-user's user-agent to the <i>Redirection Endpoint</i> containing the <i>Authorization Code</i>
|
||||
* - the <i>Redirection Endpoint</i> is automatically configured for the application and
|
||||
* defaults to <code>"/oauth2/authorize/code/{clientAlias}"</code>.
|
||||
*
|
||||
* <p>
|
||||
* At this point in the <i>"authentication flow"</i>, the configured
|
||||
* {@link org.springframework.security.oauth2.client.authentication.AuthorizationGrantTokenExchanger}
|
||||
* will exchange the <i>Authorization Code</i> for an <i>Access Token</i> and then use it to access the protected resource
|
||||
* at the <i>UserInfo Endpoint</i> (via {@link org.springframework.security.oauth2.client.user.OAuth2UserService})
|
||||
* in order to retrieve the details of the <i>Resource Owner</i> (end-user) and establish the <i>"authenticated"</i> session.
|
||||
*
|
||||
* <h2>Example Configurations</h2>
|
||||
*
|
||||
* The minimal configuration defaults to automatically generating a login page at <code>"/login"</code>
|
||||
* and redirecting to <code>"/login?error"</code> when an authentication error occurs or redirecting to
|
||||
* <code>"/"</code> when an authenticated session is established.
|
||||
*
|
||||
* <pre>
|
||||
* @EnableWebSecurity
|
||||
* public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
*
|
||||
* @Override
|
||||
* protected void configure(HttpSecurity http) throws Exception {
|
||||
* http
|
||||
* .authorizeRequests()
|
||||
* .anyRequest().authenticated()
|
||||
* .and()
|
||||
* .oauth2Login();
|
||||
* }
|
||||
*
|
||||
* @Bean
|
||||
* public ClientRegistrationRepository clientRegistrationRepository() {
|
||||
* // ClientRegistrationRepositoryImpl must be composed of at least one ClientRegistration instance
|
||||
* return new ClientRegistrationRepositoryImpl();
|
||||
* }
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* The following shows the configuration options available for customizing the defaults.
|
||||
*
|
||||
* <pre>
|
||||
* @EnableWebSecurity
|
||||
* public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
*
|
||||
* @Override
|
||||
* protected void configure(HttpSecurity http) throws Exception {
|
||||
* http
|
||||
* .authorizeRequests()
|
||||
* .anyRequest().authenticated()
|
||||
* .and()
|
||||
* .oauth2Login()
|
||||
* .clients(this.clientRegistrationRepository())
|
||||
* .authorizationRequestBuilder(this.authorizationRequestBuilder())
|
||||
* .authorizationCodeTokenExchanger(this.authorizationCodeTokenExchanger())
|
||||
* .userInfoEndpoint()
|
||||
* .userInfoService(this.userInfoService())
|
||||
* .userInfoEndpoint()
|
||||
* // Provide a mapping between a Converter implementation and a UserInfo Endpoint URI
|
||||
* .userInfoTypeConverter(this.userInfoConverter(),
|
||||
* new URI("https://www.googleapis.com/oauth2/v3/userinfo"));
|
||||
* }
|
||||
*
|
||||
* @Bean
|
||||
* public ClientRegistrationRepository clientRegistrationRepository() {
|
||||
* // ClientRegistrationRepositoryImpl must be composed of at least one ClientRegistration instance
|
||||
* return new ClientRegistrationRepositoryImpl();
|
||||
* }
|
||||
*
|
||||
* @Bean
|
||||
* public AuthorizationRequestUriBuilder authorizationRequestBuilder() {
|
||||
* // Custom URI builder for the "Authorization Request"
|
||||
* return new AuthorizationRequestUriBuilderImpl();
|
||||
* }
|
||||
*
|
||||
* @Bean
|
||||
* public AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> authorizationCodeTokenExchanger() {
|
||||
* // Custom implementation that exchanges an "Authorization Code Grant" for an "Access Token"
|
||||
* return new AuthorizationCodeTokenExchangerImpl();
|
||||
* }
|
||||
*
|
||||
* @Bean
|
||||
* public OAuth2UserService userInfoService() {
|
||||
* // Custom implementation that retrieves the details of the authenticated user at the "UserInfo Endpoint"
|
||||
* return new OAuth2UserServiceImpl();
|
||||
* }
|
||||
*
|
||||
* @Bean
|
||||
* public Converter<ClientHttpResponse, UserInfo> userInfoConverter() {
|
||||
* // Default converter implementation for UserInfo
|
||||
* return new org.springframework.security.oauth2.client.user.converter.UserInfoConverter();
|
||||
* }
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @author Joe Grandja
|
||||
* @since 5.0
|
||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant Flow</a>
|
||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.1">Section 4.1.1 Authorization Request</a>
|
||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization Response</a>
|
||||
* @see org.springframework.security.oauth2.client.registration.ClientRegistration
|
||||
* @see org.springframework.security.oauth2.client.registration.ClientRegistrationRepository
|
||||
* @see org.springframework.security.oauth2.client.authentication.AuthorizationRequestUriBuilder
|
||||
* @see org.springframework.security.oauth2.client.authentication.AuthorizationGrantTokenExchanger
|
||||
* @see org.springframework.security.oauth2.client.user.OAuth2UserService
|
||||
*
|
||||
* @return the {@link OAuth2LoginConfigurer} for further customizations
|
||||
* @throws Exception
|
||||
*/
|
||||
public OAuth2LoginConfigurer<HttpSecurity> oauth2Login() throws Exception {
|
||||
return getOrApply(new OAuth2LoginConfigurer<HttpSecurity>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures channel security. In order for this configuration to be useful at least
|
||||
* one mapping to a required channel must be provided.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationProcessingFilter;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationProvider;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationToken;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationGrantTokenExchanger;
|
||||
import org.springframework.security.oauth2.client.authentication.nimbus.NimbusAuthorizationCodeTokenExchanger;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.user.OAuth2UserService;
|
||||
import org.springframework.security.oauth2.client.user.nimbus.NimbusOAuth2UserService;
|
||||
import org.springframework.security.oauth2.core.user.OAuth2User;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author Joe Grandja
|
||||
*/
|
||||
final class AuthorizationCodeAuthenticationFilterConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
AbstractAuthenticationFilterConfigurer<H, AuthorizationCodeAuthenticationFilterConfigurer<H>, AuthorizationCodeAuthenticationProcessingFilter> {
|
||||
|
||||
private AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> authorizationCodeTokenExchanger;
|
||||
private OAuth2UserService userInfoService;
|
||||
private Map<URI, Converter<ClientHttpResponse, ? extends OAuth2User>> userInfoTypeConverters = new HashMap<>();
|
||||
|
||||
|
||||
AuthorizationCodeAuthenticationFilterConfigurer() {
|
||||
super(new AuthorizationCodeAuthenticationProcessingFilter(), null);
|
||||
}
|
||||
|
||||
AuthorizationCodeAuthenticationFilterConfigurer<H> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
|
||||
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
|
||||
Assert.notEmpty(clientRegistrationRepository.getRegistrations(), "clientRegistrationRepository cannot be empty");
|
||||
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
|
||||
return this;
|
||||
}
|
||||
|
||||
AuthorizationCodeAuthenticationFilterConfigurer<H> authorizationCodeTokenExchanger(
|
||||
AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> authorizationCodeTokenExchanger) {
|
||||
|
||||
Assert.notNull(authorizationCodeTokenExchanger, "authorizationCodeTokenExchanger cannot be null");
|
||||
this.authorizationCodeTokenExchanger = authorizationCodeTokenExchanger;
|
||||
return this;
|
||||
}
|
||||
|
||||
AuthorizationCodeAuthenticationFilterConfigurer<H> userInfoService(OAuth2UserService userInfoService) {
|
||||
Assert.notNull(userInfoService, "userInfoService cannot be null");
|
||||
this.userInfoService = userInfoService;
|
||||
return this;
|
||||
}
|
||||
|
||||
AuthorizationCodeAuthenticationFilterConfigurer<H> userInfoTypeConverter(Converter<ClientHttpResponse, ? extends OAuth2User> userInfoConverter, URI userInfoUri) {
|
||||
Assert.notNull(userInfoConverter, "userInfoConverter cannot be null");
|
||||
Assert.notNull(userInfoUri, "userInfoUri cannot be null");
|
||||
this.userInfoTypeConverters.put(userInfoUri, userInfoConverter);
|
||||
return this;
|
||||
}
|
||||
|
||||
String getLoginUrl() {
|
||||
return super.getLoginPage();
|
||||
}
|
||||
|
||||
String getLoginFailureUrl() {
|
||||
return super.getFailureUrl();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(H http) throws Exception {
|
||||
AuthorizationCodeAuthenticationProvider authenticationProvider = new AuthorizationCodeAuthenticationProvider(
|
||||
this.getAuthorizationCodeTokenExchanger(), this.getUserInfoService());
|
||||
authenticationProvider = this.postProcess(authenticationProvider);
|
||||
http.authenticationProvider(authenticationProvider);
|
||||
super.init(http);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(H http) throws Exception {
|
||||
AuthorizationCodeAuthenticationProcessingFilter authFilter = this.getAuthenticationFilter();
|
||||
authFilter.setClientRegistrationRepository(OAuth2LoginConfigurer.getClientRegistrationRepository(this.getBuilder()));
|
||||
super.configure(http);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
|
||||
return this.getAuthenticationFilter().getAuthorizeRequestMatcher();
|
||||
}
|
||||
|
||||
private AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> getAuthorizationCodeTokenExchanger() {
|
||||
if (this.authorizationCodeTokenExchanger == null) {
|
||||
this.authorizationCodeTokenExchanger = new NimbusAuthorizationCodeTokenExchanger();
|
||||
}
|
||||
return this.authorizationCodeTokenExchanger;
|
||||
}
|
||||
|
||||
private OAuth2UserService getUserInfoService() {
|
||||
if (this.userInfoService == null) {
|
||||
this.userInfoService = new NimbusOAuth2UserService(this.userInfoTypeConverters);
|
||||
}
|
||||
return this.userInfoService;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
|
||||
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeRequestRedirectFilter;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationRequestUriBuilder;
|
||||
import org.springframework.security.oauth2.client.authentication.DefaultAuthorizationRequestUriBuilder;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* @author Joe Grandja
|
||||
*/
|
||||
final class AuthorizationCodeRequestRedirectFilterConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
AbstractHttpConfigurer<AuthorizationCodeRequestRedirectFilterConfigurer<B>, B> {
|
||||
|
||||
private AuthorizationRequestUriBuilder authorizationRequestBuilder;
|
||||
|
||||
AuthorizationCodeRequestRedirectFilterConfigurer<B> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
|
||||
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
|
||||
Assert.notEmpty(clientRegistrationRepository.getRegistrations(), "clientRegistrationRepository cannot be empty");
|
||||
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
|
||||
return this;
|
||||
}
|
||||
|
||||
AuthorizationCodeRequestRedirectFilterConfigurer<B> authorizationRequestBuilder(AuthorizationRequestUriBuilder authorizationRequestBuilder) {
|
||||
Assert.notNull(authorizationRequestBuilder, "authorizationRequestBuilder cannot be null");
|
||||
this.authorizationRequestBuilder = authorizationRequestBuilder;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(B http) throws Exception {
|
||||
AuthorizationCodeRequestRedirectFilter filter = new AuthorizationCodeRequestRedirectFilter(
|
||||
OAuth2LoginConfigurer.getClientRegistrationRepository(this.getBuilder()),
|
||||
this.getAuthorizationRequestBuilder());
|
||||
http.addFilter(this.postProcess(filter));
|
||||
}
|
||||
|
||||
private AuthorizationRequestUriBuilder getAuthorizationRequestBuilder() {
|
||||
if (this.authorizationRequestBuilder == null) {
|
||||
this.authorizationRequestBuilder = new DefaultAuthorizationRequestUriBuilder();
|
||||
}
|
||||
return this.authorizationRequestBuilder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationToken;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeRequestRedirectFilter;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationGrantTokenExchanger;
|
||||
import org.springframework.security.oauth2.client.authentication.AuthorizationRequestUriBuilder;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.user.OAuth2UserService;
|
||||
import org.springframework.security.oauth2.core.user.OAuth2User;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @author Joe Grandja
|
||||
*/
|
||||
public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
AbstractHttpConfigurer<OAuth2LoginConfigurer<B>, B> {
|
||||
|
||||
private final AuthorizationCodeRequestRedirectFilterConfigurer<B> authorizationCodeRequestRedirectFilterConfigurer;
|
||||
private final AuthorizationCodeAuthenticationFilterConfigurer<B> authorizationCodeAuthenticationFilterConfigurer;
|
||||
private final UserInfoEndpointConfig userInfoEndpointConfig;
|
||||
|
||||
public OAuth2LoginConfigurer() {
|
||||
this.authorizationCodeRequestRedirectFilterConfigurer = new AuthorizationCodeRequestRedirectFilterConfigurer<>();
|
||||
this.authorizationCodeAuthenticationFilterConfigurer = new AuthorizationCodeAuthenticationFilterConfigurer<>();
|
||||
this.userInfoEndpointConfig = new UserInfoEndpointConfig();
|
||||
}
|
||||
|
||||
public OAuth2LoginConfigurer<B> clients(ClientRegistration... clientRegistrations) {
|
||||
Assert.notEmpty(clientRegistrations, "clientRegistrations cannot be empty");
|
||||
return clients(new InMemoryClientRegistrationRepository(Arrays.asList(clientRegistrations)));
|
||||
}
|
||||
|
||||
public OAuth2LoginConfigurer<B> clients(ClientRegistrationRepository clientRegistrationRepository) {
|
||||
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
|
||||
Assert.notEmpty(clientRegistrationRepository.getRegistrations(), "clientRegistrationRepository cannot be empty");
|
||||
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
|
||||
return this;
|
||||
}
|
||||
|
||||
public OAuth2LoginConfigurer<B> authorizationRequestBuilder(AuthorizationRequestUriBuilder authorizationRequestBuilder) {
|
||||
Assert.notNull(authorizationRequestBuilder, "authorizationRequestBuilder cannot be null");
|
||||
this.authorizationCodeRequestRedirectFilterConfigurer.authorizationRequestBuilder(authorizationRequestBuilder);
|
||||
return this;
|
||||
}
|
||||
|
||||
public OAuth2LoginConfigurer<B> authorizationCodeTokenExchanger(
|
||||
AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> authorizationCodeTokenExchanger) {
|
||||
|
||||
Assert.notNull(authorizationCodeTokenExchanger, "authorizationCodeTokenExchanger cannot be null");
|
||||
this.authorizationCodeAuthenticationFilterConfigurer.authorizationCodeTokenExchanger(authorizationCodeTokenExchanger);
|
||||
return this;
|
||||
}
|
||||
|
||||
public UserInfoEndpointConfig userInfoEndpoint() {
|
||||
return this.userInfoEndpointConfig;
|
||||
}
|
||||
|
||||
public class UserInfoEndpointConfig {
|
||||
|
||||
private UserInfoEndpointConfig() {
|
||||
}
|
||||
|
||||
public OAuth2LoginConfigurer<B> userInfoService(OAuth2UserService userInfoService) {
|
||||
Assert.notNull(userInfoService, "userInfoService cannot be null");
|
||||
OAuth2LoginConfigurer.this.authorizationCodeAuthenticationFilterConfigurer.userInfoService(userInfoService);
|
||||
return this.and();
|
||||
}
|
||||
|
||||
public OAuth2LoginConfigurer<B> userInfoTypeConverter(Converter<ClientHttpResponse, ? extends OAuth2User> userInfoConverter, URI userInfoUri) {
|
||||
Assert.notNull(userInfoConverter, "userInfoConverter cannot be null");
|
||||
Assert.notNull(userInfoUri, "userInfoUri cannot be null");
|
||||
OAuth2LoginConfigurer.this.authorizationCodeAuthenticationFilterConfigurer.userInfoTypeConverter(userInfoConverter, userInfoUri);
|
||||
return this.and();
|
||||
}
|
||||
|
||||
public OAuth2LoginConfigurer<B> and() {
|
||||
return OAuth2LoginConfigurer.this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(B http) throws Exception {
|
||||
this.authorizationCodeRequestRedirectFilterConfigurer.setBuilder(http);
|
||||
this.authorizationCodeAuthenticationFilterConfigurer.setBuilder(http);
|
||||
|
||||
this.authorizationCodeRequestRedirectFilterConfigurer.init(http);
|
||||
this.authorizationCodeAuthenticationFilterConfigurer.init(http);
|
||||
this.initDefaultLoginFilter(http);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(B http) throws Exception {
|
||||
this.authorizationCodeRequestRedirectFilterConfigurer.configure(http);
|
||||
this.authorizationCodeAuthenticationFilterConfigurer.configure(http);
|
||||
}
|
||||
|
||||
static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getClientRegistrationRepository(B http) {
|
||||
ClientRegistrationRepository clientRegistrationRepository = http.getSharedObject(ClientRegistrationRepository.class);
|
||||
if (clientRegistrationRepository == null) {
|
||||
clientRegistrationRepository = getDefaultClientRegistrationRepository(http);
|
||||
http.setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
|
||||
}
|
||||
return clientRegistrationRepository;
|
||||
}
|
||||
|
||||
private static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getDefaultClientRegistrationRepository(B http) {
|
||||
return http.getSharedObject(ApplicationContext.class).getBean(ClientRegistrationRepository.class);
|
||||
}
|
||||
|
||||
private void initDefaultLoginFilter(B http) {
|
||||
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http.getSharedObject(DefaultLoginPageGeneratingFilter.class);
|
||||
if (loginPageGeneratingFilter != null && !this.authorizationCodeAuthenticationFilterConfigurer.isCustomLoginPage()) {
|
||||
ClientRegistrationRepository clientRegistrationRepository = getClientRegistrationRepository(this.getBuilder());
|
||||
if (!CollectionUtils.isEmpty(clientRegistrationRepository.getRegistrations())) {
|
||||
Map<String, String> oauth2AuthenticationUrlToClientName = clientRegistrationRepository.getRegistrations().stream()
|
||||
.collect(Collectors.toMap(e -> AuthorizationCodeRequestRedirectFilter.AUTHORIZATION_BASE_URI + "/" + e.getClientAlias(),
|
||||
e -> e.getClientName()));
|
||||
loginPageGeneratingFilter.setOauth2LoginEnabled(true);
|
||||
loginPageGeneratingFilter.setOauth2AuthenticationUrlToClientName(oauth2AuthenticationUrlToClientName);
|
||||
loginPageGeneratingFilter.setLoginPageUrl(this.authorizationCodeAuthenticationFilterConfigurer.getLoginUrl());
|
||||
loginPageGeneratingFilter.setFailureUrl(this.authorizationCodeAuthenticationFilterConfigurer.getLoginFailureUrl());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
|
||||
<p><font color='red'>Your login attempt was not successful, try again.<br/><br/>Reason: Bad credentials</font></p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<p style='color:red;'>Your login attempt was not successful, try again.<br/><br/>Reason: Bad credentials</p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<table>
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
@@ -107,7 +107,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to default success page"
|
||||
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
|
||||
<p><font color='green'>You have been logged out</font></p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<p style='color:green;'>You have been logged out</p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<table>
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
|
||||
Reference in New Issue
Block a user