diff --git a/config/spring-security-config.gradle b/config/spring-security-config.gradle index be2ef37316..9881e78d15 100644 --- a/config/spring-security-config.gradle +++ b/config/spring-security-config.gradle @@ -23,7 +23,6 @@ dependencies { optional project(':spring-security-oauth2-client') optional project(':spring-security-oauth2-jose') optional project(':spring-security-oauth2-resource-server') - optional project(':spring-security-openid') optional project(':spring-security-rsocket') optional project(':spring-security-web') optional 'io.projectreactor:reactor-core' @@ -80,10 +79,6 @@ dependencies { testImplementation 'org.hsqldb:hsqldb' testImplementation 'org.mockito:mockito-core' testImplementation "org.mockito:mockito-inline" - testImplementation ('org.openid4java:openid4java-nodeps') { - exclude group: 'com.google.code.guice', module: 'guice' - exclude group: 'commons-logging', module: 'commons-logging' - } testImplementation('org.seleniumhq.selenium:htmlunit-driver') { exclude group: 'commons-logging', module: 'commons-logging' } diff --git a/config/src/main/java/org/springframework/security/config/Elements.java b/config/src/main/java/org/springframework/security/config/Elements.java index 0b79c47d65..f5beb02ff4 100644 --- a/config/src/main/java/org/springframework/security/config/Elements.java +++ b/config/src/main/java/org/springframework/security/config/Elements.java @@ -72,12 +72,6 @@ public abstract class Elements { public static final String FORM_LOGIN = "form-login"; - public static final String OPENID_LOGIN = "openid-login"; - - public static final String OPENID_ATTRIBUTE_EXCHANGE = "attribute-exchange"; - - public static final String OPENID_ATTRIBUTE = "openid-attribute"; - public static final String BASIC_AUTH = "http-basic"; public static final String REMEMBER_ME = "remember-me"; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java b/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java index c3da8890e3..28aa1f641e 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java @@ -23,7 +23,6 @@ import org.springframework.security.config.annotation.SecurityBuilder; import org.springframework.security.config.annotation.SecurityConfigurer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.openid.OpenIDAuthenticationFilter; import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.access.ExceptionTranslationFilter; import org.springframework.security.web.access.channel.ChannelProcessingFilter; @@ -132,7 +131,6 @@ public interface HttpSecurityBuilder> *
  • CasAuthenticationFilter
  • *
  • {@link UsernamePasswordAuthenticationFilter}
  • - *
  • {@link OpenIDAuthenticationFilter}
  • *
  • {@link org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter}
  • *
  • {@link org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter}
  • *
  • {@link ConcurrentSessionFilter}
  • diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java index 2026e7d855..f00cecd394 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java @@ -91,7 +91,6 @@ final class FilterOrderRegistration { order.next()); put(UsernamePasswordAuthenticationFilter.class, order.next()); order.next(); // gh-8105 - this.filterToOrder.put("org.springframework.security.openid.OpenIDAuthenticationFilter", order.next()); put(DefaultLoginPageGeneratingFilter.class, order.next()); put(DefaultLogoutPageGeneratingFilter.class, order.next()); put(ConcurrentSessionFilter.class, order.next()); diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java index 7f04681042..1302cc2f68 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java @@ -70,7 +70,6 @@ import org.springframework.security.config.annotation.web.configurers.X509Config import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2ClientConfigurer; import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer; import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; -import org.springframework.security.config.annotation.web.configurers.openid.OpenIDLoginConfigurer; import org.springframework.security.config.annotation.web.configurers.saml2.Saml2LoginConfigurer; import org.springframework.security.config.annotation.web.configurers.saml2.Saml2LogoutConfigurer; import org.springframework.security.core.Authentication; @@ -171,219 +170,6 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilderExample Configurations - * - * A basic example accepting the defaults and not using attribute exchange: - * - *
    -	 * @Configuration
    -	 * @EnableWebSecurity
    -	 * public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
    -	 *
    -	 * 	@Override
    -	 * 	protected void configure(HttpSecurity http) {
    -	 * 		http.authorizeRequests().antMatchers("/**").hasRole("USER").and().openidLogin()
    -	 * 				.permitAll();
    -	 * 	}
    -	 *
    -	 * 	@Override
    -	 * 	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    -	 * 		auth.inMemoryAuthentication()
    -	 * 				// the username must match the OpenID of the user you are
    -	 * 				// logging in with
    -	 * 				.withUser(
    -	 * 						"https://www.google.com/accounts/o8/id?id=lmkCn9xzPdsxVwG7pjYMuDgNNdASFmobNkcRPaWU")
    -	 * 				.password("password").roles("USER");
    -	 * 	}
    -	 * }
    -	 * 
    - * - * A more advanced example demonstrating using attribute exchange and providing a - * custom AuthenticationUserDetailsService that will make any user that authenticates - * a valid user. - * - *
    -	 * @Configuration
    -	 * @EnableWebSecurity
    -	 * public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
    -	 *
    -	 * 	@Override
    -	 * 	protected void configure(HttpSecurity http) {
    -	 * 		http.authorizeRequests()
    -	 * 				.antMatchers("/**")
    -	 * 				.hasRole("USER")
    -	 * 				.and()
    -	 * 				.openidLogin()
    -	 * 				.loginPage("/login")
    -	 * 				.permitAll()
    -	 * 				.authenticationUserDetailsService(
    -	 * 						new AutoProvisioningUserDetailsService())
    -	 * 				.attributeExchange("https://www.google.com/.*").attribute("email")
    -	 * 				.type("https://axschema.org/contact/email").required(true).and()
    -	 * 				.attribute("firstname").type("https://axschema.org/namePerson/first")
    -	 * 				.required(true).and().attribute("lastname")
    -	 * 				.type("https://axschema.org/namePerson/last").required(true).and().and()
    -	 * 				.attributeExchange(".*yahoo.com.*").attribute("email")
    -	 * 				.type("https://schema.openid.net/contact/email").required(true).and()
    -	 * 				.attribute("fullname").type("https://axschema.org/namePerson")
    -	 * 				.required(true).and().and().attributeExchange(".*myopenid.com.*")
    -	 * 				.attribute("email").type("https://schema.openid.net/contact/email")
    -	 * 				.required(true).and().attribute("fullname")
    -	 * 				.type("https://schema.openid.net/namePerson").required(true);
    -	 * 	}
    -	 * }
    -	 *
    -	 * public class AutoProvisioningUserDetailsService implements
    -	 * 		AuthenticationUserDetailsService<OpenIDAuthenticationToken> {
    -	 * 	public UserDetails loadUserDetails(OpenIDAuthenticationToken token)
    -	 * 			throws UsernameNotFoundException {
    -	 * 		return new User(token.getName(), "NOTUSED",
    -	 * 				AuthorityUtils.createAuthorityList("ROLE_USER"));
    -	 * 	}
    -	 * }
    -	 * 
    - * @return the {@link OpenIDLoginConfigurer} for further customizations. - * @throws Exception - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - * @see OpenIDLoginConfigurer - */ - @Deprecated - public OpenIDLoginConfigurer openidLogin() throws Exception { - return getOrApply(new OpenIDLoginConfigurer<>()); - } - - /** - * Allows configuring OpenID based authentication. - * - *

    Example Configurations

    - * - * A basic example accepting the defaults and not using attribute exchange: - * - *
    -	 * @Configuration
    -	 * @EnableWebSecurity
    -	 * public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
    -	 *
    -	 * 	@Override
    -	 * 	protected void configure(HttpSecurity http) {
    -	 * 		http
    -	 * 			.authorizeRequests((authorizeRequests) ->
    -	 * 				authorizeRequests
    -	 * 					.antMatchers("/**").hasRole("USER")
    -	 * 			)
    -	 * 			.openidLogin((openidLogin) ->
    -	 * 				openidLogin
    -	 * 					.permitAll()
    -	 * 			);
    -	 * 	}
    -	 *
    -	 * 	@Override
    -	 * 	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    -	 * 		auth.inMemoryAuthentication()
    -	 * 				// the username must match the OpenID of the user you are
    -	 * 				// logging in with
    -	 * 				.withUser(
    -	 * 						"https://www.google.com/accounts/o8/id?id=lmkCn9xzPdsxVwG7pjYMuDgNNdASFmobNkcRPaWU")
    -	 * 				.password("password").roles("USER");
    -	 * 	}
    -	 * }
    -	 * 
    - * - * A more advanced example demonstrating using attribute exchange and providing a - * custom AuthenticationUserDetailsService that will make any user that authenticates - * a valid user. - * - *
    -	 * @Configuration
    -	 * @EnableWebSecurity
    -	 * public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
    -	 *
    -	 * 	@Override
    -	 * 	protected void configure(HttpSecurity http) throws Exception {
    -	 * 		http.authorizeRequests((authorizeRequests) ->
    -	 * 				authorizeRequests
    -	 * 					.antMatchers("/**").hasRole("USER")
    -	 * 			)
    -	 * 			.openidLogin((openidLogin) ->
    -	 * 				openidLogin
    -	 * 					.loginPage("/login")
    -	 * 					.permitAll()
    -	 * 					.authenticationUserDetailsService(
    -	 * 						new AutoProvisioningUserDetailsService())
    -	 * 					.attributeExchange((googleExchange) ->
    -	 * 						googleExchange
    -	 * 							.identifierPattern("https://www.google.com/.*")
    -	 * 							.attribute((emailAttribute) ->
    -	 * 								emailAttribute
    -	 * 									.name("email")
    -	 * 									.type("https://axschema.org/contact/email")
    -	 * 									.required(true)
    -	 * 							)
    -	 * 							.attribute((firstnameAttribute) ->
    -	 * 								firstnameAttribute
    -	 * 									.name("firstname")
    -	 * 									.type("https://axschema.org/namePerson/first")
    -	 * 									.required(true)
    -	 * 							)
    -	 * 							.attribute((lastnameAttribute) ->
    -	 * 								lastnameAttribute
    -	 * 									.name("lastname")
    -	 * 									.type("https://axschema.org/namePerson/last")
    -	 * 									.required(true)
    -	 * 							)
    -	 * 					)
    -	 * 					.attributeExchange((yahooExchange) ->
    -	 * 						yahooExchange
    -	 * 							.identifierPattern(".*yahoo.com.*")
    -	 * 							.attribute((emailAttribute) ->
    -	 * 								emailAttribute
    -	 * 									.name("email")
    -	 * 									.type("https://schema.openid.net/contact/email")
    -	 * 									.required(true)
    -	 * 							)
    -	 * 							.attribute((fullnameAttribute) ->
    -	 * 								fullnameAttribute
    -	 * 									.name("fullname")
    -	 * 									.type("https://axschema.org/namePerson")
    -	 * 									.required(true)
    -	 * 							)
    -	 * 					)
    -	 * 			);
    -	 * 	}
    -	 * }
    -	 *
    -	 * public class AutoProvisioningUserDetailsService implements
    -	 * 		AuthenticationUserDetailsService<OpenIDAuthenticationToken> {
    -	 * 	public UserDetails loadUserDetails(OpenIDAuthenticationToken token)
    -	 * 			throws UsernameNotFoundException {
    -	 * 		return new User(token.getName(), "NOTUSED",
    -	 * 				AuthorityUtils.createAuthorityList("ROLE_USER"));
    -	 * 	}
    -	 * }
    -	 * 
    - * @param openidLoginCustomizer the {@link Customizer} to provide more options for the - * {@link OpenIDLoginConfigurer} - * @return the {@link HttpSecurity} for further customizations - * @throws Exception - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - * @see OpenIDLoginConfigurer - */ - @Deprecated - public HttpSecurity openidLogin(Customizer> openidLoginCustomizer) - throws Exception { - openidLoginCustomizer.customize(getOrApply(new OpenIDLoginConfigurer<>())); - return HttpSecurity.this; - } - /** * Adds the Security headers to the response. This is activated by default when using * {@link WebSecurityConfigurerAdapter}'s default constructor. Accepting the default diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java index f38ca4c76c..507f7b85bf 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java @@ -26,7 +26,6 @@ import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.HttpSecurityBuilder; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.annotation.web.configurers.openid.OpenIDLoginConfigurer; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.PortMapper; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; @@ -57,7 +56,6 @@ import org.springframework.web.accept.HeaderContentNegotiationStrategy; * @author Rob Winch * @since 3.2 * @see FormLoginConfigurer - * @see OpenIDLoginConfigurer */ public abstract class AbstractAuthenticationFilterConfigurer, T extends AbstractAuthenticationFilterConfigurer, F extends AbstractAuthenticationProcessingFilter> extends AbstractHttpConfigurer { diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurer.java deleted file mode 100644 index db04204779..0000000000 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurer.java +++ /dev/null @@ -1,569 +0,0 @@ -/* - * Copyright 2002-2019 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 - * - * https://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.openid; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import jakarta.servlet.http.HttpServletRequest; - -import org.openid4java.consumer.ConsumerException; -import org.openid4java.consumer.ConsumerManager; - -import org.springframework.security.authentication.AuthenticationDetailsSource; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.Customizer; -import org.springframework.security.config.annotation.web.HttpSecurityBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer; -import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer; -import org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer; -import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer; -import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.openid.AxFetchListFactory; -import org.springframework.security.openid.OpenID4JavaConsumer; -import org.springframework.security.openid.OpenIDAttribute; -import org.springframework.security.openid.OpenIDAuthenticationFilter; -import org.springframework.security.openid.OpenIDAuthenticationProvider; -import org.springframework.security.openid.OpenIDAuthenticationToken; -import org.springframework.security.openid.OpenIDConsumer; -import org.springframework.security.openid.RegexBasedAxFetchListFactory; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; -import org.springframework.security.web.authentication.RememberMeServices; -import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; -import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import org.springframework.security.web.util.matcher.RequestMatcher; - -/** - * Adds support for OpenID based authentication. - * - *

    Example Configuration

    - * - *
    - *
    - * @Configuration
    - * @EnableWebSecurity
    - * public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
    - *
    - * 	@Override
    - * 	protected void configure(HttpSecurity http) {
    - * 		http
    - * 			.authorizeRequests()
    - * 				.antMatchers("/**").hasRole("USER")
    - * 				.and()
    - * 			.openidLogin()
    - * 				.permitAll();
    - * 	}
    - *
    - * 	@Override
    - * 	protected void configure(AuthenticationManagerBuilder auth)(
    - * 			AuthenticationManagerBuilder auth) throws Exception {
    - * 		auth
    - * 			.inMemoryAuthentication()
    - * 				.withUser("https://www.google.com/accounts/o8/id?id=lmkCn9xzPdsxVwG7pjYMuDgNNdASFmobNkcRPaWU")
    - * 					.password("password")
    - * 					.roles("USER");
    - * 	}
    - * }
    - * 
    - * - *

    Security Filters

    - * - * The following Filters are populated - * - *
      - *
    • {@link OpenIDAuthenticationFilter}
    • - *
    - * - *

    Shared Objects Created

    - * - *
      - *
    • {@link AuthenticationEntryPoint} is populated with a - * {@link LoginUrlAuthenticationEntryPoint}
    • - *
    • An {@link OpenIDAuthenticationProvider} is populated into - * {@link HttpSecurity#authenticationProvider(org.springframework.security.authentication.AuthenticationProvider)} - *
    • - *
    - * - *

    Shared Objects Used

    - * - * The following shared objects are used: - * - *
      - *
    • {@link AuthenticationManager}
    • - *
    • {@link RememberMeServices} - is optionally used. See {@link RememberMeConfigurer} - *
    • - *
    • {@link SessionAuthenticationStrategy} - is optionally used. See - * {@link SessionManagementConfigurer}
    • - *
    - * - * @author Rob Winch - * @since 3.2 - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public final class OpenIDLoginConfigurer> - extends AbstractAuthenticationFilterConfigurer, OpenIDAuthenticationFilter> { - - private OpenIDConsumer openIDConsumer; - - private ConsumerManager consumerManager; - - private AuthenticationUserDetailsService authenticationUserDetailsService; - - private List attributeExchangeConfigurers = new ArrayList<>(); - - /** - * Creates a new instance - */ - public OpenIDLoginConfigurer() { - super(new OpenIDAuthenticationFilter(), "/login/openid"); - } - - /** - * Sets up OpenID attribute exchange for OpenID's matching the specified pattern. - * @param identifierPattern the regular expression for matching on OpenID's (i.e. - * "https://www.google.com/.*", ".*yahoo.com.*", etc) - * @return a {@link AttributeExchangeConfigurer} for further customizations of the - * attribute exchange - */ - public AttributeExchangeConfigurer attributeExchange(String identifierPattern) { - AttributeExchangeConfigurer attributeExchangeConfigurer = new AttributeExchangeConfigurer(identifierPattern); - this.attributeExchangeConfigurers.add(attributeExchangeConfigurer); - return attributeExchangeConfigurer; - } - - /** - * Sets up OpenID attribute exchange for OpenIDs matching the specified pattern. The - * default pattern is ".*", it can be specified using - * {@link AttributeExchangeConfigurer#identifierPattern(String)} - * @param attributeExchangeCustomizer the {@link Customizer} to provide more options - * for the {@link AttributeExchangeConfigurer} - * @return a {@link OpenIDLoginConfigurer} for further customizations - */ - public OpenIDLoginConfigurer attributeExchange( - Customizer attributeExchangeCustomizer) { - AttributeExchangeConfigurer attributeExchangeConfigurer = new AttributeExchangeConfigurer(".*"); - attributeExchangeCustomizer.customize(attributeExchangeConfigurer); - this.attributeExchangeConfigurers.add(attributeExchangeConfigurer); - return this; - } - - /** - * Allows specifying the {@link OpenIDConsumer} to be used. The default is using an - * {@link OpenID4JavaConsumer}. - * @param consumer the {@link OpenIDConsumer} to be used - * @return the {@link OpenIDLoginConfigurer} for further customizations - */ - public OpenIDLoginConfigurer consumer(OpenIDConsumer consumer) { - this.openIDConsumer = consumer; - return this; - } - - /** - * Allows specifying the {@link ConsumerManager} to be used. If specified, will be - * populated into an {@link OpenID4JavaConsumer}. - * - *

    - * This is a shortcut for specifying the {@link OpenID4JavaConsumer} with a specific - * {@link ConsumerManager} on {@link #consumer(OpenIDConsumer)}. - *

    - * @param consumerManager the {@link ConsumerManager} to use. Cannot be null. - * @return the {@link OpenIDLoginConfigurer} for further customizations - */ - public OpenIDLoginConfigurer consumerManager(ConsumerManager consumerManager) { - this.consumerManager = consumerManager; - return this; - } - - /** - * The {@link AuthenticationUserDetailsService} to use. By default a - * {@link UserDetailsByNameServiceWrapper} is used with the {@link UserDetailsService} - * shared object found with {@link HttpSecurity#getSharedObject(Class)}. - * @param authenticationUserDetailsService the {@link AuthenticationDetailsSource} to - * use - * @return the {@link OpenIDLoginConfigurer} for further customizations - */ - public OpenIDLoginConfigurer authenticationUserDetailsService( - AuthenticationUserDetailsService authenticationUserDetailsService) { - this.authenticationUserDetailsService = authenticationUserDetailsService; - return this; - } - - /** - * Specifies the URL used to authenticate OpenID requests. If the - * {@link HttpServletRequest} matches this URL the {@link OpenIDAuthenticationFilter} - * will attempt to authenticate the request. The default is "/login/openid". - * @param loginProcessingUrl the URL used to perform authentication - * @return the {@link OpenIDLoginConfigurer} for additional customization - */ - @Override - public OpenIDLoginConfigurer loginProcessingUrl(String loginProcessingUrl) { - return super.loginProcessingUrl(loginProcessingUrl); - } - - /** - *

    - * Specifies the URL to send users to if login is required. If used with - * {@link WebSecurityConfigurerAdapter} a default login page will be generated when - * this attribute is not specified. - *

    - * - *

    - * If a URL is specified or this is not being used in conjunction with - * {@link WebSecurityConfigurerAdapter}, users are required to process the specified - * URL to generate a login page. - *

    - * - *
      - *
    • It must be an HTTP POST
    • - *
    • It must be submitted to {@link #loginProcessingUrl(String)}
    • - *
    • It should include the OpenID as an HTTP parameter by the name of - * {@link OpenIDAuthenticationFilter#DEFAULT_CLAIMED_IDENTITY_FIELD}
    • - *
    - * - * - *

    Impact on other defaults

    - * - * Updating this value, also impacts a number of other default values. For example, - * the following are the default values when only formLogin() was specified. - * - *
      - *
    • /login GET - the login form
    • - *
    • /login POST - process the credentials and if valid authenticate the user
    • - *
    • /login?error GET - redirect here for failed authentication attempts
    • - *
    • /login?logout GET - redirect here after successfully logging out
    • - *
    - * - * If "/authenticate" was passed to this method it update the defaults as shown below: - * - *
      - *
    • /authenticate GET - the login form
    • - *
    • /authenticate POST - process the credentials and if valid authenticate the user - *
    • - *
    • /authenticate?error GET - redirect here for failed authentication attempts
    • - *
    • /authenticate?logout GET - redirect here after successfully logging out
    • - *
    - * @param loginPage the login page to redirect to if authentication is required (i.e. - * "/login") - * @return the {@link FormLoginConfigurer} for additional customization - */ - @Override - public OpenIDLoginConfigurer loginPage(String loginPage) { - return super.loginPage(loginPage); - } - - @Override - public void init(H http) throws Exception { - super.init(http); - OpenIDAuthenticationProvider authenticationProvider = new OpenIDAuthenticationProvider(); - authenticationProvider.setAuthenticationUserDetailsService(getAuthenticationUserDetailsService(http)); - authenticationProvider = postProcess(authenticationProvider); - http.authenticationProvider(authenticationProvider); - initDefaultLoginFilter(http); - } - - @Override - public void configure(H http) throws Exception { - getAuthenticationFilter().setConsumer(getConsumer()); - super.configure(http); - } - - @Override - protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) { - return new AntPathRequestMatcher(loginProcessingUrl); - } - - /** - * Gets the {@link OpenIDConsumer} that was configured or defaults to an - * {@link OpenID4JavaConsumer}. - * @return the {@link OpenIDConsumer} to use - * @throws ConsumerException - */ - private OpenIDConsumer getConsumer() throws ConsumerException { - if (this.openIDConsumer == null) { - this.openIDConsumer = new OpenID4JavaConsumer(getConsumerManager(), attributesToFetchFactory()); - } - return this.openIDConsumer; - } - - /** - * Gets the {@link ConsumerManager} that was configured or defaults to using a - * {@link ConsumerManager} with the default constructor. - * @return the {@link ConsumerManager} to use - */ - private ConsumerManager getConsumerManager() { - if (this.consumerManager != null) { - return this.consumerManager; - } - return new ConsumerManager(); - } - - /** - * Creates an {@link RegexBasedAxFetchListFactory} using the attributes populated by - * {@link AttributeExchangeConfigurer} - * @return the {@link AxFetchListFactory} to use - */ - private AxFetchListFactory attributesToFetchFactory() { - Map> identityToAttrs = new HashMap<>(); - for (AttributeExchangeConfigurer conf : this.attributeExchangeConfigurers) { - identityToAttrs.put(conf.identifier, conf.getAttributes()); - } - return new RegexBasedAxFetchListFactory(identityToAttrs); - } - - /** - * Gets the {@link AuthenticationUserDetailsService} that was configured or defaults - * to {@link UserDetailsByNameServiceWrapper} that uses a {@link UserDetailsService} - * looked up using {@link HttpSecurity#getSharedObject(Class)} - * @param http the current {@link HttpSecurity} - * @return the {@link AuthenticationUserDetailsService}. - */ - private AuthenticationUserDetailsService getAuthenticationUserDetailsService(H http) { - if (this.authenticationUserDetailsService != null) { - return this.authenticationUserDetailsService; - } - return new UserDetailsByNameServiceWrapper<>(http.getSharedObject(UserDetailsService.class)); - } - - /** - * If available, initializes the {@link DefaultLoginPageGeneratingFilter} shared - * object. - * @param http the {@link HttpSecurityBuilder} to use - */ - private void initDefaultLoginFilter(H http) { - DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http - .getSharedObject(DefaultLoginPageGeneratingFilter.class); - if (loginPageGeneratingFilter != null && !isCustomLoginPage()) { - loginPageGeneratingFilter.setOpenIdEnabled(true); - loginPageGeneratingFilter.setOpenIDauthenticationUrl(getLoginProcessingUrl()); - String loginPageUrl = loginPageGeneratingFilter.getLoginPageUrl(); - if (loginPageUrl == null) { - loginPageGeneratingFilter.setLoginPageUrl(getLoginPage()); - loginPageGeneratingFilter.setFailureUrl(getFailureUrl()); - } - loginPageGeneratingFilter - .setOpenIDusernameParameter(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD); - } - } - - /** - * A class used to add OpenID attributes to look up - * - * @author Rob Winch - */ - public final class AttributeExchangeConfigurer { - - private String identifier; - - private List attributes = new ArrayList<>(); - - private List attributeConfigurers = new ArrayList<>(); - - /** - * Creates a new instance - * @param identifierPattern the pattern that attempts to match on the OpenID - * @see OpenIDLoginConfigurer#attributeExchange(String) - */ - private AttributeExchangeConfigurer(String identifierPattern) { - this.identifier = identifierPattern; - } - - /** - * Get the {@link OpenIDLoginConfigurer} to customize the OpenID configuration - * further - * @return the {@link OpenIDLoginConfigurer} - */ - public OpenIDLoginConfigurer and() { - return OpenIDLoginConfigurer.this; - } - - /** - * Sets the regular expression for matching on OpenID's (i.e. - * "https://www.google.com/.*", ".*yahoo.com.*", etc) - * @param identifierPattern the regular expression for matching on OpenID's - * @return the {@link AttributeExchangeConfigurer} for further customization of - * attribute exchange - */ - public AttributeExchangeConfigurer identifierPattern(String identifierPattern) { - this.identifier = identifierPattern; - return this; - } - - /** - * Adds an {@link OpenIDAttribute} to be obtained for the configured OpenID - * pattern. - * @param attribute the {@link OpenIDAttribute} to obtain - * @return the {@link AttributeExchangeConfigurer} for further customization of - * attribute exchange - */ - public AttributeExchangeConfigurer attribute(OpenIDAttribute attribute) { - this.attributes.add(attribute); - return this; - } - - /** - * Adds an {@link OpenIDAttribute} with the given name - * @param name the name of the {@link OpenIDAttribute} to create - * @return an {@link AttributeConfigurer} to further configure the - * {@link OpenIDAttribute} that should be obtained. - */ - public AttributeConfigurer attribute(String name) { - AttributeConfigurer attributeConfigurer = new AttributeConfigurer(name); - this.attributeConfigurers.add(attributeConfigurer); - return attributeConfigurer; - } - - /** - * Adds an {@link OpenIDAttribute} named "default-attribute". The name - * can by updated using {@link AttributeConfigurer#name(String)}. - * @param attributeCustomizer the {@link Customizer} to provide more options for - * the {@link AttributeConfigurer} - * @return a {@link AttributeExchangeConfigurer} for further customizations - */ - public AttributeExchangeConfigurer attribute(Customizer attributeCustomizer) { - AttributeConfigurer attributeConfigurer = new AttributeConfigurer(); - attributeCustomizer.customize(attributeConfigurer); - this.attributeConfigurers.add(attributeConfigurer); - return this; - } - - /** - * Gets the {@link OpenIDAttribute}'s for the configured OpenID pattern - * @return - */ - private List getAttributes() { - for (AttributeConfigurer config : this.attributeConfigurers) { - this.attributes.add(config.build()); - } - this.attributeConfigurers.clear(); - return this.attributes; - } - - /** - * Configures an {@link OpenIDAttribute} - * - * @author Rob Winch - * @since 3.2 - */ - public final class AttributeConfigurer { - - private String name; - - private int count = 1; - - private boolean required = false; - - private String type; - - /** - * Creates a new instance named "default-attribute". The name can by updated - * using {@link #name(String)}. - * - * @see AttributeExchangeConfigurer#attribute(String) - */ - private AttributeConfigurer() { - this.name = "default-attribute"; - } - - /** - * Creates a new instance - * @param name the name of the attribute - * @see AttributeExchangeConfigurer#attribute(String) - */ - private AttributeConfigurer(String name) { - this.name = name; - } - - /** - * Specifies the number of attribute values to request. Default is 1. - * @param count the number of attributes to request. - * @return the {@link AttributeConfigurer} for further customization - */ - public AttributeConfigurer count(int count) { - this.count = count; - return this; - } - - /** - * Specifies that this attribute is required. The default is - * false. Note that as outlined in the OpenID specification, - * required attributes are not validated by the OpenID Provider. Developers - * should perform any validation in custom code. - * @param required specifies the attribute is required - * @return the {@link AttributeConfigurer} for further customization - */ - public AttributeConfigurer required(boolean required) { - this.required = required; - return this; - } - - /** - * The OpenID attribute type. - * @param type - * @return the {@link AttributeConfigurer} for further customizations - */ - public AttributeConfigurer type(String type) { - this.type = type; - return this; - } - - /** - * The OpenID attribute name. - * @param name - * @return the {@link AttributeConfigurer} for further customizations - */ - public AttributeConfigurer name(String name) { - this.name = name; - return this; - } - - /** - * Gets the {@link AttributeExchangeConfigurer} for further customization of - * the attributes - * @return the {@link AttributeConfigurer} - */ - public AttributeExchangeConfigurer and() { - return AttributeExchangeConfigurer.this; - } - - /** - * Builds the {@link OpenIDAttribute}. - * @return - */ - private OpenIDAttribute build() { - OpenIDAttribute attribute = new OpenIDAttribute(this.name, this.type); - attribute.setCount(this.count); - attribute.setRequired(this.required); - return attribute; - } - - } - - } - -} diff --git a/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java b/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java index 7b1d57076f..aae7baf6c7 100644 --- a/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java +++ b/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java @@ -85,16 +85,6 @@ final class AuthenticationConfigBuilder { private static final String DEF_REALM = "Realm"; - static final String OPEN_ID_AUTHENTICATION_PROCESSING_FILTER_CLASS = "org.springframework.security.openid.OpenIDAuthenticationFilter"; - - static final String OPEN_ID_AUTHENTICATION_PROVIDER_CLASS = "org.springframework.security.openid.OpenIDAuthenticationProvider"; - - private static final String OPEN_ID_CONSUMER_CLASS = "org.springframework.security.openid.OpenID4JavaConsumer"; - - static final String OPEN_ID_ATTRIBUTE_CLASS = "org.springframework.security.openid.OpenIDAttribute"; - - private static final String OPEN_ID_ATTRIBUTE_FACTORY_CLASS = "org.springframework.security.openid.RegexBasedAxFetchListFactory"; - static final String AUTHENTICATION_PROCESSING_FILTER_CLASS = "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"; static final String ATT_AUTH_DETAILS_SOURCE_REF = "authentication-details-source-ref"; @@ -135,14 +125,8 @@ final class AuthenticationConfigBuilder { private BeanDefinition formEntryPoint; - private BeanDefinition openIDEntryPoint; - - private BeanReference openIDProviderRef; - private String formFilterId = null; - private String openIDFilterId = null; - private BeanDefinition x509Filter; private BeanReference x509ProviderRef; @@ -180,12 +164,8 @@ final class AuthenticationConfigBuilder { private String loginProcessingUrl; - private String openidLoginProcessingUrl; - private String formLoginPage; - private String openIDLoginPage; - private boolean oauth2LoginEnabled; private boolean defaultAuthorizedClientRepositoryRegistered; @@ -237,7 +217,6 @@ final class AuthenticationConfigBuilder { createBearerTokenAuthenticationFilter(authenticationManager); createFormLoginFilter(sessionStrategy, authenticationManager); createOAuth2ClientFilters(sessionStrategy, requestCache, authenticationManager); - createOpenIDLoginFilter(sessionStrategy, authenticationManager); createX509Filter(authenticationManager); createJeeFilter(authenticationManager); createLogoutFilter(); @@ -395,106 +374,6 @@ final class AuthenticationConfigBuilder { } } - void createOpenIDLoginFilter(BeanReference sessionStrategy, BeanReference authManager) { - Element openIDLoginElt = DomUtils.getChildElementByTagName(this.httpElt, Elements.OPENID_LOGIN); - RootBeanDefinition openIDFilter = null; - if (openIDLoginElt != null) { - openIDFilter = parseOpenIDFilter(sessionStrategy, openIDLoginElt); - } - if (openIDFilter != null) { - openIDFilter.getPropertyValues().addPropertyValue("allowSessionCreation", this.allowSessionCreation); - openIDFilter.getPropertyValues().addPropertyValue("authenticationManager", authManager); - // Required by login page filter - this.openIDFilterId = this.pc.getReaderContext().generateBeanName(openIDFilter); - this.pc.registerBeanComponent(new BeanComponentDefinition(openIDFilter, this.openIDFilterId)); - injectRememberMeServicesRef(openIDFilter, this.rememberMeServicesId); - createOpenIDProvider(); - } - } - - /** - * Parses OpenID 1.0 and 2.0 - related parts of configuration xmls - * @param sessionStrategy sessionStrategy - * @param openIDLoginElt the element from the xml file - * @return the parsed filter as rootBeanDefinition - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ - @Deprecated - private RootBeanDefinition parseOpenIDFilter(BeanReference sessionStrategy, Element openIDLoginElt) { - RootBeanDefinition openIDFilter; - FormLoginBeanDefinitionParser parser = new FormLoginBeanDefinitionParser("/login/openid", null, - OPEN_ID_AUTHENTICATION_PROCESSING_FILTER_CLASS, this.requestCache, sessionStrategy, - this.allowSessionCreation, this.portMapper, this.portResolver); - - parser.parse(openIDLoginElt, this.pc); - openIDFilter = parser.getFilterBean(); - this.openIDEntryPoint = parser.getEntryPointBean(); - this.openidLoginProcessingUrl = parser.getLoginProcessingUrl(); - this.openIDLoginPage = parser.getLoginPage(); - List attrExElts = DomUtils.getChildElementsByTagName(openIDLoginElt, - Elements.OPENID_ATTRIBUTE_EXCHANGE); - if (!attrExElts.isEmpty()) { - // Set up the consumer with the required attribute list - BeanDefinitionBuilder consumerBldr = BeanDefinitionBuilder.rootBeanDefinition(OPEN_ID_CONSUMER_CLASS); - BeanDefinitionBuilder axFactory = BeanDefinitionBuilder.rootBeanDefinition(OPEN_ID_ATTRIBUTE_FACTORY_CLASS); - ManagedMap> axMap = new ManagedMap<>(); - for (Element attrExElt : attrExElts) { - String identifierMatch = attrExElt.getAttribute("identifier-match"); - if (!StringUtils.hasText(identifierMatch)) { - if (attrExElts.size() > 1) { - this.pc.getReaderContext().error("You must supply an identifier-match attribute if using more" - + " than one " + Elements.OPENID_ATTRIBUTE_EXCHANGE + " element", attrExElt); - } - // Match anything - identifierMatch = ".*"; - } - axMap.put(identifierMatch, parseOpenIDAttributes(attrExElt)); - } - axFactory.addConstructorArgValue(axMap); - consumerBldr.addConstructorArgValue(axFactory.getBeanDefinition()); - openIDFilter.getPropertyValues().addPropertyValue("consumer", consumerBldr.getBeanDefinition()); - } - return openIDFilter; - } - - private ManagedList parseOpenIDAttributes(Element attrExElt) { - ManagedList attributes = new ManagedList<>(); - for (Element attElt : DomUtils.getChildElementsByTagName(attrExElt, Elements.OPENID_ATTRIBUTE)) { - String name = attElt.getAttribute("name"); - String type = attElt.getAttribute("type"); - String required = attElt.getAttribute("required"); - String count = attElt.getAttribute("count"); - BeanDefinitionBuilder attrBldr = BeanDefinitionBuilder.rootBeanDefinition(OPEN_ID_ATTRIBUTE_CLASS); - attrBldr.addConstructorArgValue(name); - attrBldr.addConstructorArgValue(type); - if (StringUtils.hasLength(required)) { - attrBldr.addPropertyValue("required", Boolean.valueOf(required)); - } - if (StringUtils.hasLength(count)) { - attrBldr.addPropertyValue("count", Integer.parseInt(count)); - } - attributes.add(attrBldr.getBeanDefinition()); - } - return attributes; - } - - private void createOpenIDProvider() { - Element openIDLoginElt = DomUtils.getChildElementByTagName(this.httpElt, Elements.OPENID_LOGIN); - BeanDefinitionBuilder openIDProviderBuilder = BeanDefinitionBuilder - .rootBeanDefinition(OPEN_ID_AUTHENTICATION_PROVIDER_CLASS); - RootBeanDefinition uds = new RootBeanDefinition(); - uds.setFactoryBeanName(BeanIds.USER_DETAILS_SERVICE_FACTORY); - uds.setFactoryMethodName("authenticationUserDetailsService"); - uds.getConstructorArgumentValues().addGenericArgumentValue(openIDLoginElt.getAttribute(ATT_USER_SERVICE_REF)); - openIDProviderBuilder.addPropertyValue("authenticationUserDetailsService", uds); - BeanDefinition openIDProvider = openIDProviderBuilder.getBeanDefinition(); - this.openIDProviderRef = new RuntimeBeanReference( - this.pc.getReaderContext().registerWithGeneratedName(openIDProvider)); - } - private void injectRememberMeServicesRef(RootBeanDefinition bean, String rememberMeServicesId) { if (rememberMeServicesId != null) { bean.getPropertyValues().addPropertyValue("rememberMeServices", @@ -640,10 +519,9 @@ final class AuthenticationConfigBuilder { } void createLoginPageFilterIfNeeded() { - boolean needLoginPage = this.formFilterId != null || this.openIDFilterId != null - || this.oauth2LoginFilterId != null; + boolean needLoginPage = this.formFilterId != null || this.oauth2LoginFilterId != null; // If no login page has been defined, add in the default page generator. - if (needLoginPage && this.formLoginPage == null && this.openIDLoginPage == null) { + if (needLoginPage && this.formLoginPage == null) { this.logger.info("No login page configured. The default internal one will be used. Use the '" + FormLoginBeanDefinitionParser.ATT_LOGIN_PAGE + "' attribute to set the URL of the login page."); BeanDefinitionBuilder loginPageFilter = BeanDefinitionBuilder @@ -657,12 +535,7 @@ final class AuthenticationConfigBuilder { loginPageFilter.addConstructorArgReference(this.formFilterId); loginPageFilter.addPropertyValue("authenticationUrl", this.loginProcessingUrl); } - if (this.openIDFilterId != null) { - loginPageFilter.addConstructorArgReference(this.openIDFilterId); - loginPageFilter.addPropertyValue("openIDauthenticationUrl", this.openidLoginProcessingUrl); - } if (this.oauth2LoginFilterId != null) { - loginPageFilter.addConstructorArgReference(this.oauth2LoginFilterId); loginPageFilter.addPropertyValue("Oauth2LoginEnabled", true); loginPageFilter.addPropertyValue("Oauth2AuthenticationUrlToClientName", this.oauth2LoginLinks); } @@ -820,21 +693,11 @@ final class AuthenticationConfigBuilder { } Element basicAuthElt = DomUtils.getChildElementByTagName(this.httpElt, Elements.BASIC_AUTH); Element formLoginElt = DomUtils.getChildElementByTagName(this.httpElt, Elements.FORM_LOGIN); - Element openIDLoginElt = DomUtils.getChildElementByTagName(this.httpElt, Elements.OPENID_LOGIN); // Basic takes precedence if explicit element is used and no others are configured - if (basicAuthElt != null && formLoginElt == null && openIDLoginElt == null - && this.oauth2LoginEntryPoint == null) { + if (basicAuthElt != null && formLoginElt == null && this.oauth2LoginEntryPoint == null) { return this.basicEntryPoint; } - // If formLogin has been enabled either through an element or auto-config, then it - // is used if no openID login page - // has been set. - if (this.formLoginPage != null && this.openIDLoginPage != null) { - this.pc.getReaderContext().error( - "Only one login-page can be defined, either for OpenID or form-login, " + "but not both.", - this.pc.extractSource(openIDLoginElt)); - } - if (this.formFilterId != null && this.openIDLoginPage == null) { + if (this.formFilterId != null) { // If form login was enabled through element and Oauth2 login was enabled from // element then use form login (gh-6802) if (formLoginElt != null && this.oauth2LoginEntryPoint != null) { @@ -846,10 +709,6 @@ final class AuthenticationConfigBuilder { return this.formEntryPoint; } } - // Otherwise use OpenID if enabled - if (this.openIDFilterId != null) { - return this.openIDEntryPoint; - } // If X.509 or JEE have been enabled, use the preauth entry point. if (this.preAuthEntryPoint != null) { return this.preAuthEntryPoint; @@ -902,10 +761,6 @@ final class AuthenticationConfigBuilder { filters.add(new OrderDecorator(this.oauth2AuthorizationRequestRedirectFilter, SecurityFilters.OAUTH2_AUTHORIZATION_REQUEST_FILTER)); } - if (this.openIDFilterId != null) { - filters.add( - new OrderDecorator(new RuntimeBeanReference(this.openIDFilterId), SecurityFilters.OPENID_FILTER)); - } if (this.loginPageGenerationFilter != null) { filters.add(new OrderDecorator(this.loginPageGenerationFilter, SecurityFilters.LOGIN_PAGE_FILTER)); filters.add(new OrderDecorator(this.logoutPageGenerationFilter, SecurityFilters.LOGOUT_PAGE_FILTER)); @@ -935,9 +790,6 @@ final class AuthenticationConfigBuilder { if (this.rememberMeProviderRef != null) { providers.add(this.rememberMeProviderRef); } - if (this.openIDProviderRef != null) { - providers.add(this.openIDProviderRef); - } if (this.x509ProviderRef != null) { providers.add(this.x509ProviderRef); } diff --git a/config/src/main/java/org/springframework/security/config/http/SecurityFilters.java b/config/src/main/java/org/springframework/security/config/http/SecurityFilters.java index c9b053a3b6..3fb6a0bb7b 100644 --- a/config/src/main/java/org/springframework/security/config/http/SecurityFilters.java +++ b/config/src/main/java/org/springframework/security/config/http/SecurityFilters.java @@ -57,8 +57,6 @@ enum SecurityFilters { FORM_LOGIN_FILTER, - OPENID_FILTER, - LOGIN_PAGE_FILTER, LOGOUT_PAGE_FILTER, diff --git a/config/src/main/java/org/springframework/security/config/http/UserDetailsServiceFactoryBean.java b/config/src/main/java/org/springframework/security/config/http/UserDetailsServiceFactoryBean.java index 851416c3f8..227adbc0ec 100644 --- a/config/src/main/java/org/springframework/security/config/http/UserDetailsServiceFactoryBean.java +++ b/config/src/main/java/org/springframework/security/config/http/UserDetailsServiceFactoryBean.java @@ -109,7 +109,7 @@ public class UserDetailsServiceFactoryBean implements ApplicationContextAware { } if (beans.size() > 1) { throw new ApplicationContextException("More than one UserDetailsService registered. Please " - + "use a specific Id reference in or elements."); + + "use a specific Id reference in or elements."); } return (UserDetailsService) beans.values().toArray()[0]; } diff --git a/config/src/main/resources/org/springframework/security/config/spring-security-6.0.rnc b/config/src/main/resources/org/springframework/security/config/spring-security-6.0.rnc index 42b1349c0e..c87e75ddbb 100644 --- a/config/src/main/resources/org/springframework/security/config/spring-security-6.0.rnc +++ b/config/src/main/resources/org/springframework/security/config/spring-security-6.0.rnc @@ -312,7 +312,7 @@ http-firewall = http = ## Container element for HTTP security configuration. Multiple elements can now be defined, each with a specific pattern to which the enclosed security configuration applies. A pattern can also be configured to bypass Spring Security's filters completely by setting the "security" attribute to "none". - element http {http.attlist, (intercept-url* & access-denied-handler? & form-login? & oauth2-login? & oauth2-client? & oauth2-resource-server? & openid-login? & x509? & jee? & http-basic? & logout? & password-management? & session-management & remember-me? & anonymous? & port-mappings & custom-filter* & request-cache? & expression-handler? & headers? & csrf? & cors?) } + element http {http.attlist, (intercept-url* & access-denied-handler? & form-login? & oauth2-login? & oauth2-client? & oauth2-resource-server? & x509? & jee? & http-basic? & logout? & password-management? & session-management & remember-me? & anonymous? & port-mappings & custom-filter* & request-cache? & expression-handler? & headers? & csrf? & cors?) } http.attlist &= ## The request URL pattern which will be mapped to the filter chain created by this element. If omitted, the filter chain will match all requests. attribute pattern {xsd:token}? @@ -630,36 +630,6 @@ opaque-token.attlist &= ## Reference to an OpaqueTokenIntrospector attribute introspector-ref {xsd:token}? -openid-login = - ## Sets up form login for authentication with an Open ID identity. NOTE: The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2. - element openid-login {form-login.attlist, user-service-ref?, attribute-exchange*} - -attribute-exchange = - ## Sets up an attribute exchange configuration to request specified attributes from the OpenID identity provider. When multiple elements are used, each must have an identifier-attribute attribute. Each configuration will be matched in turn against the supplied login identifier until a match is found. - element attribute-exchange {attribute-exchange.attlist, openid-attribute+} - -attribute-exchange.attlist &= - ## A regular expression which will be compared against the claimed identity, when deciding which attribute-exchange configuration to use during authentication. - attribute identifier-match {xsd:token}? - -openid-attribute = - ## Attributes used when making an OpenID AX Fetch Request. NOTE: The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2. - element openid-attribute {openid-attribute.attlist} - -openid-attribute.attlist &= - ## Specifies the name of the attribute that you wish to get back. For example, email. - attribute name {xsd:token} -openid-attribute.attlist &= - ## Specifies the attribute type. For example, https://axschema.org/contact/email. See your OP's documentation for valid attribute types. - attribute type {xsd:token} -openid-attribute.attlist &= - ## Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false. - attribute required {xsd:boolean}? -openid-attribute.attlist &= - ## Specifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1. - attribute count {xsd:int}? - - filter-chain-map = ## Used to explicitly configure a FilterChainProxy instance with a FilterChainMap element filter-chain-map {filter-chain-map.attlist, filter-chain+} @@ -1148,4 +1118,4 @@ position = ## The explicit position at which the custom-filter should be placed in the chain. Use if you are replacing a standard filter. attribute position {named-security-filter} -named-security-filter = "FIRST" | "CHANNEL_FILTER" | "SECURITY_CONTEXT_FILTER" | "CONCURRENT_SESSION_FILTER" | "WEB_ASYNC_MANAGER_FILTER" | "HEADERS_FILTER" | "CORS_FILTER" | "CSRF_FILTER" | "LOGOUT_FILTER" | "OAUTH2_AUTHORIZATION_REQUEST_FILTER" | "X509_FILTER" | "PRE_AUTH_FILTER" | "CAS_FILTER" | "OAUTH2_LOGIN_FILTER" | "FORM_LOGIN_FILTER" | "OPENID_FILTER" | "LOGIN_PAGE_FILTER" |"LOGOUT_PAGE_FILTER" | "DIGEST_AUTH_FILTER" | "BEARER_TOKEN_AUTH_FILTER" | "BASIC_AUTH_FILTER" | "REQUEST_CACHE_FILTER" | "SERVLET_API_SUPPORT_FILTER" | "JAAS_API_SUPPORT_FILTER" | "REMEMBER_ME_FILTER" | "ANONYMOUS_FILTER" | "OAUTH2_AUTHORIZATION_CODE_GRANT_FILTER" | "WELL_KNOWN_CHANGE_PASSWORD_REDIRECT_FILTER" | "SESSION_MANAGEMENT_FILTER" | "EXCEPTION_TRANSLATION_FILTER" | "FILTER_SECURITY_INTERCEPTOR" | "SWITCH_USER_FILTER" | "LAST" +named-security-filter = "FIRST" | "CHANNEL_FILTER" | "SECURITY_CONTEXT_FILTER" | "CONCURRENT_SESSION_FILTER" | "WEB_ASYNC_MANAGER_FILTER" | "HEADERS_FILTER" | "CORS_FILTER" | "CSRF_FILTER" | "LOGOUT_FILTER" | "OAUTH2_AUTHORIZATION_REQUEST_FILTER" | "X509_FILTER" | "PRE_AUTH_FILTER" | "CAS_FILTER" | "OAUTH2_LOGIN_FILTER" | "FORM_LOGIN_FILTER" | "LOGIN_PAGE_FILTER" |"LOGOUT_PAGE_FILTER" | "DIGEST_AUTH_FILTER" | "BEARER_TOKEN_AUTH_FILTER" | "BASIC_AUTH_FILTER" | "REQUEST_CACHE_FILTER" | "SERVLET_API_SUPPORT_FILTER" | "JAAS_API_SUPPORT_FILTER" | "REMEMBER_ME_FILTER" | "ANONYMOUS_FILTER" | "OAUTH2_AUTHORIZATION_CODE_GRANT_FILTER" | "WELL_KNOWN_CHANGE_PASSWORD_REDIRECT_FILTER" | "SESSION_MANAGEMENT_FILTER" | "EXCEPTION_TRANSLATION_FILTER" | "FILTER_SECURITY_INTERCEPTOR" | "SWITCH_USER_FILTER" | "LAST" diff --git a/config/src/main/resources/org/springframework/security/config/spring-security-6.0.xsd b/config/src/main/resources/org/springframework/security/config/spring-security-6.0.xsd index 201953d2cf..737ec71827 100644 --- a/config/src/main/resources/org/springframework/security/config/spring-security-6.0.xsd +++ b/config/src/main/resources/org/springframework/security/config/spring-security-6.0.xsd @@ -1015,28 +1015,6 @@ - - - Sets up form login for authentication with an Open ID identity. NOTE: The OpenID 1.0 and - 2.0 protocols have been deprecated and users are <a - href="https://openid.net/specs/openid-connect-migration-1_0.html">encouraged to - migrate</a> to <a href="https://openid.net/connect/">OpenID Connect</a>, which is - supported by <code>spring-security-oauth2</code>. - - - - - - - - - - A reference to a user-service (or UserDetailsService bean) Id - - - - - Adds support for X.509 client authentication. @@ -1942,73 +1920,6 @@ - - - - Sets up an attribute exchange configuration to request specified attributes from the - OpenID identity provider. When multiple elements are used, each must have an - identifier-attribute attribute. Each configuration will be matched in turn against the - supplied login identifier until a match is found. - - - - - - - - - - - - - A regular expression which will be compared against the claimed identity, when deciding - which attribute-exchange configuration to use during authentication. - - - - - - - Attributes used when making an OpenID AX Fetch Request. NOTE: The OpenID 1.0 and 2.0 - protocols have been deprecated and users are <a - href="https://openid.net/specs/openid-connect-migration-1_0.html">encouraged to - migrate</a> to <a href="https://openid.net/connect/">OpenID Connect</a>, which is - supported by <code>spring-security-oauth2</code>. - - - - - - - - - - Specifies the name of the attribute that you wish to get back. For example, email. - - - - - - Specifies the attribute type. For example, https://axschema.org/contact/email. See your - OP's documentation for valid attribute types. - - - - - - Specifies if this attribute is required to the OP, but does not error out if the OP does - not return the attribute. Default is false. - - - - - - Specifies the number of attributes that you wish to get back. For example, return 3 - emails. The default value is 1. - - - - Used to explicitly configure a FilterChainProxy instance with a FilterChainMap @@ -3335,7 +3246,6 @@ - diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.java index 4f580a7a2d..4f76131750 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.java @@ -260,87 +260,6 @@ public class DefaultLoginPageConfigurerTests { // @formatter:on } - @Test - public void loginPageWhenOpenIdLoginConfiguredThenOpedIdLoginPage() throws Exception { - this.spring.register(DefaultLoginPageWithOpenIDConfig.class).autowire(); - CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN"); - String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN"); - // @formatter:off - this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken)) - .andExpect(content().string("\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " Please sign in\n" - + " \n" - + " \n" - + " \n" - + " \n" - + "
    \n" - + "
    \n" - + " \n" - + "

    \n" - + " \n" - + " \n" - + "

    \n" - + "\n" - + " \n" - + "
    \n" - + "
    \n" - + "")); - // @formatter:on - } - - @Test - public void loginPageWhenOpenIdLoginAndFormLoginAndRememberMeConfiguredThenOpedIdLoginPage() throws Exception { - this.spring.register(DefaultLoginPageWithFormLoginOpenIDRememberMeConfig.class).autowire(); - CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN"); - String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN"); - // @formatter:off - this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken)) - .andExpect(content().string("\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " Please sign in\n" - + " \n" - + " \n" - + " \n" - + " \n" - + "
    \n" - + "
    \n" - + " \n" + "

    \n" - + " \n" - + " \n" - + "

    \n" - + "

    \n" - + " \n" - + " \n" - + "

    \n" - + "

    Remember me on this computer.

    \n" - + "\n" - + " \n" - + "
    \n" - + "
    \n" - + " \n" - + "

    \n" + " \n" - + " \n" - + "

    \n" - + "

    Remember me on this computer.

    \n" - + "\n" - + " \n" - + "
    \n" - + "
    \n" - + "")); - // @formatter:on - } - @Test public void configureWhenRegisteringObjectPostProcessorThenInvokedOnDefaultLoginPageGeneratingFilter() { ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class); @@ -472,42 +391,6 @@ public class DefaultLoginPageConfigurerTests { } - @EnableWebSecurity - static class DefaultLoginPageWithOpenIDConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests() - .anyRequest().hasRole("USER") - .and() - .openidLogin(); - // @formatter:on - } - - } - - @EnableWebSecurity - static class DefaultLoginPageWithFormLoginOpenIDRememberMeConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests() - .anyRequest().hasRole("USER") - .and() - .rememberMe() - .and() - .formLogin() - .and() - .openidLogin(); - // @formatter:on - } - - } - @EnableWebSecurity static class DefaultLoginWithCustomAuthenticationEntryPointConfig extends WebSecurityConfigurerAdapter { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java deleted file mode 100644 index 31af12b014..0000000000 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright 2002-2019 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 - * - * https://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; - -import java.util.Arrays; -import java.util.List; - -import jakarta.servlet.http.HttpServletRequest; - -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.openid4java.consumer.ConsumerManager; -import org.openid4java.discovery.DiscoveryInformation; -import org.openid4java.discovery.yadis.YadisResolver; -import org.openid4java.message.AuthRequest; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationDetailsSource; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.config.annotation.ObjectPostProcessor; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.test.SpringTestContext; -import org.springframework.security.config.test.SpringTestContextExtension; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.openid.OpenIDAttribute; -import org.springframework.security.openid.OpenIDAuthenticationFilter; -import org.springframework.security.openid.OpenIDAuthenticationStatus; -import org.springframework.security.openid.OpenIDAuthenticationToken; -import org.springframework.security.openid.OpenIDConsumer; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; -import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; -import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * Tests to verify that all the functionality of <openid-login> attributes is - * present - * - * @author Rob Winch - * @author Josh Cummings - */ -@ExtendWith(SpringTestContextExtension.class) -public class NamespaceHttpOpenIDLoginTests { - - public final SpringTestContext spring = new SpringTestContext(this); - - @Autowired - MockMvc mvc; - - @Test - public void openidLoginWhenUsingDefaultsThenMatchesNamespace() throws Exception { - this.spring.register(OpenIDLoginConfig.class).autowire(); - this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/login")); - this.mvc.perform(post("/login/openid").with(csrf())).andExpect(redirectedUrl("/login?error")); - } - - @Test - public void openidLoginWhenAttributeExchangeConfiguredThenFetchAttributesMatchAttributeList() throws Exception { - OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER = mock(ConsumerManager.class); - AuthRequest mockAuthRequest = mock(AuthRequest.class); - DiscoveryInformation mockDiscoveryInformation = mock(DiscoveryInformation.class); - given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl"); - given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.associate(any())) - .willReturn(mockDiscoveryInformation); - given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(), - any())).willReturn(mockAuthRequest); - this.spring.register(OpenIDLoginAttributeExchangeConfig.class).autowire(); - try (MockWebServer server = new MockWebServer()) { - String endpoint = server.url("/").toString(); - server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); - server.enqueue(new MockResponse() - .setBody(String.format("%s", endpoint))); - MvcResult mvcResult = this.mvc.perform(get("/login/openid") - .param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "https://www.google.com/1")) - .andExpect(status().isFound()).andReturn(); - Object attributeObject = mvcResult.getRequest().getSession() - .getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST"); - assertThat(attributeObject).isInstanceOf(List.class); - List attributeList = (List) attributeObject; - assertThat(attributeList.stream().anyMatch((attribute) -> "firstname".equals(attribute.getName()) - && "https://axschema.org/namePerson/first".equals(attribute.getType()) && attribute.isRequired())) - .isTrue(); - assertThat(attributeList.stream().anyMatch((attribute) -> "lastname".equals(attribute.getName()) - && "https://axschema.org/namePerson/last".equals(attribute.getType()) && attribute.isRequired())) - .isTrue(); - assertThat(attributeList.stream().anyMatch((attribute) -> "email".equals(attribute.getName()) - && "https://axschema.org/contact/email".equals(attribute.getType()) && attribute.isRequired())) - .isTrue(); - } - } - - @Test - public void openidLoginWhenUsingCustomEndpointsThenMatchesNamespace() throws Exception { - this.spring.register(OpenIDLoginCustomConfig.class).autowire(); - this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/authentication/login")); - this.mvc.perform(post("/authentication/login/process").with(csrf())) - .andExpect(redirectedUrl("/authentication/login?failed")); - } - - @Test - public void openidLoginWithCustomHandlersThenBehaviorMatchesNamespace() throws Exception { - OpenIDAuthenticationToken token = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, - "identityUrl", "message", Arrays.asList(new OpenIDAttribute("name", "type"))); - OpenIDLoginCustomRefsConfig.AUDS = mock(AuthenticationUserDetailsService.class); - User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")); - given(OpenIDLoginCustomRefsConfig.AUDS.loadUserDetails(any(Authentication.class))).willReturn(user); - OpenIDLoginCustomRefsConfig.ADS = spy(new WebAuthenticationDetailsSource()); - OpenIDLoginCustomRefsConfig.CONSUMER = mock(OpenIDConsumer.class); - this.spring.register(OpenIDLoginCustomRefsConfig.class, UserDetailsServiceConfig.class).autowire(); - given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class))) - .willThrow(new AuthenticationServiceException("boom")); - // @formatter:off - MockHttpServletRequestBuilder login = post("/login/openid") - .with(csrf()) - .param("openid.identity", "identity"); - // @formatter:on - this.mvc.perform(login).andExpect(redirectedUrl("/custom/failure")); - reset(OpenIDLoginCustomRefsConfig.CONSUMER); - given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class))).willReturn(token); - this.mvc.perform(login).andExpect(redirectedUrl("/custom/targetUrl")); - verify(OpenIDLoginCustomRefsConfig.AUDS).loadUserDetails(any(Authentication.class)); - verify(OpenIDLoginCustomRefsConfig.ADS).buildDetails(any(Object.class)); - } - - @Configuration - @EnableWebSecurity - static class OpenIDLoginConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests() - .anyRequest().hasRole("USER") - .and() - .openidLogin() - .permitAll(); - // @formatter:on - } - - } - - @Configuration - @EnableWebSecurity - static class OpenIDLoginAttributeExchangeConfig extends WebSecurityConfigurerAdapter { - - static ConsumerManager CONSUMER_MANAGER; - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests() - .anyRequest().hasRole("USER") - .and() - .openidLogin() - .consumerManager(CONSUMER_MANAGER) - .attributeExchange("https://www.google.com/.*") // attribute-exchange@identifier-match - .attribute("email") // openid-attribute@name - .type("https://axschema.org/contact/email") // openid-attribute@type - .required(true) // openid-attribute@required - .count(1) // openid-attribute@count - .and() - .attribute("firstname") - .type("https://axschema.org/namePerson/first") - .required(true) - .and() - .attribute("lastname") - .type("https://axschema.org/namePerson/last") - .required(true) - .and() - .and() - .attributeExchange(".*yahoo.com.*") - .attribute("email") - .type("https://schema.openid.net/contact/email") - .required(true) - .and() - .attribute("fullname") - .type("https://axschema.org/namePerson") - .required(true) - .and() - .and() - .permitAll(); - // @formatter:on - } - - } - - @Configuration - @EnableWebSecurity - static class OpenIDLoginCustomConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - boolean alwaysUseDefaultSuccess = true; - // @formatter:off - http - .authorizeRequests() - .anyRequest().hasRole("USER") - .and() - .openidLogin() - .permitAll() - .loginPage("/authentication/login") // openid-login@login-page - .failureUrl("/authentication/login?failed") // openid-login@authentication-failure-url - .loginProcessingUrl("/authentication/login/process") // openid-login@login-processing-url - .defaultSuccessUrl("/default", alwaysUseDefaultSuccess); // openid-login@default-target-url / openid-login@always-use-default-target - // @formatter:on - } - - } - - @Configuration - @EnableWebSecurity - static class OpenIDLoginCustomRefsConfig extends WebSecurityConfigurerAdapter { - - static AuthenticationUserDetailsService AUDS; - static AuthenticationDetailsSource ADS; - static OpenIDConsumer CONSUMER; - - @Override - protected void configure(HttpSecurity http) throws Exception { - SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler(); - handler.setDefaultTargetUrl("/custom/targetUrl"); - // @formatter:off - http - .authorizeRequests() - .anyRequest().hasRole("USER") - .and() - .openidLogin() - // if using UserDetailsService wrap with new UserDetailsByNameServiceWrapper() - .authenticationUserDetailsService(AUDS) // openid-login@user-service-ref - .failureHandler(new SimpleUrlAuthenticationFailureHandler("/custom/failure")) // openid-login@authentication-failure-handler-ref - .successHandler(handler) // openid-login@authentication-success-handler-ref - .authenticationDetailsSource(ADS) // openid-login@authentication-details-source-ref - .withObjectPostProcessor(new ObjectPostProcessor() { - @Override - public O postProcess(O filter) { - filter.setConsumer(CONSUMER); - return filter; - } - }); - // @formatter:on - } - - } - - @Configuration - static class UserDetailsServiceConfig { - - @Bean - UserDetailsService userDetailsService() { - return new InMemoryUserDetailsManager( - User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build()); - } - - } - -} diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java deleted file mode 100644 index 07c3b0146a..0000000000 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright 2002-2019 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 - * - * https://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.openid; - -import java.util.List; - -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.openid4java.consumer.ConsumerManager; -import org.openid4java.discovery.DiscoveryInformation; -import org.openid4java.discovery.yadis.YadisResolver; -import org.openid4java.message.AuthRequest; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.ObjectPostProcessor; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.test.SpringTestContext; -import org.springframework.security.config.test.SpringTestContextExtension; -import org.springframework.security.openid.OpenIDAttribute; -import org.springframework.security.openid.OpenIDAuthenticationFilter; -import org.springframework.security.openid.OpenIDAuthenticationProvider; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.springframework.security.config.Customizer.withDefaults; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * Tests for {@link OpenIDLoginConfigurer} - * - * @author Rob Winch - * @author Eleftheria Stein - */ -@ExtendWith(SpringTestContextExtension.class) -public class OpenIDLoginConfigurerTests { - - public final SpringTestContext spring = new SpringTestContext(this); - - @Autowired - MockMvc mvc; - - @Test - public void configureWhenRegisteringObjectPostProcessorThenInvokedOnOpenIDAuthenticationFilter() { - ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class); - this.spring.register(ObjectPostProcessorConfig.class).autowire(); - verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(OpenIDAuthenticationFilter.class)); - } - - @Test - public void configureWhenRegisteringObjectPostProcessorThenInvokedOnOpenIDAuthenticationProvider() { - ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class); - this.spring.register(ObjectPostProcessorConfig.class).autowire(); - verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(OpenIDAuthenticationProvider.class)); - } - - @Test - public void openidLoginWhenInvokedTwiceThenUsesOriginalLoginPage() throws Exception { - this.spring.register(InvokeTwiceDoesNotOverrideConfig.class).autowire(); - // @formatter:off - this.mvc.perform(get("/")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("http://localhost/login/custom")); - // @formatter:on - } - - @Test - public void requestWhenOpenIdLoginPageInLambdaThenRedirectsToLoginPAge() throws Exception { - this.spring.register(OpenIdLoginPageInLambdaConfig.class).autowire(); - // @formatter:off - this.mvc.perform(get("/")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("http://localhost/login/custom")); - // @formatter:on - } - - @Test - public void requestWhenAttributeExchangeConfiguredThenFetchAttributesMatchAttributeList() throws Exception { - OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER = mock(ConsumerManager.class); - AuthRequest mockAuthRequest = mock(AuthRequest.class); - DiscoveryInformation mockDiscoveryInformation = mock(DiscoveryInformation.class); - given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl"); - given(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.associate(any())).willReturn(mockDiscoveryInformation); - given(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(), - any())).willReturn(mockAuthRequest); - this.spring.register(OpenIdAttributesInLambdaConfig.class).autowire(); - try (MockWebServer server = new MockWebServer()) { - String endpoint = server.url("/").toString(); - server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); - server.enqueue(new MockResponse() - .setBody(String.format("%s", endpoint))); - MvcResult mvcResult = this.mvc.perform( - get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint)) - .andExpect(status().isFound()).andReturn(); - Object attributeObject = mvcResult.getRequest().getSession() - .getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST"); - assertThat(attributeObject).isInstanceOf(List.class); - List attributeList = (List) attributeObject; - assertThat( - attributeList.stream() - .anyMatch((attribute) -> "nickname".equals(attribute.getName()) - && "https://schema.openid.net/namePerson/friendly".equals(attribute.getType()))) - .isTrue(); - assertThat(attributeList.stream() - .anyMatch((attribute) -> "email".equals(attribute.getName()) - && "https://schema.openid.net/contact/email".equals(attribute.getType()) - && attribute.isRequired() && attribute.getCount() == 2)).isTrue(); - } - } - - @Test - public void requestWhenAttributeNameNotSpecifiedThenAttributeNameDefaulted() throws Exception { - OpenIdAttributesNullNameConfig.CONSUMER_MANAGER = mock(ConsumerManager.class); - AuthRequest mockAuthRequest = mock(AuthRequest.class); - DiscoveryInformation mockDiscoveryInformation = mock(DiscoveryInformation.class); - given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl"); - given(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.associate(any())).willReturn(mockDiscoveryInformation); - given(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(), - any())).willReturn(mockAuthRequest); - this.spring.register(OpenIdAttributesNullNameConfig.class).autowire(); - try (MockWebServer server = new MockWebServer()) { - String endpoint = server.url("/").toString(); - server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); - server.enqueue(new MockResponse() - .setBody(String.format("%s", endpoint))); - // @formatter:off - MockHttpServletRequestBuilder request = get("/login/openid") - .param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint); - MvcResult mvcResult = this.mvc.perform(request) - .andExpect(status().isFound()) - .andReturn(); - Object attributeObject = mvcResult.getRequest().getSession() - .getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST"); - // @formatter:on - assertThat(attributeObject).isInstanceOf(List.class); - List attributeList = (List) attributeObject; - assertThat(attributeList).hasSize(1); - assertThat(attributeList.get(0).getName()).isEqualTo("default-attribute"); - } - } - - @EnableWebSecurity - static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter { - - static ObjectPostProcessor objectPostProcessor; - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .openidLogin(); - // @formatter:on - } - - @Bean - static ObjectPostProcessor objectPostProcessor() { - return objectPostProcessor; - } - - } - - static class ReflectingObjectPostProcessor implements ObjectPostProcessor { - - @Override - public O postProcess(O object) { - return object; - } - - } - - @EnableWebSecurity - static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth - .inMemoryAuthentication(); - // @formatter:on - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests() - .anyRequest().authenticated() - .and() - .openidLogin() - .loginPage("/login/custom") - .and() - .openidLogin(); - // @formatter:on - } - - } - - @EnableWebSecurity - static class OpenIdLoginPageInLambdaConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests((authorizeRequests) -> - authorizeRequests - .anyRequest().authenticated() - ) - .openidLogin((openIdLogin) -> - openIdLogin - .loginPage("/login/custom") - ); - // @formatter:on - } - - } - - @EnableWebSecurity - static class OpenIdAttributesInLambdaConfig extends WebSecurityConfigurerAdapter { - - static ConsumerManager CONSUMER_MANAGER; - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests((authorizeRequests) -> - authorizeRequests - .anyRequest().permitAll() - ) - .openidLogin((openIdLogin) -> - openIdLogin - .consumerManager(CONSUMER_MANAGER) - .attributeExchange((attributeExchange) -> - attributeExchange - .identifierPattern(".*") - .attribute((nicknameAttribute) -> - nicknameAttribute - .name("nickname") - .type("https://schema.openid.net/namePerson/friendly") - ) - .attribute((emailAttribute) -> - emailAttribute - .name("email") - .type("https://schema.openid.net/contact/email") - .required(true) - .count(2) - ) - ) - ); - // @formatter:on - } - - } - - @EnableWebSecurity - static class OpenIdAttributesNullNameConfig extends WebSecurityConfigurerAdapter { - - static ConsumerManager CONSUMER_MANAGER; - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests((authorizeRequests) -> - authorizeRequests - .anyRequest().permitAll() - ) - .openidLogin((openIdLogin) -> - openIdLogin - .consumerManager(CONSUMER_MANAGER) - .attributeExchange((attributeExchange) -> - attributeExchange - .identifierPattern(".*") - .attribute(withDefaults()) - ) - ); - // @formatter:on - } - - } - -} diff --git a/config/src/test/java/org/springframework/security/config/authentication/UserServiceBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/authentication/UserServiceBeanDefinitionParserTests.java index 3240058897..9f6f0747d9 100644 --- a/config/src/test/java/org/springframework/security/config/authentication/UserServiceBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/authentication/UserServiceBeanDefinitionParserTests.java @@ -92,21 +92,6 @@ public class UserServiceBeanDefinitionParserTests { Long.parseLong(joe.getPassword()); } - @Test - public void worksWithOpenIDUrlsAsNames() { - // @formatter:off - setContext("" - + " " - + " " - + ""); - // @formatter:on - UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service"); - assertThat(userService.loadUserByUsername("https://joe.myopenid.com/").getUsername()) - .isEqualTo("https://joe.myopenid.com/"); - assertThat(userService.loadUserByUsername("https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9") - .getUsername()).isEqualTo("https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9"); - } - @Test public void disabledAndEmbeddedFlagsAreSupported() { // @formatter:off diff --git a/config/src/test/java/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.java index afd668ec06..d501ee82bd 100644 --- a/config/src/test/java/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.java @@ -129,91 +129,6 @@ public class FormLoginBeanDefinitionParserTests { // @formatter:on } - @Test - public void getLoginWhenConfiguredForOpenIdThenLoginPageReflects() throws Exception { - this.spring.configLocations(this.xml("WithOpenId")).autowire(); - // @formatter:off - String expectedContent = "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " Please sign in\n" - + " \n" - + " \n" - + " \n" - + " \n" - + "
    \n" - + "
    \n" - + " \n" - + "

    \n" - + " \n" - + " \n" - + "

    \n" - + "

    \n" - + " \n" - + " \n" - + "

    \n" - + " \n" - + "
    \n" - + "
    \n" - + " \n" - + "

    \n" - + " \n" - + " \n" - + "

    \n" - + " \n" - + "
    \n" - + "
    \n" - + ""; - // @formatter:on - this.mvc.perform(get("/login")).andExpect(content().string(expectedContent)); - } - - @Test - public void getLoginWhenConfiguredForOpenIdWithCustomAttributesThenLoginPageReflects() throws Exception { - this.spring.configLocations(this.xml("WithOpenIdCustomAttributes")).autowire(); - // @formatter:off - String expectedContent = "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " Please sign in\n" - + " \n" - + " \n" - + " \n" - + " \n" - + "
    \n" - + "
    \n" - + " \n" - + "

    \n" - + " \n" - + " \n" - + "

    \n" - + "

    \n" - + " \n" - + " \n" - + "

    \n" - + " \n" - + "
    \n" - + "
    \n" - + " \n" + "

    \n" - + " \n" - + " \n" - + "

    \n" - + " \n" - + "
    \n" - + "
    \n" - + ""; - // @formatter:on - this.mvc.perform(get("/login")).andExpect(content().string(expectedContent)); - } - @Test public void failedLoginWhenConfiguredWithCustomAuthenticationFailureThenForwardsAccordingly() throws Exception { this.spring.configLocations(this.xml("WithAuthenticationFailureForwardUrl")).autowire(); diff --git a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java index 9f6128b089..63d7f0886d 100644 --- a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java @@ -78,7 +78,6 @@ import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; -import org.springframework.security.openid.OpenIDAuthenticationFilter; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.access.ExceptionTranslationFilter; @@ -105,7 +104,6 @@ import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.RequestCacheAwareFilter; import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter; import org.springframework.security.web.session.SessionManagementFilter; -import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @@ -624,8 +622,6 @@ public class MiscHttpConfigTests { this.mvc.perform(get("/details").session(session)) .andExpect(content().string(details.getClass().getName())); // @formatter:on - assertThat(ReflectionTestUtils.getField(getFilter(OpenIDAuthenticationFilter.class), - "authenticationDetailsSource")).isEqualTo(source); } @Test diff --git a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java deleted file mode 100644 index dee0a38818..0000000000 --- a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2002-2018 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 - * - * https://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.http; - -import java.util.HashSet; -import java.util.Set; - -import jakarta.servlet.Filter; -import jakarta.servlet.http.HttpServletRequest; - -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.openid4java.consumer.ConsumerManager; -import org.openid4java.discovery.yadis.YadisResolver; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; -import org.springframework.security.config.test.SpringTestContext; -import org.springframework.security.config.test.SpringTestContextExtension; -import org.springframework.security.openid.OpenID4JavaConsumer; -import org.springframework.security.openid.OpenIDAuthenticationFilter; -import org.springframework.security.openid.OpenIDConsumer; -import org.springframework.security.util.FieldUtils; -import org.springframework.security.web.FilterChainProxy; -import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; -import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.CoreMatchers.containsString; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * Tests usage of the <openid-login> element - * - * @author Luke Taylor - */ -@ExtendWith(SpringTestContextExtension.class) -public class OpenIDConfigTests { - - private static final String CONFIG_LOCATION_PREFIX = "classpath:org/springframework/security/config/http/OpenIDConfigTests"; - - @Autowired - MockMvc mvc; - - public final SpringTestContext spring = new SpringTestContext(this); - - @Test - public void requestWhenOpenIDAndFormLoginBothConfiguredThenRedirectsToGeneratedLoginPage() throws Exception { - this.spring.configLocations(this.xml("WithFormLogin")).autowire(); - // @formatter:off - this.mvc.perform(get("/")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("http://localhost/login")); - // @formatter:on - assertThat(getFilter(DefaultLoginPageGeneratingFilter.class)).isNotNull(); - } - - @Test - public void requestWhenOpenIDAndFormLoginWithFormLoginPageConfiguredThenFormLoginPageWins() throws Exception { - this.spring.configLocations(this.xml("WithFormLoginPage")).autowire(); - // @formatter:off - this.mvc.perform(get("/")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("http://localhost/form-page")); - // @formatter:on - } - - @Test - public void requestWhenOpenIDAndFormLoginWithOpenIDLoginPageConfiguredThenOpenIDLoginPageWins() throws Exception { - this.spring.configLocations(this.xml("WithOpenIDLoginPageAndFormLogin")).autowire(); - // @formatter:off - this.mvc.perform(get("/")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("http://localhost/openid-page")); - // @formatter:on - } - - @Test - public void configureWhenOpenIDAndFormLoginBothConfigureLoginPagesThenWiringException() { - assertThatExceptionOfType(BeanDefinitionParsingException.class) - .isThrownBy(() -> this.spring.configLocations(this.xml("WithFormLoginAndOpenIDLoginPages")).autowire()); - } - - @Test - public void requestWhenOpenIDAndRememberMeConfiguredThenRememberMePassedToIdp() throws Exception { - this.spring.configLocations(this.xml("WithRememberMe")).autowire(); - OpenIDAuthenticationFilter openIDFilter = getFilter(OpenIDAuthenticationFilter.class); - String openIdEndpointUrl = "https://testopenid.com?openid.return_to="; - Set returnToUrlParameters = new HashSet<>(); - returnToUrlParameters.add(AbstractRememberMeServices.DEFAULT_PARAMETER); - openIDFilter.setReturnToUrlParameters(returnToUrlParameters); - OpenIDConsumer consumer = mock(OpenIDConsumer.class); - given(consumer.beginConsumption(any(HttpServletRequest.class), anyString(), anyString(), anyString())) - .will((invocation) -> openIdEndpointUrl + invocation.getArgument(2)); - openIDFilter.setConsumer(consumer); - String expectedReturnTo = new StringBuilder("http://localhost/login/openid").append("?") - .append(AbstractRememberMeServices.DEFAULT_PARAMETER).append("=").append("on").toString(); - // @formatter:off - this.mvc.perform(get("/")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("http://localhost/login")); - this.mvc.perform(get("/login")) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(AbstractRememberMeServices.DEFAULT_PARAMETER))); - MockHttpServletRequestBuilder openidLogin = get("/login/openid") - .param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "https://ww1.openid.com") - .param(AbstractRememberMeServices.DEFAULT_PARAMETER, "on"); - this.mvc.perform(openidLogin) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(openIdEndpointUrl + expectedReturnTo)); - // @formatter:on - } - - @Test - public void requestWhenAttributeExchangeConfiguredThenFetchAttributesPassedToIdp() throws Exception { - this.spring.configLocations(this.xml("WithOpenIDAttributes")).autowire(); - OpenIDAuthenticationFilter openIDFilter = getFilter(OpenIDAuthenticationFilter.class); - OpenID4JavaConsumer consumer = getFieldValue(openIDFilter, "consumer"); - ConsumerManager manager = getFieldValue(consumer, "consumerManager"); - manager.setMaxAssocAttempts(0); - try (MockWebServer server = new MockWebServer()) { - String endpoint = server.url("/").toString(); - server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); - server.enqueue(new MockResponse() - .setBody(String.format("%s", endpoint))); - this.mvc.perform( - get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint)) - .andExpect(status().isFound()) - .andExpect((result) -> result.getResponse().getRedirectedUrl().endsWith( - "openid.ext1.type.nickname=http%3A%2F%2Fschema.openid.net%2FnamePerson%2Ffriendly&" - + "openid.ext1.if_available=nickname&" - + "openid.ext1.type.email=http%3A%2F%2Fschema.openid.net%2Fcontact%2Femail&" - + "openid.ext1.required=email&" + "openid.ext1.count.email=2")); - } - } - - /** - * SEC-2919 - */ - @Test - public void requestWhenLoginPageConfiguredWithPhraseLoginThenRedirectsOnlyToUserGeneratedLoginPage() - throws Exception { - this.spring.configLocations(this.xml("Sec2919")).autowire(); - assertThat(getFilter(DefaultLoginPageGeneratingFilter.class)).isNull(); - // @formatter:off - this.mvc.perform(get("/login")) - .andExpect(status().isOk()) - .andExpect(content().string("a custom login page")); - // @formatter:on - } - - private T getFilter(Class clazz) { - FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class); - return (T) filterChain.getFilters("/").stream().filter(clazz::isInstance).findFirst().orElse(null); - } - - private String xml(String configName) { - return CONFIG_LOCATION_PREFIX + "-" + configName + ".xml"; - } - - private static T getFieldValue(Object bean, String fieldName) throws IllegalAccessException { - return (T) FieldUtils.getFieldValue(bean, fieldName); - } - - @RestController - static class CustomLoginController { - - @GetMapping("/login") - String custom() { - return "a custom login page"; - } - - } - -} diff --git a/config/src/test/resources/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests-WithOpenId.xml b/config/src/test/resources/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests-WithOpenId.xml deleted file mode 100644 index 2f470a67e3..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests-WithOpenId.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - diff --git a/config/src/test/resources/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests-WithOpenIdCustomAttributes.xml b/config/src/test/resources/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests-WithOpenIdCustomAttributes.xml deleted file mode 100644 index c088988603..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests-WithOpenIdCustomAttributes.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - diff --git a/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CustomAuthenticationDetailsSourceRef.xml b/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CustomAuthenticationDetailsSourceRef.xml index 464b57716e..41c049ce60 100644 --- a/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CustomAuthenticationDetailsSourceRef.xml +++ b/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CustomAuthenticationDetailsSourceRef.xml @@ -28,7 +28,6 @@ - diff --git a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-Sec2919.xml b/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-Sec2919.xml deleted file mode 100644 index c16954ca47..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-Sec2919.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLogin.xml b/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLogin.xml deleted file mode 100644 index de1398e153..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLogin.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - diff --git a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLoginAndOpenIDLoginPages.xml b/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLoginAndOpenIDLoginPages.xml deleted file mode 100644 index 0311a2d591..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLoginAndOpenIDLoginPages.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - diff --git a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLoginPage.xml b/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLoginPage.xml deleted file mode 100644 index e02aff0b80..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithFormLoginPage.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - diff --git a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithOpenIDAttributes.xml b/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithOpenIDAttributes.xml deleted file mode 100644 index 9f539d01e3..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithOpenIDAttributes.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithOpenIDLoginPageAndFormLogin.xml b/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithOpenIDLoginPageAndFormLogin.xml deleted file mode 100644 index 65a220b12b..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithOpenIDLoginPageAndFormLogin.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - diff --git a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithRememberMe.xml b/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithRememberMe.xml deleted file mode 100644 index 85c4bc4283..0000000000 --- a/config/src/test/resources/org/springframework/security/config/http/OpenIDConfigTests-WithRememberMe.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - diff --git a/core/src/main/java/org/springframework/security/authentication/InternalAuthenticationServiceException.java b/core/src/main/java/org/springframework/security/authentication/InternalAuthenticationServiceException.java index 140bbb8f2e..3037ebaaf0 100644 --- a/core/src/main/java/org/springframework/security/authentication/InternalAuthenticationServiceException.java +++ b/core/src/main/java/org/springframework/security/authentication/InternalAuthenticationServiceException.java @@ -29,7 +29,7 @@ package org.springframework.security.authentication; *

    * This might be thrown if a backend authentication repository is unavailable, for * example. However, it would not be thrown in the event that an error occurred when - * validating an OpenID response with an OpenID Provider. + * validating an OIDC response from an OIDC provider. *

    * * @author Rob Winch diff --git a/dependencies/spring-security-dependencies.gradle b/dependencies/spring-security-dependencies.gradle index 1483eb02c1..dce3f2e696 100644 --- a/dependencies/spring-security-dependencies.gradle +++ b/dependencies/spring-security-dependencies.gradle @@ -58,7 +58,6 @@ dependencies { api "org.mockito:mockito-core:3.12.4" api "org.mockito:mockito-inline:3.12.4" api "org.mockito:mockito-junit-jupiter:3.12.4" - api "org.openid4java:openid4java-nodeps:0.9.6" api "org.opensaml:opensaml-core:$openSamlVersion" api "org.opensaml:opensaml-saml-api:$openSamlVersion" api "org.opensaml:opensaml-saml-impl:$openSamlVersion" diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index f69fee64e6..28bc5af3b8 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -38,7 +38,6 @@ ***** xref:servlet/authentication/passwords/ldap.adoc[LDAP] *** xref:servlet/authentication/session-management.adoc[Session Management] *** xref:servlet/authentication/rememberme.adoc[Remember Me] -*** xref:servlet/authentication/openid.adoc[OpenID] *** xref:servlet/authentication/anonymous.adoc[Anonymous] *** xref:servlet/authentication/preauth.adoc[Pre-Authentication] *** xref:servlet/authentication/jaas.adoc[JAAS] diff --git a/docs/modules/ROOT/pages/getting-spring-security.adoc b/docs/modules/ROOT/pages/getting-spring-security.adoc index 3ef4465472..a5f733060d 100644 --- a/docs/modules/ROOT/pages/getting-spring-security.adoc +++ b/docs/modules/ROOT/pages/getting-spring-security.adoc @@ -71,7 +71,7 @@ You can do so by adding a Maven property: ---- ==== -If you use additional features (such as LDAP, OpenID, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies]. +If you use additional features (such as LDAP, OAuth 2, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies]. [[getting-maven-no-boot]] === Maven Without Spring Boot @@ -117,7 +117,7 @@ A minimal Spring Security Maven set of dependencies typically looks like the fol ---- ==== -If you use additional features (such as LDAP, OpenID, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies]. +If you use additional features (such as LDAP, OAuth 2, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies]. Spring Security builds against Spring Framework {spring-core-version} but should generally work with any newer version of Spring Framework 5.x. Many users are likely to run afoul of the fact that Spring Security's transitive dependencies resolve Spring Framework {spring-core-version}, which can cause strange classpath problems. @@ -238,7 +238,7 @@ ext['spring.version']='{spring-core-version}' ---- ==== -If you use additional features (such as LDAP, OpenID, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies]. +If you use additional features (such as LDAP, OAuth 2, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies]. === Gradle Without Spring Boot @@ -276,7 +276,7 @@ dependencies { ---- ==== -If you use additional features (such as LDAP, OpenID, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies]. +If you use additional features (such as LDAP, OAuth 2, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies]. Spring Security builds against Spring Framework {spring-core-version} but should generally work with any newer version of Spring Framework 5.x. Many users are likely to run afoul of the fact that Spring Security's transitive dependencies resolve Spring Framework {spring-core-version}, which can cause strange classpath problems. diff --git a/docs/modules/ROOT/pages/modules.adoc b/docs/modules/ROOT/pages/modules.adoc index 9d02bff889..c74d34fb04 100644 --- a/docs/modules/ROOT/pages/modules.adoc +++ b/docs/modules/ROOT/pages/modules.adoc @@ -139,10 +139,6 @@ None of the classes are intended for direct use in an application. | | Required if you are using the LDAP namespace options (optional). -| spring-security-openid -| -| Required if you are using OpenID authentication (optional). - | aspectjweaver | 1.6.10 | Required if using the protect-pointcut namespace syntax (optional). @@ -275,44 +271,6 @@ This is the basis of the Spring Security integration. | Required if you are using the Ehcache-based ticket cache (optional). |=== -[[spring-security-openid]] -== OpenID -- `spring-security-openid.jar` - -[NOTE] -==== -The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2. -==== - -This module contains OpenID web authentication support. -It is used to authenticate users against an external OpenID server. -The top-level package is `org.springframework.security.openid`. -It requires OpenID4Java. - -.OpenID Dependencies -|=== -| Dependency | Version | Description - -| spring-security-core -| -| - -| spring-security-web -| -| - -| openid4java-nodeps -| 0.9.6 -| Spring Security's OpenID integration uses OpenID4Java. - -| httpclient -| 4.1.1 -| openid4java-nodeps depends on HttpClient 4. - -| guice -| 2.0 -| openid4java-nodeps depends on Guice 2. -|=== - [[spring-security-test]] == Test -- `spring-security-test.jar` diff --git a/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc b/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc index eb81c2734c..170eb53e18 100644 --- a/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc +++ b/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc @@ -159,7 +159,6 @@ The default value is true. * <> * <> * <> -* <> * <> * <> * <> @@ -838,7 +837,7 @@ Used to add an `UsernamePasswordAuthenticationFilter` to the filter stack and an This will always take precedence over other namespace-created entry points. If no attributes are supplied, a login page will be generated automatically at the URL "/login" footnote:[ This feature is really just provided for convenience and is not intended for production (where a view technology will have been chosen and can be used to render a customized login page). -The class `DefaultLoginPageGeneratingFilter` is responsible for rendering the login page and will provide login forms for both normal form login and/or OpenID if required. +The class `DefaultLoginPageGeneratingFilter` is responsible for rendering the login page and will provide login forms for both normal form login and/or OIDC if required. ] The behaviour can be customized using the <` Attributes>>. @@ -1476,182 +1475,6 @@ Defaults to "/logout". May be used to supply an instance of `LogoutSuccessHandler` which will be invoked to control the navigation after logging out. -[[nsa-openid-login]] -== -Similar to `` and has the same attributes. -The default value for `login-processing-url` is "/login/openid". -An `OpenIDAuthenticationFilter` and `OpenIDAuthenticationProvider` will be registered. -The latter requires a reference to a `UserDetailsService`. -Again, this can be specified by `id`, using the `user-service-ref` attribute, or will be located automatically in the application context. - - -[[nsa-openid-login-parents]] -=== Parent Elements of - - -* <> - - - -[[nsa-openid-login-attributes]] -=== Attributes - - -[[nsa-openid-login-always-use-default-target]] -* **always-use-default-target** -Whether the user should always be redirected to the default-target-url after login. - - -[[nsa-openid-login-authentication-details-source-ref]] -* **authentication-details-source-ref** -Reference to an AuthenticationDetailsSource which will be used by the authentication filter - - -[[nsa-openid-login-authentication-failure-handler-ref]] -* **authentication-failure-handler-ref** -Reference to an AuthenticationFailureHandler bean which should be used to handle a failed authentication request. -Should not be used in combination with authentication-failure-url as the implementation should always deal with navigation to the subsequent destination - - -[[nsa-openid-login-authentication-failure-url]] -* **authentication-failure-url** -The URL for the login failure page. -If no login failure URL is specified, Spring Security will automatically create a failure login URL at /login?login_error and a corresponding filter to render that login failure URL when requested. - - -[[nsa-openid-login-authentication-success-forward-url]] -* **authentication-success-forward-url** -Maps a `ForwardAuthenticationSuccessHandler` to `authenticationSuccessHandler` property of `UsernamePasswordAuthenticationFilter`. - - -[[nsa-openid-login-authentication-failure-forward-url]] -* **authentication-failure-forward-url** -Maps a `ForwardAuthenticationFailureHandler` to `authenticationFailureHandler` property of `UsernamePasswordAuthenticationFilter`. - - -[[nsa-openid-login-authentication-success-handler-ref]] -* **authentication-success-handler-ref** -Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful authentication request. -Should not be used in combination with <> (or <>) as the implementation should always deal with navigation to the subsequent destination - - -[[nsa-openid-login-default-target-url]] -* **default-target-url** -The URL that will be redirected to after successful authentication, if the user's previous action could not be resumed. -This generally happens if the user visits a login page without having first requested a secured operation that triggers authentication. -If unspecified, defaults to the root of the application. - - -[[nsa-openid-login-login-page]] -* **login-page** -The URL for the login page. -If no login URL is specified, Spring Security will automatically create a login URL at /login and a corresponding filter to render that login URL when requested. - - -[[nsa-openid-login-login-processing-url]] -* **login-processing-url** -The URL that the login form is posted to. -If unspecified, it defaults to /login. - - -[[nsa-openid-login-password-parameter]] -* **password-parameter** -The name of the request parameter which contains the password. -Defaults to "password". - - -[[nsa-openid-login-user-service-ref]] -* **user-service-ref** -A reference to a user-service (or UserDetailsService bean) Id - - -[[nsa-openid-login-username-parameter]] -* **username-parameter** -The name of the request parameter which contains the username. -Defaults to "username". - - -[[nsa-openid-login-children]] -=== Child Elements of -* <> - - - -[[nsa-attribute-exchange]] -== -The `attribute-exchange` element defines the list of attributes which should be requested from the identity provider. -An example can be found in the xref:servlet/authentication/openid.adoc#servlet-openid[OpenID Support] section of the namespace configuration chapter. -More than one can be used, in which case each must have an `identifier-match` attribute, containing a regular expression which is matched against the supplied OpenID identifier. -This allows different attribute lists to be fetched from different providers (Google, Yahoo etc). - - -[[nsa-attribute-exchange-parents]] -=== Parent Elements of - - -* <> - - - -[[nsa-attribute-exchange-attributes]] -=== Attributes - - -[[nsa-attribute-exchange-identifier-match]] -* **identifier-match** -A regular expression which will be compared against the claimed identity, when deciding which attribute-exchange configuration to use during authentication. - - -[[nsa-attribute-exchange-children]] -=== Child Elements of - - -* <> - - - -[[nsa-openid-attribute]] -== -Attributes used when making an OpenID AX https://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_request[ Fetch Request] - - -[[nsa-openid-attribute-parents]] -=== Parent Elements of - - -* <> - - - -[[nsa-openid-attribute-attributes]] -=== Attributes - - -[[nsa-openid-attribute-count]] -* **count** -Specifies the number of attributes that you wish to get back. -For example, return 3 emails. -The default value is 1. - - -[[nsa-openid-attribute-name]] -* **name** -Specifies the name of the attribute that you wish to get back. -For example, email. - - -[[nsa-openid-attribute-required]] -* **required** -Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. -Default is false. - - -[[nsa-openid-attribute-type]] -* **type** -Specifies the attribute type. -For example, https://axschema.org/contact/email. -See your OP's documentation for valid attribute types. - [[nsa-password-management]] == This element configures password management. diff --git a/docs/modules/ROOT/pages/servlet/architecture.adoc b/docs/modules/ROOT/pages/servlet/architecture.adoc index 26b9a329f9..0612b85b8a 100644 --- a/docs/modules/ROOT/pages/servlet/architecture.adoc +++ b/docs/modules/ROOT/pages/servlet/architecture.adoc @@ -182,7 +182,6 @@ The following is a comprehensive list of Spring Security Filter ordering: * `OAuth2LoginAuthenticationFilter` * `Saml2WebSsoAuthenticationFilter` * xref:servlet/authentication/passwords/form.adoc#servlet-authentication-usernamepasswordauthenticationfilter[`UsernamePasswordAuthenticationFilter`] -* `OpenIDAuthenticationFilter` * `DefaultLoginPageGeneratingFilter` * `DefaultLogoutPageGeneratingFilter` * `ConcurrentSessionFilter` diff --git a/docs/modules/ROOT/pages/servlet/authentication/index.adoc b/docs/modules/ROOT/pages/servlet/authentication/index.adoc index 83ed147bb9..42802897e9 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/index.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/index.adoc @@ -18,6 +18,5 @@ These sections focus on specific ways you may want to authenticate and point bac * xref:servlet/saml2/index.adoc#servlet-saml2[SAML 2.0 Login] - SAML 2.0 Log In * xref:servlet/authentication/rememberme.adoc#servlet-rememberme[Remember Me] - how to remember a user past session expiration * xref:servlet/authentication/jaas.adoc#servlet-jaas[JAAS Authentication] - authenticate with JAAS -* xref:servlet/authentication/openid.adoc#servlet-openid[OpenID] - OpenID Authentication (not to be confused with OpenID Connect) * xref:servlet/authentication/preauth.adoc#servlet-preauth[Pre-Authentication Scenarios] - authenticate with an external mechanism such as https://www.siteminder.com/[SiteMinder] or Java EE security but still use Spring Security for authorization and protection against common exploits. * xref:servlet/authentication/x509.adoc#servlet-x509[X509 Authentication] - X509 Authentication diff --git a/docs/modules/ROOT/pages/servlet/authentication/openid.adoc b/docs/modules/ROOT/pages/servlet/authentication/openid.adoc deleted file mode 100644 index 28c00fb257..0000000000 --- a/docs/modules/ROOT/pages/servlet/authentication/openid.adoc +++ /dev/null @@ -1,70 +0,0 @@ -[[servlet-openid]] -= OpenID Support - -[NOTE] -==== -The OpenID 1.0 and 2.0 protocols have been deprecated. You should migrate to OpenID Connect, which is supported by `spring-security-oauth2`. -==== - -The namespace supports https://openid.net/[OpenID] login either instead of or in addition to normal form-based login, with a simple change: - -==== -[source,xml] ----- - - - - ----- -==== - -You should then register yourself with an OpenID provider (such as myopenid.com), and add the user information to your in-memory ``: - -==== -[source,xml] ----- - ----- -==== - -You should be able to login by using the `myopenid.com` site to authenticate. -You can also select a specific `UserDetailsService` bean for use with OpenID by setting the `user-service-ref` attribute on the `openid-login` element. -Note that we have omitted the password attribute from the above user configuration, since this set of user data is being used only to load the authorities for the user. -A random password is generated internally, preventing you from accidentally using this user data as an authentication source elsewhere in your configuration. - - -== Attribute Exchange -Spring Security includes support for OpenID https://openid.net/specs/openid-attribute-exchange-1_0.html[attribute exchange]. -As an example, the following configuration tries to retrieve the email and full name from the OpenID provider for use by the application: - -==== -[source,xml] ----- - - - - - - ----- -==== - -The "`type`" of each OpenID attribute is a URI, determined by a particular schema -- in this case, https://axschema.org/[https://axschema.org/]. -If an attribute must be retrieved for successful authentication, you can set the `required` attribute. -The exact schema and attributes supported depend on your OpenID provider. -The attribute values are returned as part of the authentication process and can be accessed afterwards by using the following code: - -==== -[source,java] ----- -OpenIDAuthenticationToken token = - (OpenIDAuthenticationToken)SecurityContextHolder.getContext().getAuthentication(); -List attributes = token.getAttributes(); ----- -==== - -We can obtain the `OpenIDAuthenticationToken` from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. -The `OpenIDAttribute` contains the attribute type and the retrieved value (or values in the case of multi-valued attributes). -You can supply multiple `attribute-exchange` elements by using an `identifier-matcher` attribute on each element. -This contains a regular expression that is matched against the OpenID identifier supplied by the user. -See the OpenID sample application in the codebase for an example configuration, providing different attribute lists for the Google, Yahoo and MyOpenID providers. diff --git a/etc/s101/project.java.hsp b/etc/s101/project.java.hsp index 1e876cd2e4..58211eb9a7 100644 --- a/etc/s101/project.java.hsp +++ b/etc/s101/project.java.hsp @@ -29,7 +29,6 @@ - diff --git a/openid/spring-security-openid.gradle b/openid/spring-security-openid.gradle deleted file mode 100644 index 5bbd99d35b..0000000000 --- a/openid/spring-security-openid.gradle +++ /dev/null @@ -1,43 +0,0 @@ -// NOTE: The OpenID 1.0 and 2.0 protocols have been deprecated and users are -// encouraged to migrate -// to OpenID Connect, which is supported by spring-security-oauth2. - -apply plugin: 'io.spring.convention.spring-module' - -dependencies { - management platform(project(":spring-security-dependencies")) - api project(':spring-security-core') - api project(':spring-security-web') - api('com.google.inject:guice') { - exclude group: 'aopalliance', module: 'aopalliance' - exclude group: 'javax.inject', module: 'javax.inject' - } - // openid4java has a compile time dep on guice with a group - // name which is different from the maven central one. - // We use the maven central version here instead. - api('org.openid4java:openid4java-nodeps') { - exclude group: 'com.google.code.guice', module: 'guice' - exclude group: 'commons-logging', module: 'commons-logging' - } - api 'org.springframework:spring-aop' - api 'org.springframework:spring-beans' - api 'org.springframework:spring-context' - api 'org.springframework:spring-core' - api 'org.springframework:spring-web' - - provided 'jakarta.servlet:jakarta.servlet-api' - - runtimeOnly 'net.sourceforge.nekohtml:nekohtml' - runtimeOnly('org.apache.httpcomponents:httpclient') { - exclude group: 'commons-logging', module: 'commons-logging' - } - - testImplementation "jakarta.inject:jakarta.inject-api" - testImplementation "org.assertj:assertj-core" - testImplementation "org.junit.jupiter:junit-jupiter-api" - testImplementation "org.junit.jupiter:junit-jupiter-params" - testImplementation "org.junit.jupiter:junit-jupiter-engine" - testImplementation "org.mockito:mockito-core" - testImplementation "org.mockito:mockito-junit-jupiter" - testImplementation "org.springframework:spring-test" -} diff --git a/openid/src/main/java/org/springframework/security/openid/AuthenticationCancelledException.java b/openid/src/main/java/org/springframework/security/openid/AuthenticationCancelledException.java deleted file mode 100644 index 089b710612..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/AuthenticationCancelledException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -import org.springframework.security.core.AuthenticationException; - -/** - * Indicates that OpenID authentication was cancelled - * - * @author Robin Bramley, Opsera Ltd - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class AuthenticationCancelledException extends AuthenticationException { - - public AuthenticationCancelledException(String msg) { - super(msg); - } - - public AuthenticationCancelledException(String msg, Throwable cause) { - super(msg, cause); - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/AxFetchListFactory.java b/openid/src/main/java/org/springframework/security/openid/AxFetchListFactory.java deleted file mode 100644 index f6b4f5bd57..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/AxFetchListFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2002-2016 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 - * - * https://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.openid; - -import java.util.List; - -/** - * A strategy which can be used by an OpenID consumer implementation, to dynamically - * determine the attribute exchange information based on the OpenID identifier. - *

    - * This allows the list of attributes for a fetch request to be tailored for different - * OpenID providers, since they do not all support the same attributes. - * - * @author Luke Taylor - * @since 3.1 - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public interface AxFetchListFactory { - - /** - * Builds the list of attributes which should be added to the fetch request for the - * supplied OpenID identifier. - * @param identifier the claimed_identity - * @return the attributes to fetch for this identifier - */ - List createAttributeList(String identifier); - -} diff --git a/openid/src/main/java/org/springframework/security/openid/NullAxFetchListFactory.java b/openid/src/main/java/org/springframework/security/openid/NullAxFetchListFactory.java deleted file mode 100644 index 2d34debff5..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/NullAxFetchListFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2002-2016 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 - * - * https://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.openid; - -import java.util.Collections; -import java.util.List; - -/** - * @author Luke Taylor - * @since 3.1 - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class NullAxFetchListFactory implements AxFetchListFactory { - - @Override - public List createAttributeList(String identifier) { - return Collections.emptyList(); - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java b/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java deleted file mode 100644 index 085999f3a9..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import jakarta.servlet.http.HttpServletRequest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openid4java.association.AssociationException; -import org.openid4java.consumer.ConsumerException; -import org.openid4java.consumer.ConsumerManager; -import org.openid4java.consumer.VerificationResult; -import org.openid4java.discovery.DiscoveryException; -import org.openid4java.discovery.DiscoveryInformation; -import org.openid4java.discovery.Identifier; -import org.openid4java.message.AuthRequest; -import org.openid4java.message.Message; -import org.openid4java.message.MessageException; -import org.openid4java.message.MessageExtension; -import org.openid4java.message.ParameterList; -import org.openid4java.message.ax.AxMessage; -import org.openid4java.message.ax.FetchRequest; -import org.openid4java.message.ax.FetchResponse; - -import org.springframework.util.StringUtils; - -/** - * @author Ray Krueger - * @author Luke Taylor - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -@SuppressWarnings("unchecked") -public class OpenID4JavaConsumer implements OpenIDConsumer { - - private static final String DISCOVERY_INFO_KEY = DiscoveryInformation.class.getName(); - - private static final String ATTRIBUTE_LIST_KEY = "SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST"; - - protected final Log logger = LogFactory.getLog(getClass()); - - private final ConsumerManager consumerManager; - - private final AxFetchListFactory attributesToFetchFactory; - - public OpenID4JavaConsumer() throws ConsumerException { - this(new ConsumerManager(), new NullAxFetchListFactory()); - } - - public OpenID4JavaConsumer(AxFetchListFactory attributesToFetchFactory) throws ConsumerException { - this(new ConsumerManager(), attributesToFetchFactory); - } - - public OpenID4JavaConsumer(ConsumerManager consumerManager, AxFetchListFactory attributesToFetchFactory) { - this.consumerManager = consumerManager; - this.attributesToFetchFactory = attributesToFetchFactory; - } - - @Override - public String beginConsumption(HttpServletRequest req, String identityUrl, String returnToUrl, String realm) - throws OpenIDConsumerException { - List discoveries = getDiscoveries(identityUrl); - DiscoveryInformation information = this.consumerManager.associate(discoveries); - req.getSession().setAttribute(DISCOVERY_INFO_KEY, information); - AuthRequest authReq = getAuthRequest(req, identityUrl, returnToUrl, realm, information); - return authReq.getDestinationUrl(true); - } - - private List getDiscoveries(String identityUrl) throws OpenIDConsumerException { - try { - return this.consumerManager.discover(identityUrl); - } - catch (DiscoveryException ex) { - throw new OpenIDConsumerException("Error during discovery", ex); - } - } - - private AuthRequest getAuthRequest(HttpServletRequest req, String identityUrl, String returnToUrl, String realm, - DiscoveryInformation information) throws OpenIDConsumerException { - try { - AuthRequest authReq = this.consumerManager.authenticate(information, returnToUrl, realm); - this.logger.debug("Looking up attribute fetch list for identifier: " + identityUrl); - List attributesToFetch = this.attributesToFetchFactory.createAttributeList(identityUrl); - if (!attributesToFetch.isEmpty()) { - req.getSession().setAttribute(ATTRIBUTE_LIST_KEY, attributesToFetch); - FetchRequest fetchRequest = FetchRequest.createFetchRequest(); - for (OpenIDAttribute attr : attributesToFetch) { - if (this.logger.isDebugEnabled()) { - this.logger.debug("Adding attribute " + attr.getType() + " to fetch request"); - } - fetchRequest.addAttribute(attr.getName(), attr.getType(), attr.isRequired(), attr.getCount()); - } - authReq.addExtension(fetchRequest); - } - return authReq; - } - catch (MessageException | ConsumerException ex) { - throw new OpenIDConsumerException("Error processing ConsumerManager authentication", ex); - } - } - - @Override - public OpenIDAuthenticationToken endConsumption(HttpServletRequest request) throws OpenIDConsumerException { - // extract the parameters from the authentication response - // (which comes in as a HTTP request from the OpenID provider) - ParameterList openidResp = new ParameterList(request.getParameterMap()); - // retrieve the previously stored discovery information - DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute(DISCOVERY_INFO_KEY); - if (discovered == null) { - throw new OpenIDConsumerException( - "DiscoveryInformation is not available. Possible causes are lost session or replay attack"); - } - List attributesToFetch = (List) request.getSession() - .getAttribute(ATTRIBUTE_LIST_KEY); - request.getSession().removeAttribute(DISCOVERY_INFO_KEY); - request.getSession().removeAttribute(ATTRIBUTE_LIST_KEY); - // extract the receiving URL from the HTTP request - StringBuffer receivingURL = request.getRequestURL(); - String queryString = request.getQueryString(); - if (StringUtils.hasLength(queryString)) { - receivingURL.append("?").append(request.getQueryString()); - } - // verify the response - VerificationResult verification; - try { - verification = this.consumerManager.verify(receivingURL.toString(), openidResp, discovered); - } - catch (MessageException | AssociationException | DiscoveryException ex) { - throw new OpenIDConsumerException("Error verifying openid response", ex); - } - // examine the verification result and extract the verified identifier - Identifier verified = verification.getVerifiedId(); - if (verified == null) { - Identifier id = discovered.getClaimedIdentifier(); - return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, - (id != null) ? id.getIdentifier() : "Unknown", - "Verification status message: [" + verification.getStatusMsg() + "]", - Collections.emptyList()); - } - List attributes = fetchAxAttributes(verification.getAuthResponse(), attributesToFetch); - return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, verified.getIdentifier(), - "some message", attributes); - } - - List fetchAxAttributes(Message authSuccess, List attributesToFetch) - throws OpenIDConsumerException { - if (attributesToFetch == null || !authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { - return Collections.emptyList(); - } - this.logger.debug("Extracting attributes retrieved by attribute exchange"); - List attributes = Collections.emptyList(); - try { - MessageExtension ext = authSuccess.getExtension(AxMessage.OPENID_NS_AX); - if (ext instanceof FetchResponse) { - FetchResponse fetchResp = (FetchResponse) ext; - attributes = new ArrayList<>(attributesToFetch.size()); - for (OpenIDAttribute attr : attributesToFetch) { - List values = fetchResp.getAttributeValues(attr.getName()); - if (!values.isEmpty()) { - OpenIDAttribute fetched = new OpenIDAttribute(attr.getName(), attr.getType(), values); - fetched.setRequired(attr.isRequired()); - attributes.add(fetched); - } - } - } - } - catch (MessageException ex) { - throw new OpenIDConsumerException("Attribute retrieval failed", ex); - } - if (this.logger.isDebugEnabled()) { - this.logger.debug("Retrieved attributes" + attributes); - } - return attributes; - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDAttribute.java b/openid/src/main/java/org/springframework/security/openid/OpenIDAttribute.java deleted file mode 100644 index 003c067146..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDAttribute.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2002-2016 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 - * - * https://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.openid; - -import java.io.Serializable; -import java.util.List; - -import org.springframework.util.Assert; - -/** - * Represents an OpenID subject identity attribute. - *

    - * Can be used for configuring the OpenID4JavaConsumer with the attributes which - * should be requested during a fetch request, or to hold values for an attribute which - * are returned during the authentication process. - * - * @author Luke Taylor - * @since 3.0 - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class OpenIDAttribute implements Serializable { - - private final String name; - - private final String typeIdentifier; - - private boolean required = false; - - private int count = 1; - - private final List values; - - public OpenIDAttribute(String name, String type) { - this.name = name; - this.typeIdentifier = type; - this.values = null; - } - - public OpenIDAttribute(String name, String type, List values) { - Assert.notEmpty(values, "values cannot be empty"); - this.name = name; - this.typeIdentifier = type; - this.values = values; - } - - /** - * The attribute name - */ - public String getName() { - return this.name; - } - - /** - * The attribute type Identifier (a URI). - */ - public String getType() { - return this.typeIdentifier; - } - - /** - * The "required" flag for the attribute when used with an authentication request. - * Defaults to "false". - */ - public boolean isRequired() { - return this.required; - } - - public void setRequired(boolean required) { - this.required = required; - } - - /** - * The requested count for the attribute when it is used as part of an authentication - * request. Defaults to 1. - */ - public int getCount() { - return this.count; - } - - public void setCount(int count) { - this.count = count; - } - - /** - * The values obtained from an attribute exchange. - */ - public List getValues() { - Assert.notNull(this.values, "Cannot read values from an authentication request attribute"); - return this.values; - } - - @Override - public String toString() { - StringBuilder result = new StringBuilder("["); - result.append(this.name); - if (this.values != null) { - result.append(":"); - result.append(this.values.toString()); - } - result.append("]"); - return result.toString(); - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationFilter.java b/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationFilter.java deleted file mode 100644 index 915ff464b6..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationFilter.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -import org.openid4java.consumer.ConsumerException; - -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; -import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -/** - * Filter which processes OpenID authentication requests. - *

    - * The OpenID authentication involves two stages. - * - *

    Submission of OpenID identity

    - * - * The user's OpenID identity is submitted via a login form, just as it would be for a - * normal form login. At this stage the filter will extract the identity from the - * submitted request (by default, the parameter is called openid_identifier, as - * recommended by the OpenID 2.0 Specification). It then passes the identity to the - * configured OpenIDConsumer, which returns the URL to which the request should - * be redirected for authentication. A "return_to" URL is also supplied, which matches the - * URL processed by this filter, to allow the filter to handle the request once the user - * has been successfully authenticated. The OpenID server will then authenticate the user - * and redirect back to the application. - * - *

    Processing the Redirect from the OpenID Server

    - * - * Once the user has been authenticated externally, the redirected request will be passed - * to the OpenIDConsumer again for validation. The returned - * OpenIDAuthentication will be passed to the AuthenticationManager - * where it should (normally) be processed by an OpenIDAuthenticationProvider in - * order to load the authorities for the user. - * - * @author Robin Bramley - * @author Ray Krueger - * @author Luke Taylor - * @since 2.0 - * @see OpenIDAuthenticationProvider - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessingFilter { - - public static final String DEFAULT_CLAIMED_IDENTITY_FIELD = "openid_identifier"; - - private OpenIDConsumer consumer; - - private String claimedIdentityFieldName = DEFAULT_CLAIMED_IDENTITY_FIELD; - - private Map realmMapping = Collections.emptyMap(); - - private Set returnToUrlParameters = Collections.emptySet(); - - public OpenIDAuthenticationFilter() { - super("/login/openid"); - } - - @Override - public void afterPropertiesSet() { - super.afterPropertiesSet(); - if (this.consumer == null) { - try { - this.consumer = new OpenID4JavaConsumer(); - } - catch (ConsumerException ex) { - throw new IllegalArgumentException("Failed to initialize OpenID", ex); - } - } - if (this.returnToUrlParameters.isEmpty() && getRememberMeServices() instanceof AbstractRememberMeServices) { - this.returnToUrlParameters = new HashSet<>(); - this.returnToUrlParameters.add(((AbstractRememberMeServices) getRememberMeServices()).getParameter()); - } - } - - /** - * Authentication has two phases. - *
      - *
    1. The initial submission of the claimed OpenID. A redirect to the URL returned - * from the consumer will be performed and null will be returned.
    2. - *
    3. The redirection from the OpenID server to the return_to URL, once it has - * authenticated the user
    4. - *
    - */ - @Override - public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) - throws AuthenticationException, IOException { - OpenIDAuthenticationToken token; - String identity = request.getParameter("openid.identity"); - if (!StringUtils.hasText(identity)) { - String claimedIdentity = obtainUsername(request); - try { - String returnToUrl = buildReturnToUrl(request); - String realm = lookupRealm(returnToUrl); - String openIdUrl = this.consumer.beginConsumption(request, claimedIdentity, returnToUrl, realm); - if (this.logger.isDebugEnabled()) { - this.logger.debug("return_to is '" + returnToUrl + "', realm is '" + realm + "'"); - this.logger.debug("Redirecting to " + openIdUrl); - } - response.sendRedirect(openIdUrl); - // Indicate to parent class that authentication is continuing. - return null; - } - catch (OpenIDConsumerException ex) { - this.logger.debug("Failed to consume claimedIdentity: " + claimedIdentity, ex); - throw new AuthenticationServiceException( - "Unable to process claimed identity '" + claimedIdentity + "'"); - } - } - if (this.logger.isDebugEnabled()) { - this.logger.debug("Supplied OpenID identity is " + identity); - } - try { - token = this.consumer.endConsumption(request); - } - catch (OpenIDConsumerException ex) { - throw new AuthenticationServiceException("Consumer error", ex); - } - token.setDetails(this.authenticationDetailsSource.buildDetails(request)); - // delegate to the authentication provider - Authentication authentication = this.getAuthenticationManager().authenticate(token); - return authentication; - } - - protected String lookupRealm(String returnToUrl) { - String mapping = this.realmMapping.get(returnToUrl); - if (mapping == null) { - try { - URL url = new URL(returnToUrl); - int port = url.getPort(); - StringBuilder realmBuffer = new StringBuilder(returnToUrl.length()).append(url.getProtocol()) - .append("://").append(url.getHost()); - if (port > 0) { - realmBuffer.append(":").append(port); - } - realmBuffer.append("/"); - mapping = realmBuffer.toString(); - } - catch (MalformedURLException ex) { - this.logger.warn("returnToUrl was not a valid URL: [" + returnToUrl + "]", ex); - } - } - return mapping; - } - - /** - * Builds the return_to URL that will be sent to the OpenID service provider. - * By default returns the URL of the current request. - * @param request the current request which is being processed by this filter - * @return The return_to URL. - */ - protected String buildReturnToUrl(HttpServletRequest request) { - StringBuffer sb = request.getRequestURL(); - Iterator iterator = this.returnToUrlParameters.iterator(); - boolean isFirst = true; - while (iterator.hasNext()) { - String name = iterator.next(); - // Assume for simplicity that there is only one value - String value = request.getParameter(name); - if (value == null) { - continue; - } - if (isFirst) { - sb.append("?"); - isFirst = false; - } - sb.append(utf8UrlEncode(name)).append("=").append(utf8UrlEncode(value)); - if (iterator.hasNext()) { - sb.append("&"); - } - } - return sb.toString(); - } - - /** - * Reads the claimedIdentityFieldName from the submitted request. - */ - protected String obtainUsername(HttpServletRequest req) { - String claimedIdentity = req.getParameter(this.claimedIdentityFieldName); - if (!StringUtils.hasText(claimedIdentity)) { - this.logger.error("No claimed identity supplied in authentication request"); - return ""; - } - return claimedIdentity.trim(); - } - - /** - * Maps the return_to url to a realm, for example: - * - *
    -	 * https://www.example.com/login/openid -> https://www.example.com/realm
    -	 * 
    - * - * If no mapping is provided then the returnToUrl will be parsed to extract the - * protocol, hostname and port followed by a trailing slash. This means that - * https://foo.example.com/login/openid will automatically become - * http://foo.example.com:80/ - * @param realmMapping containing returnToUrl -> realm mappings - */ - public void setRealmMapping(Map realmMapping) { - this.realmMapping = realmMapping; - } - - /** - * The name of the request parameter containing the OpenID identity, as submitted from - * the initial login form. - * @param claimedIdentityFieldName defaults to "openid_identifier" - */ - public void setClaimedIdentityFieldName(String claimedIdentityFieldName) { - this.claimedIdentityFieldName = claimedIdentityFieldName; - } - - public void setConsumer(OpenIDConsumer consumer) { - this.consumer = consumer; - } - - /** - * Specifies any extra parameters submitted along with the identity field which should - * be appended to the {@code return_to} URL which is assembled by - * {@link #buildReturnToUrl}. - * @param returnToUrlParameters the set of parameter names. If not set, it will - * default to the parameter name used by the {@code RememberMeServices} obtained from - * the parent class (if one is set). - */ - public void setReturnToUrlParameters(Set returnToUrlParameters) { - Assert.notNull(returnToUrlParameters, "returnToUrlParameters cannot be null"); - this.returnToUrlParameters = returnToUrlParameters; - } - - /** - * Performs URL encoding with UTF-8 - * @param value the value to URL encode - * @return the encoded value - */ - private String utf8UrlEncode(String value) { - try { - return URLEncoder.encode(value, "UTF-8"); - } - catch (UnsupportedEncodingException ex) { - Error err = new AssertionError( - "The Java platform guarantees UTF-8 support, but it seemingly is not present."); - err.initCause(ex); - throw err; - } - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationProvider.java b/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationProvider.java deleted file mode 100644 index b1f71d54ff..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationProvider.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; -import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper; -import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.util.Assert; - -/** - * Finalises the OpenID authentication by obtaining local authorities for the - * authenticated user. - *

    - * The authorities are obtained by calling the configured {@code UserDetailsService}. The - * {@code UserDetails} it returns must, at minimum, contain the username and - * {@code GrantedAuthority} objects applicable to the authenticated user. Note that by - * default, Spring Security ignores the password and enabled/disabled status of the - * {@code UserDetails} because this is authentication-related and should have been - * enforced by another provider server. - *

    - * The {@code UserDetails} returned by implementations is stored in the generated - * {@code Authentication} token, so additional properties such as email addresses, - * telephone numbers etc can easily be stored. - * - * @author Robin Bramley, Opsera Ltd. - * @author Luke Taylor - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class OpenIDAuthenticationProvider implements AuthenticationProvider, InitializingBean { - - private AuthenticationUserDetailsService userDetailsService; - - private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper(); - - @Override - public void afterPropertiesSet() { - Assert.notNull(this.userDetailsService, "The userDetailsService must be set"); - } - - @Override - public Authentication authenticate(final Authentication authentication) throws AuthenticationException { - if (!supports(authentication.getClass())) { - return null; - } - if (!(authentication instanceof OpenIDAuthenticationToken)) { - return null; - } - OpenIDAuthenticationToken response = (OpenIDAuthenticationToken) authentication; - OpenIDAuthenticationStatus status = response.getStatus(); - // handle the various possibilities - if (status == OpenIDAuthenticationStatus.SUCCESS) { - // Lookup user details - UserDetails userDetails = this.userDetailsService.loadUserDetails(response); - return createSuccessfulAuthentication(userDetails, response); - } - if (status == OpenIDAuthenticationStatus.CANCELLED) { - throw new AuthenticationCancelledException("Log in cancelled"); - } - if (status == OpenIDAuthenticationStatus.ERROR) { - throw new AuthenticationServiceException("Error message from server: " + response.getMessage()); - } - if (status == OpenIDAuthenticationStatus.FAILURE) { - throw new BadCredentialsException("Log in failed - identity could not be verified"); - } - if (status == OpenIDAuthenticationStatus.SETUP_NEEDED) { - throw new AuthenticationServiceException("The server responded setup was needed, which shouldn't happen"); - } - throw new AuthenticationServiceException("Unrecognized return value " + status.toString()); - } - - /** - * Handles the creation of the final Authentication object which will be - * returned by the provider. - *

    - * The default implementation just creates a new OpenIDAuthenticationToken from the - * original, but with the UserDetails as the principal and including the authorities - * loaded by the UserDetailsService. - * @param userDetails the loaded UserDetails object - * @param auth the token passed to the authenticate method, containing - * @return the token which will represent the authenticated user. - */ - protected Authentication createSuccessfulAuthentication(UserDetails userDetails, OpenIDAuthenticationToken auth) { - return new OpenIDAuthenticationToken(userDetails, - this.authoritiesMapper.mapAuthorities(userDetails.getAuthorities()), auth.getIdentityUrl(), - auth.getAttributes()); - } - - /** - * Used to load the {@code UserDetails} for the authenticated OpenID user. - */ - public void setUserDetailsService(UserDetailsService userDetailsService) { - this.userDetailsService = new UserDetailsByNameServiceWrapper<>(userDetailsService); - } - - /** - * Used to load the {@code UserDetails} for the authenticated OpenID user. - */ - public void setAuthenticationUserDetailsService( - AuthenticationUserDetailsService userDetailsService) { - this.userDetailsService = userDetailsService; - } - - @Override - public boolean supports(Class authentication) { - return OpenIDAuthenticationToken.class.isAssignableFrom(authentication); - } - - public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { - this.authoritiesMapper = authoritiesMapper; - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationStatus.java b/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationStatus.java deleted file mode 100644 index e7c4450ed2..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationStatus.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -/** - * Authentication status codes, based on JanRain status codes - * @author JanRain Inc. - * @author Robin Bramley, Opsera Ltd - * @author Luke Taylor - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -public enum OpenIDAuthenticationStatus { - - /** This code indicates a successful authentication request */ - SUCCESS("success"), - - /** This code indicates a failed authentication request */ - FAILURE("failure"), - - /** This code indicates the server reported an error */ - ERROR("error"), - - /** - * This code indicates that the user needs to do additional work to prove their - * identity - */ - SETUP_NEEDED("setup needed"), - - /** This code indicates that the user cancelled their login request */ - CANCELLED("cancelled"); - - private final String name; - - OpenIDAuthenticationStatus(String name) { - this.name = name; - } - - @Override - public String toString() { - return this.name; - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationToken.java b/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationToken.java deleted file mode 100644 index 3a3d0de93e..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationToken.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.springframework.security.authentication.AbstractAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.SpringSecurityCoreVersion; - -/** - * OpenID Authentication Token - * - * @author Robin Bramley - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class OpenIDAuthenticationToken extends AbstractAuthenticationToken { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - private final OpenIDAuthenticationStatus status; - - private final Object principal; - - private final String identityUrl; - - private final String message; - - private final List attributes; - - public OpenIDAuthenticationToken(OpenIDAuthenticationStatus status, String identityUrl, String message, - List attributes) { - super(new ArrayList<>(0)); - this.principal = identityUrl; - this.status = status; - this.identityUrl = identityUrl; - this.message = message; - this.attributes = attributes; - setAuthenticated(false); - } - - /** - * Created by the OpenIDAuthenticationProvider on successful authentication. - * @param principal usually the UserDetails returned by the configured - * UserDetailsService used by the OpenIDAuthenticationProvider. - */ - public OpenIDAuthenticationToken(Object principal, Collection authorities, - String identityUrl, List attributes) { - super(authorities); - this.principal = principal; - this.status = OpenIDAuthenticationStatus.SUCCESS; - this.identityUrl = identityUrl; - this.message = null; - this.attributes = attributes; - - setAuthenticated(true); - } - - /** - * Returns 'null' always, as no credentials are processed by the OpenID provider. - * @see org.springframework.security.core.Authentication#getCredentials() - */ - @Override - public Object getCredentials() { - return null; - } - - public String getIdentityUrl() { - return this.identityUrl; - } - - public String getMessage() { - return this.message; - } - - /** - * Returns the principal value. - * - * @see org.springframework.security.core.Authentication#getPrincipal() - */ - @Override - public Object getPrincipal() { - return this.principal; - } - - public OpenIDAuthenticationStatus getStatus() { - return this.status; - } - - public List getAttributes() { - return this.attributes; - } - - @Override - public String toString() { - return "[" + super.toString() + ", attributes : " + this.attributes + "]"; - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDConsumer.java b/openid/src/main/java/org/springframework/security/openid/OpenIDConsumer.java deleted file mode 100644 index a58e4ba6e4..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDConsumer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -import jakarta.servlet.http.HttpServletRequest; - -/** - * An interface for OpenID library implementations - * - * @author Ray Krueger - * @author Robin Bramley, Opsera Ltd - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public interface OpenIDConsumer { - - /** - * Given the request, the claimedIdentity, the return to url, and a realm, lookup the - * openId authentication page the user should be redirected to. - * @param req HttpServletRequest - * @param claimedIdentity String URI the user presented during authentication - * @param returnToUrl String URI of the URL we want the user sent back to by the OP - * @param realm URI pattern matching the realm we want the user to see - * @return String URI to redirect user to for authentication - * @throws OpenIDConsumerException if anything bad happens - */ - String beginConsumption(HttpServletRequest req, String claimedIdentity, String returnToUrl, String realm) - throws OpenIDConsumerException; - - OpenIDAuthenticationToken endConsumption(HttpServletRequest req) throws OpenIDConsumerException; - -} diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDConsumerException.java b/openid/src/main/java/org/springframework/security/openid/OpenIDConsumerException.java deleted file mode 100644 index b020f0efe4..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDConsumerException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -/** - * Thrown by an OpenIDConsumer if it cannot process a request - * - * @author Robin Bramley, Opsera Ltd - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class OpenIDConsumerException extends Exception { - - public OpenIDConsumerException(String message) { - super(message); - } - - public OpenIDConsumerException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/RegexBasedAxFetchListFactory.java b/openid/src/main/java/org/springframework/security/openid/RegexBasedAxFetchListFactory.java deleted file mode 100644 index 9a41eb1090..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/RegexBasedAxFetchListFactory.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2002-2016 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 - * - * https://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.openid; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * @author Luke Taylor - * @since 3.1 - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class RegexBasedAxFetchListFactory implements AxFetchListFactory { - - private final Map> idToAttributes; - - /** - * @param regexMap map of regular-expressions (matching the identifier) to attributes - * which should be fetched for that pattern. - */ - public RegexBasedAxFetchListFactory(Map> regexMap) { - this.idToAttributes = new LinkedHashMap<>(); - for (Map.Entry> entry : regexMap.entrySet()) { - this.idToAttributes.put(Pattern.compile(entry.getKey()), entry.getValue()); - } - } - - /** - * Iterates through the patterns stored in the map and returns the list of attributes - * defined for the first match. If no match is found, returns an empty list. - */ - @Override - public List createAttributeList(String identifier) { - for (Map.Entry> entry : this.idToAttributes.entrySet()) { - if (entry.getKey().matcher(identifier).matches()) { - return entry.getValue(); - } - } - return Collections.emptyList(); - } - -} diff --git a/openid/src/main/java/org/springframework/security/openid/package-info.java b/openid/src/main/java/org/springframework/security/openid/package-info.java deleted file mode 100644 index 62b2897d07..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/package-info.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2002-2016 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 - * - * https://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.openid; diff --git a/openid/src/main/java/org/springframework/security/openid/package.html b/openid/src/main/java/org/springframework/security/openid/package.html deleted file mode 100644 index f2417fd615..0000000000 --- a/openid/src/main/java/org/springframework/security/openid/package.html +++ /dev/null @@ -1,9 +0,0 @@ - - -

    Authenticates standard web browser users via OpenID.

    - -

    NOTE: The OpenID 1.0 and 2.0 protocols have been deprecated and users are - encouraged to migrate - to OpenID Connect, which is supported by spring-security-oauth2.

    - - diff --git a/openid/src/test/java/org/springframework/security/openid/MockOpenIDConsumer.java b/openid/src/test/java/org/springframework/security/openid/MockOpenIDConsumer.java deleted file mode 100644 index a4a142b0b1..0000000000 --- a/openid/src/test/java/org/springframework/security/openid/MockOpenIDConsumer.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -import jakarta.servlet.http.HttpServletRequest; - -/** - * @author Robin Bramley, Opsera Ltd - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class MockOpenIDConsumer implements OpenIDConsumer { - - private OpenIDAuthenticationToken token; - - private String redirectUrl; - - public MockOpenIDConsumer() { - } - - public MockOpenIDConsumer(String redirectUrl, OpenIDAuthenticationToken token) { - this.redirectUrl = redirectUrl; - this.token = token; - } - - public MockOpenIDConsumer(String redirectUrl) { - this.redirectUrl = redirectUrl; - } - - public MockOpenIDConsumer(OpenIDAuthenticationToken token) { - this.token = token; - } - - @Override - public String beginConsumption(HttpServletRequest req, String claimedIdentity, String returnToUrl, String realm) { - return this.redirectUrl; - } - - @Override - public OpenIDAuthenticationToken endConsumption(HttpServletRequest req) { - return this.token; - } - - /** - * Set the redirectUrl to be returned by beginConsumption - * @param redirectUrl - */ - public void setRedirectUrl(String redirectUrl) { - this.redirectUrl = redirectUrl; - } - - public void setReturnToUrl(String returnToUrl) { - // TODO Auto-generated method stub - } - - /** - * Set the token to be returned by endConsumption - * @param token - */ - public void setToken(OpenIDAuthenticationToken token) { - this.token = token; - } - -} diff --git a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java deleted file mode 100644 index 632316954f..0000000000 --- a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright 2002-2016 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 - * - * https://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.openid; - -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import org.openid4java.association.AssociationException; -import org.openid4java.consumer.ConsumerException; -import org.openid4java.consumer.ConsumerManager; -import org.openid4java.consumer.VerificationResult; -import org.openid4java.discovery.DiscoveryException; -import org.openid4java.discovery.DiscoveryInformation; -import org.openid4java.discovery.Identifier; -import org.openid4java.message.AuthRequest; -import org.openid4java.message.Message; -import org.openid4java.message.MessageException; -import org.openid4java.message.ParameterList; -import org.openid4java.message.ax.AxMessage; -import org.openid4java.message.ax.FetchResponse; - -import org.springframework.mock.web.MockHttpServletRequest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * @author Luke Taylor - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class OpenID4JavaConsumerTests { - - List attributes = Arrays.asList(new OpenIDAttribute("a", "b"), - new OpenIDAttribute("b", "b", Arrays.asList("c"))); - - @SuppressWarnings("deprecation") - @Test - public void beginConsumptionCreatesExpectedSessionData() throws Exception { - ConsumerManager mgr = mock(ConsumerManager.class); - AuthRequest authReq = mock(AuthRequest.class); - DiscoveryInformation di = mock(DiscoveryInformation.class); - given(mgr.authenticate(any(DiscoveryInformation.class), any(), any())).willReturn(authReq); - given(mgr.associate(any())).willReturn(di); - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new MockAttributesFactory()); - MockHttpServletRequest request = new MockHttpServletRequest(); - consumer.beginConsumption(request, "", "", ""); - assertThat(request.getSession().getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST")) - .isEqualTo(this.attributes); - assertThat(request.getSession().getAttribute(DiscoveryInformation.class.getName())).isEqualTo(di); - // Check with empty attribute fetch list - consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - request = new MockHttpServletRequest(); - consumer.beginConsumption(request, "", "", ""); - } - - @Test - public void discoveryExceptionRaisesOpenIDException() throws Exception { - ConsumerManager mgr = mock(ConsumerManager.class); - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - given(mgr.discover(any())).willThrow(new DiscoveryException("msg")); - assertThatExceptionOfType(OpenIDConsumerException.class) - .isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", "")); - } - - @Test - public void messageOrConsumerAuthenticationExceptionRaisesOpenIDException() throws Exception { - ConsumerManager mgr = mock(ConsumerManager.class); - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - given(mgr.authenticate(ArgumentMatchers.any(), any(), any())) - .willThrow(new MessageException("msg"), new ConsumerException("msg")); - assertThatExceptionOfType(OpenIDConsumerException.class) - .isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", "")); - assertThatExceptionOfType(OpenIDConsumerException.class) - .isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", "")); - } - - @Test - public void failedVerificationReturnsFailedAuthenticationStatus() throws Exception { - ConsumerManager mgr = mock(ConsumerManager.class); - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - VerificationResult vr = mock(VerificationResult.class); - DiscoveryInformation di = mock(DiscoveryInformation.class); - given(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))).willReturn(vr); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession().setAttribute(DiscoveryInformation.class.getName(), di); - OpenIDAuthenticationToken auth = consumer.endConsumption(request); - assertThat(auth.getStatus()).isEqualTo(OpenIDAuthenticationStatus.FAILURE); - } - - @Test - public void verificationExceptionsRaiseOpenIDException() throws Exception { - ConsumerManager mgr = mock(ConsumerManager.class); - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - given(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))) - .willThrow(new MessageException(""), new AssociationException(""), new DiscoveryException("")); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setQueryString("x=5"); - assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request)); - assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request)); - assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request)); - } - - @SuppressWarnings("serial") - @Test - public void successfulVerificationReturnsExpectedAuthentication() throws Exception { - ConsumerManager mgr = mock(ConsumerManager.class); - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - VerificationResult vr = mock(VerificationResult.class); - DiscoveryInformation di = mock(DiscoveryInformation.class); - Identifier id = (Identifier) () -> "id"; - Message msg = mock(Message.class); - given(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))).willReturn(vr); - given(vr.getVerifiedId()).willReturn(id); - given(vr.getAuthResponse()).willReturn(msg); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession().setAttribute(DiscoveryInformation.class.getName(), di); - request.getSession().setAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST", this.attributes); - OpenIDAuthenticationToken auth = consumer.endConsumption(request); - assertThat(auth.getStatus()).isEqualTo(OpenIDAuthenticationStatus.SUCCESS); - } - - @Test - public void fetchAttributesReturnsExpectedValues() throws Exception { - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); - Message msg = mock(Message.class); - FetchResponse fr = mock(FetchResponse.class); - given(msg.hasExtension(AxMessage.OPENID_NS_AX)).willReturn(true); - given(msg.getExtension(AxMessage.OPENID_NS_AX)).willReturn(fr); - given(fr.getAttributeValues("a")).willReturn(Arrays.asList("x", "y")); - List fetched = consumer.fetchAxAttributes(msg, this.attributes); - assertThat(fetched).hasSize(1); - assertThat(fetched.get(0).getValues()).hasSize(2); - } - - @Test - public void messageExceptionFetchingAttributesRaisesOpenIDException() throws Exception { - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); - Message msg = mock(Message.class); - FetchResponse fr = mock(FetchResponse.class); - given(msg.hasExtension(AxMessage.OPENID_NS_AX)).willReturn(true); - given(msg.getExtension(AxMessage.OPENID_NS_AX)).willThrow(new MessageException("")); - given(fr.getAttributeValues("a")).willReturn(Arrays.asList("x", "y")); - assertThatExceptionOfType(OpenIDConsumerException.class) - .isThrownBy(() -> consumer.fetchAxAttributes(msg, this.attributes)); - } - - @Test - public void missingDiscoveryInformationThrowsException() throws Exception { - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); - assertThatExceptionOfType(OpenIDConsumerException.class) - .isThrownBy(() -> consumer.endConsumption(new MockHttpServletRequest())); - } - - @Test - public void additionalConstructorsWork() throws Exception { - new OpenID4JavaConsumer(); - new OpenID4JavaConsumer(new MockAttributesFactory()); - } - - private class MockAttributesFactory implements AxFetchListFactory { - - @Override - public List createAttributeList(String identifier) { - return OpenID4JavaConsumerTests.this.attributes; - } - - } - -} diff --git a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java deleted file mode 100644 index 54062063a2..0000000000 --- a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2002-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 - * - * https://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.openid; - -import java.net.URI; -import java.util.Collections; - -import jakarta.servlet.FilterChain; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -/** - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class OpenIDAuthenticationFilterTests { - - OpenIDAuthenticationFilter filter; - - private static final String REDIRECT_URL = "https://www.example.com/redirect"; - - private static final String CLAIMED_IDENTITY_URL = "https://www.example.com/identity"; - - private static final String REQUEST_PATH = "/login/openid"; - - private static final String FILTER_PROCESS_URL = "http://localhost:8080" + REQUEST_PATH; - - private static final String DEFAULT_TARGET_URL = FILTER_PROCESS_URL; - - @BeforeEach - public void setUp() { - this.filter = new OpenIDAuthenticationFilter(); - this.filter.setConsumer(new MockOpenIDConsumer(REDIRECT_URL)); - SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); - this.filter.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler()); - successHandler.setDefaultTargetUrl(DEFAULT_TARGET_URL); - this.filter.setAuthenticationManager((a) -> a); - this.filter.afterPropertiesSet(); - } - - @Test - public void testFilterOperation() throws Exception { - MockHttpServletRequest req = new MockHttpServletRequest(); - req.setServletPath(REQUEST_PATH); - req.setRequestURI(REQUEST_PATH); - req.setServerPort(8080); - MockHttpServletResponse response = new MockHttpServletResponse(); - req.setParameter("openid_identifier", " " + CLAIMED_IDENTITY_URL); - req.setRemoteHost("www.example.com"); - this.filter.setConsumer(new MockOpenIDConsumer() { - @Override - public String beginConsumption(HttpServletRequest req, String claimedIdentity, String returnToUrl, - String realm) { - assertThat(claimedIdentity).isEqualTo(CLAIMED_IDENTITY_URL); - assertThat(returnToUrl).isEqualTo(DEFAULT_TARGET_URL); - assertThat(realm).isEqualTo("http://localhost:8080/"); - return REDIRECT_URL; - } - }); - FilterChain fc = mock(FilterChain.class); - this.filter.doFilter(req, response, fc); - assertThat(response.getRedirectedUrl()).isEqualTo(REDIRECT_URL); - // Filter chain shouldn't proceed - verify(fc, never()).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); - } - - /** - * Tests that the filter encodes any query parameters on the return_to URL. - */ - @Test - public void encodesUrlParameters() throws Exception { - // Arbitrary parameter name and value that will both need to be encoded: - String paramName = "foo&bar"; - String paramValue = "https://example.com/path?a=b&c=d"; - MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_PATH); - req.addParameter(paramName, paramValue); - this.filter.setReturnToUrlParameters(Collections.singleton(paramName)); - URI returnTo = new URI(this.filter.buildReturnToUrl(req)); - String query = returnTo.getRawQuery(); - assertThat(count(query, '=')).isEqualTo(1); - assertThat(count(query, '&')).isZero(); - } - - /** - * Counts the number of occurrences of {@code c} in {@code s}. - */ - private static int count(String s, char c) { - int count = 0; - for (char ch : s.toCharArray()) { - if (c == ch) { - count += 1; - } - } - return count; - } - -} diff --git a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java deleted file mode 100644 index 2bc034861d..0000000000 --- a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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 - * - * https://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.openid; - -import org.junit.jupiter.api.Test; - -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper; -import org.springframework.security.core.userdetails.UserDetailsService; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests {@link OpenIDAuthenticationProvider} - * - * @author Robin Bramley, Opsera Ltd - * @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are - * encouraged to - * migrate to OpenID Connect, which is - * supported by spring-security-oauth2. - */ -@Deprecated -public class OpenIDAuthenticationProviderTests { - - private static final String USERNAME = "user.acegiopenid.com"; - - /* - * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. - * authenticate(Authentication)' - */ - @Test - public void testAuthenticateCancel() { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setUserDetailsService(new MockUserDetailsService()); - provider.setAuthoritiesMapper(new NullAuthoritiesMapper()); - Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.CANCELLED, USERNAME, "", - null); - assertThat(preAuth.isAuthenticated()).isFalse(); - assertThatExceptionOfType(AuthenticationCancelledException.class) - .isThrownBy(() -> provider.authenticate(preAuth)).withMessage("Log in cancelled"); - } - - /* - * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. - * authenticate(Authentication)' - */ - @Test - public void testAuthenticateError() { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setUserDetailsService(new MockUserDetailsService()); - Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.ERROR, USERNAME, "", null); - assertThat(preAuth.isAuthenticated()).isFalse(); - assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(preAuth)) - .withMessage("Error message from server: "); - } - - /* - * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. - * authenticate(Authentication)' - */ - @Test - public void testAuthenticateFailure() { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setAuthenticationUserDetailsService( - new UserDetailsByNameServiceWrapper<>(new MockUserDetailsService())); - Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, USERNAME, "", null); - assertThat(preAuth.isAuthenticated()).isFalse(); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(preAuth)) - .withMessage("Log in failed - identity could not be verified"); - } - - /* - * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. - * authenticate(Authentication)' - */ - @Test - public void testAuthenticateSetupNeeded() { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setUserDetailsService(new MockUserDetailsService()); - Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SETUP_NEEDED, USERNAME, "", - null); - assertThat(preAuth.isAuthenticated()).isFalse(); - assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(preAuth)) - .withMessage("The server responded setup was needed, which shouldn't happen"); - } - - /* - * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. - * authenticate(Authentication)' - */ - @Test - public void testAuthenticateSuccess() { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setUserDetailsService(new MockUserDetailsService()); - Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, USERNAME, "", null); - assertThat(preAuth.isAuthenticated()).isFalse(); - Authentication postAuth = provider.authenticate(preAuth); - assertThat(postAuth).isNotNull(); - assertThat(postAuth instanceof OpenIDAuthenticationToken).isTrue(); - assertThat(postAuth.isAuthenticated()).isTrue(); - assertThat(postAuth.getPrincipal()).isNotNull(); - assertThat(postAuth.getPrincipal() instanceof UserDetails).isTrue(); - assertThat(postAuth.getAuthorities()).isNotNull(); - assertThat(postAuth.getAuthorities().size() > 0).isTrue(); - assertThat(((OpenIDAuthenticationToken) postAuth).getStatus() == OpenIDAuthenticationStatus.SUCCESS).isTrue(); - assertThat(((OpenIDAuthenticationToken) postAuth).getMessage() == null).isTrue(); - } - - @Test - public void testDetectsMissingAuthoritiesPopulator() throws Exception { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); - } - - /* - * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. - * supports(Class)' - */ - @Test - public void testDoesntSupport() { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setUserDetailsService(new MockUserDetailsService()); - assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isFalse(); - } - - /* - * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. - * authenticate(Authentication)' - */ - @Test - public void testIgnoresUserPassAuthToken() { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setUserDetailsService(new MockUserDetailsService()); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(USERNAME, "password"); - assertThat(provider.authenticate(token)).isNull(); - } - - /* - * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. - * supports(Class)' - */ - @Test - public void testSupports() { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setUserDetailsService(new MockUserDetailsService()); - assertThat(provider.supports(OpenIDAuthenticationToken.class)).isTrue(); - } - - @Test - public void testValidation() throws Exception { - OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); - provider = new OpenIDAuthenticationProvider(); - provider.setUserDetailsService(new MockUserDetailsService()); - provider.afterPropertiesSet(); - } - - static class MockUserDetailsService implements UserDetailsService { - - @Override - public UserDetails loadUserByUsername(String ssoUserId) throws AuthenticationException { - return new User(ssoUserId, "password", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B")); - } - - } - -} diff --git a/openid/src/test/resources/logback-test.xml b/openid/src/test/resources/logback-test.xml deleted file mode 100644 index cc1fc42b4e..0000000000 --- a/openid/src/test/resources/logback-test.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - diff --git a/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java index c90c8bb569..a8ba24df5e 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java @@ -280,7 +280,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt * * @param request from which to extract parameters and perform the authentication * @param response the response, which may be needed if the implementation has to do a - * redirect as part of a multi-stage authentication process (such as OpenID). + * redirect as part of a multi-stage authentication process (such as OIDC). * @return the authenticated user token, or null if authentication is incomplete. * @throws AuthenticationException if authentication fails. */ diff --git a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java index d8750baf69..cec816dcad 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java @@ -32,7 +32,6 @@ import jakarta.servlet.http.HttpSession; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.WebAttributes; -import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; import org.springframework.util.Assert; @@ -63,8 +62,6 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { private boolean formLoginEnabled; - private boolean openIdEnabled; - private boolean oauth2LoginEnabled; private boolean saml2LoginEnabled; @@ -77,12 +74,6 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { private String rememberMeParameter; - private String openIDauthenticationUrl; - - private String openIDusernameParameter; - - private String openIDrememberMeParameter; - private Map oauth2AuthenticationUrlToClientName; private Map saml2AuthenticationUrlToProviderName; @@ -92,31 +83,13 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { public DefaultLoginPageGeneratingFilter() { } - public DefaultLoginPageGeneratingFilter(AbstractAuthenticationProcessingFilter filter) { - if (filter instanceof UsernamePasswordAuthenticationFilter) { - init((UsernamePasswordAuthenticationFilter) filter, null); - } - else { - init(null, filter); - } - } - - public DefaultLoginPageGeneratingFilter(UsernamePasswordAuthenticationFilter authFilter, - AbstractAuthenticationProcessingFilter openIDFilter) { - init(authFilter, openIDFilter); - } - - private void init(UsernamePasswordAuthenticationFilter authFilter, - AbstractAuthenticationProcessingFilter openIDFilter) { + public DefaultLoginPageGeneratingFilter(UsernamePasswordAuthenticationFilter authFilter) { this.loginPageUrl = DEFAULT_LOGIN_PAGE_URL; this.logoutSuccessUrl = DEFAULT_LOGIN_PAGE_URL + "?logout"; this.failureUrl = DEFAULT_LOGIN_PAGE_URL + "?" + ERROR_PARAMETER_NAME; if (authFilter != null) { initAuthFilter(authFilter); } - if (openIDFilter != null) { - initOpenIdFilter(openIDFilter); - } } private void initAuthFilter(UsernamePasswordAuthenticationFilter authFilter) { @@ -128,15 +101,6 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { } } - private void initOpenIdFilter(AbstractAuthenticationProcessingFilter openIDFilter) { - this.openIdEnabled = true; - this.openIDusernameParameter = "openid_identifier"; - if (openIDFilter.getRememberMeServices() instanceof AbstractRememberMeServices) { - this.openIDrememberMeParameter = ((AbstractRememberMeServices) openIDFilter.getRememberMeServices()) - .getParameter(); - } - } - /** * Sets a Function used to resolve a Map of the hidden inputs where the key is the * name of the input and the value is the value of the input. Typically this is used @@ -149,7 +113,7 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { } public boolean isEnabled() { - return this.formLoginEnabled || this.openIdEnabled || this.oauth2LoginEnabled || this.saml2LoginEnabled; + return this.formLoginEnabled || this.oauth2LoginEnabled || this.saml2LoginEnabled; } public void setLogoutSuccessUrl(String logoutSuccessUrl) { @@ -172,10 +136,6 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { this.formLoginEnabled = formLoginEnabled; } - public void setOpenIdEnabled(boolean openIdEnabled) { - this.openIdEnabled = openIdEnabled; - } - public void setOauth2LoginEnabled(boolean oauth2LoginEnabled) { this.oauth2LoginEnabled = oauth2LoginEnabled; } @@ -198,15 +158,6 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { public void setRememberMeParameter(String rememberMeParameter) { this.rememberMeParameter = rememberMeParameter; - this.openIDrememberMeParameter = rememberMeParameter; - } - - public void setOpenIDauthenticationUrl(String openIDauthenticationUrl) { - this.openIDauthenticationUrl = openIDauthenticationUrl; - } - - public void setOpenIDusernameParameter(String openIDusernameParameter) { - this.openIDusernameParameter = openIDusernameParameter; } public void setOauth2AuthenticationUrlToClientName(Map oauth2AuthenticationUrlToClientName) { @@ -282,19 +233,6 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { sb.append(" \n"); sb.append(" \n"); } - if (this.openIdEnabled) { - sb.append("
    \n"); - sb.append(" \n"); - sb.append(createError(loginError, errorMsg) + createLogoutSuccess(logoutSuccess) + "

    \n"); - sb.append(" \n"); - sb.append(" \n"); - sb.append("

    \n"); - sb.append(createRememberMe(this.openIDrememberMeParameter) + renderHiddenInputs(request)); - sb.append(" \n"); - sb.append("
    \n"); - } if (this.oauth2LoginEnabled) { sb.append(""); sb.append(createError(loginError, errorMsg)); diff --git a/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java index d5b4ed29e0..b3b9d702fe 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java @@ -20,8 +20,6 @@ import java.util.Collections; import java.util.Locale; import jakarta.servlet.FilterChain; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; @@ -29,8 +27,6 @@ import org.springframework.context.support.MessageSourceAccessor; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter; @@ -131,12 +127,6 @@ public class DefaultLoginPageGeneratingFilterTests { assertThat(response.getContentAsString()).isEmpty(); } - @Test - public void generatingPageWithOpenIdFilterOnlyIsSuccessFul() throws Exception { - DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new MockProcessingFilter()); - filter.doFilter(new MockHttpServletRequest("GET", "/login"), new MockHttpServletResponse(), this.chain); - } - /* SEC-1111 */ @Test public void handlesNonIso8859CharsInErrorMessage() throws Exception { @@ -178,25 +168,6 @@ public class DefaultLoginPageGeneratingFilterTests { assertThat(response.getContentAsString()).contains("Login with SAML 2.0"); assertThat(response.getContentAsString()) .contains("Google < > " ' &"); - } // Fake OpenID filter (since it's not in this module - - @SuppressWarnings("unused") - private static class MockProcessingFilter extends AbstractAuthenticationProcessingFilter { - - MockProcessingFilter() { - super("/someurl"); - } - - @Override - public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) - throws AuthenticationException { - return null; - } - - String getClaimedIdentityFieldName() { - return "unused"; - } - } }