Search in sources :

Example 6 with LoginUrlAuthenticationEntryPoint

use of org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint in project spring-security by spring-projects.

the class OAuth2LoginConfigurer method getLoginEntryPoint.

private AuthenticationEntryPoint getLoginEntryPoint(B http, String providerLoginPage) {
    RequestMatcher loginPageMatcher = new AntPathRequestMatcher(this.getLoginPage());
    RequestMatcher faviconMatcher = new AntPathRequestMatcher("/favicon.ico");
    RequestMatcher defaultEntryPointMatcher = this.getAuthenticationEntryPointMatcher(http);
    RequestMatcher defaultLoginPageMatcher = new AndRequestMatcher(new OrRequestMatcher(loginPageMatcher, faviconMatcher), defaultEntryPointMatcher);
    RequestMatcher notXRequestedWith = new NegatedRequestMatcher(new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"));
    LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
    entryPoints.put(new AndRequestMatcher(notXRequestedWith, new NegatedRequestMatcher(defaultLoginPageMatcher)), new LoginUrlAuthenticationEntryPoint(providerLoginPage));
    DelegatingAuthenticationEntryPoint loginEntryPoint = new DelegatingAuthenticationEntryPoint(entryPoints);
    loginEntryPoint.setDefaultEntryPoint(this.getAuthenticationEntryPoint());
    return loginEntryPoint;
}
Also used : NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) RequestHeaderRequestMatcher(org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) OrRequestMatcher(org.springframework.security.web.util.matcher.OrRequestMatcher) AndRequestMatcher(org.springframework.security.web.util.matcher.AndRequestMatcher) NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) DelegatingAuthenticationEntryPoint(org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint) AuthenticationEntryPoint(org.springframework.security.web.AuthenticationEntryPoint) RequestHeaderRequestMatcher(org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher) DelegatingAuthenticationEntryPoint(org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint) AndRequestMatcher(org.springframework.security.web.util.matcher.AndRequestMatcher) OrRequestMatcher(org.springframework.security.web.util.matcher.OrRequestMatcher) LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) LinkedHashMap(java.util.LinkedHashMap)

Example 7 with LoginUrlAuthenticationEntryPoint

use of org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint in project spring-security by spring-projects.

the class Saml2LoginConfigurer method init.

/**
 * {@inheritDoc}
 * <p>
 * Initializes this filter chain for SAML 2 Login. The following actions are taken:
 * <ul>
 * <li>The WebSSO endpoint has CSRF disabled, typically {@code /login/saml2/sso}</li>
 * <li>A {@link Saml2WebSsoAuthenticationFilter is configured}</li>
 * <li>The {@code loginProcessingUrl} is set</li>
 * <li>A custom login page is configured, <b>or</b></li>
 * <li>A default login page with all SAML 2.0 Identity Providers is configured</li>
 * <li>An {@link AuthenticationProvider} is configured</li>
 * </ul>
 */
@Override
public void init(B http) throws Exception {
    registerDefaultCsrfOverride(http);
    relyingPartyRegistrationRepository(http);
    this.saml2WebSsoAuthenticationFilter = new Saml2WebSsoAuthenticationFilter(getAuthenticationConverter(http), this.loginProcessingUrl);
    setAuthenticationRequestRepository(http, this.saml2WebSsoAuthenticationFilter);
    setAuthenticationFilter(this.saml2WebSsoAuthenticationFilter);
    super.loginProcessingUrl(this.loginProcessingUrl);
    if (StringUtils.hasText(this.loginPage)) {
        // Set custom login page
        super.loginPage(this.loginPage);
        super.init(http);
    } else {
        Map<String, String> providerUrlMap = getIdentityProviderUrlMap(this.authenticationRequestUri, this.relyingPartyRegistrationRepository);
        boolean singleProvider = providerUrlMap.size() == 1;
        if (singleProvider) {
            // Setup auto-redirect to provider login page
            // when only 1 IDP is configured
            this.updateAuthenticationDefaults();
            this.updateAccessDefaults(http);
            String loginUrl = providerUrlMap.entrySet().iterator().next().getKey();
            final LoginUrlAuthenticationEntryPoint entryPoint = new LoginUrlAuthenticationEntryPoint(loginUrl);
            registerAuthenticationEntryPoint(http, entryPoint);
        } else {
            super.init(http);
        }
    }
    this.initDefaultLoginFilter(http);
}
Also used : LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) Saml2WebSsoAuthenticationFilter(org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter)

Example 8 with LoginUrlAuthenticationEntryPoint

use of org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint in project spring-security by spring-projects.

the class AbstractAuthenticationFilterConfigurer method setLoginPage.

/**
 * Sets the loginPage and updates the {@link AuthenticationEntryPoint}.
 * @param loginPage
 */
private void setLoginPage(String loginPage) {
    this.loginPage = loginPage;
    this.authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint(loginPage);
}
Also used : LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint)

Example 9 with LoginUrlAuthenticationEntryPoint

use of org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint in project spring-security by spring-projects.

the class OAuth2LoginBeanDefinitionParser method parse.

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    // register magic bean
    BeanDefinition oauth2LoginBeanConfig = BeanDefinitionBuilder.rootBeanDefinition(OAuth2LoginBeanConfig.class).getBeanDefinition();
    String oauth2LoginBeanConfigId = parserContext.getReaderContext().generateBeanName(oauth2LoginBeanConfig);
    parserContext.registerBeanComponent(new BeanComponentDefinition(oauth2LoginBeanConfig, oauth2LoginBeanConfigId));
    // configure filter
    BeanMetadataElement clientRegistrationRepository = OAuth2ClientBeanDefinitionParserUtils.getClientRegistrationRepository(element);
    BeanMetadataElement authorizedClientRepository = OAuth2ClientBeanDefinitionParserUtils.getAuthorizedClientRepository(element);
    if (authorizedClientRepository == null) {
        BeanMetadataElement authorizedClientService = OAuth2ClientBeanDefinitionParserUtils.getAuthorizedClientService(element);
        this.defaultAuthorizedClientRepository = OAuth2ClientBeanDefinitionParserUtils.createDefaultAuthorizedClientRepository(clientRegistrationRepository, authorizedClientService);
        authorizedClientRepository = new RuntimeBeanReference(OAuth2AuthorizedClientRepository.class);
    }
    BeanMetadataElement accessTokenResponseClient = getAccessTokenResponseClient(element);
    BeanMetadataElement oauth2UserService = getOAuth2UserService(element);
    BeanMetadataElement authorizationRequestRepository = getAuthorizationRequestRepository(element);
    BeanDefinitionBuilder oauth2LoginAuthenticationFilterBuilder = BeanDefinitionBuilder.rootBeanDefinition(OAuth2LoginAuthenticationFilter.class).addConstructorArgValue(clientRegistrationRepository).addConstructorArgValue(authorizedClientRepository).addPropertyValue("authorizationRequestRepository", authorizationRequestRepository);
    if (this.sessionStrategy != null) {
        oauth2LoginAuthenticationFilterBuilder.addPropertyValue("sessionAuthenticationStrategy", this.sessionStrategy);
    }
    Object source = parserContext.extractSource(element);
    String loginProcessingUrl = element.getAttribute(ATT_LOGIN_PROCESSING_URL);
    if (!StringUtils.isEmpty(loginProcessingUrl)) {
        WebConfigUtils.validateHttpRedirect(loginProcessingUrl, parserContext, source);
        oauth2LoginAuthenticationFilterBuilder.addConstructorArgValue(loginProcessingUrl);
    } else {
        oauth2LoginAuthenticationFilterBuilder.addConstructorArgValue(OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI);
    }
    BeanDefinitionBuilder oauth2LoginAuthenticationProviderBuilder = BeanDefinitionBuilder.rootBeanDefinition(OAuth2LoginAuthenticationProvider.class).addConstructorArgValue(accessTokenResponseClient).addConstructorArgValue(oauth2UserService);
    String userAuthoritiesMapperRef = element.getAttribute(ATT_USER_AUTHORITIES_MAPPER_REF);
    if (!StringUtils.isEmpty(userAuthoritiesMapperRef)) {
        oauth2LoginAuthenticationProviderBuilder.addPropertyReference("authoritiesMapper", userAuthoritiesMapperRef);
    }
    this.oauth2LoginAuthenticationProvider = oauth2LoginAuthenticationProviderBuilder.getBeanDefinition();
    this.oauth2LoginOidcAuthenticationProvider = getOidcAuthProvider(element, accessTokenResponseClient, userAuthoritiesMapperRef);
    BeanDefinitionBuilder oauth2AuthorizationRequestRedirectFilterBuilder = BeanDefinitionBuilder.rootBeanDefinition(OAuth2AuthorizationRequestRedirectFilter.class);
    String authorizationRequestResolverRef = element.getAttribute(ATT_AUTHORIZATION_REQUEST_RESOLVER_REF);
    if (!StringUtils.isEmpty(authorizationRequestResolverRef)) {
        oauth2AuthorizationRequestRedirectFilterBuilder.addConstructorArgReference(authorizationRequestResolverRef);
    } else {
        oauth2AuthorizationRequestRedirectFilterBuilder.addConstructorArgValue(clientRegistrationRepository);
    }
    oauth2AuthorizationRequestRedirectFilterBuilder.addPropertyValue("authorizationRequestRepository", authorizationRequestRepository).addPropertyValue("requestCache", this.requestCache);
    this.oauth2AuthorizationRequestRedirectFilter = oauth2AuthorizationRequestRedirectFilterBuilder.getBeanDefinition();
    String authenticationSuccessHandlerRef = element.getAttribute(ATT_AUTHENTICATION_SUCCESS_HANDLER_REF);
    if (!StringUtils.isEmpty(authenticationSuccessHandlerRef)) {
        oauth2LoginAuthenticationFilterBuilder.addPropertyReference("authenticationSuccessHandler", authenticationSuccessHandlerRef);
    } else {
        BeanDefinitionBuilder successHandlerBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler").addPropertyValue("requestCache", this.requestCache);
        oauth2LoginAuthenticationFilterBuilder.addPropertyValue("authenticationSuccessHandler", successHandlerBuilder.getBeanDefinition());
    }
    String loginPage = element.getAttribute(ATT_LOGIN_PAGE);
    if (!StringUtils.isEmpty(loginPage)) {
        WebConfigUtils.validateHttpRedirect(loginPage, parserContext, source);
        this.oauth2LoginAuthenticationEntryPoint = BeanDefinitionBuilder.rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class).addConstructorArgValue(loginPage).addPropertyValue("portMapper", this.portMapper).addPropertyValue("portResolver", this.portResolver).getBeanDefinition();
    } else {
        Map<RequestMatcher, AuthenticationEntryPoint> entryPoint = getLoginEntryPoint(element);
        if (entryPoint != null) {
            this.oauth2LoginAuthenticationEntryPoint = BeanDefinitionBuilder.rootBeanDefinition(DelegatingAuthenticationEntryPoint.class).addConstructorArgValue(entryPoint).addPropertyValue("defaultEntryPoint", new LoginUrlAuthenticationEntryPoint(DEFAULT_LOGIN_URI)).getBeanDefinition();
        }
    }
    String authenticationFailureHandlerRef = element.getAttribute(ATT_AUTHENTICATION_FAILURE_HANDLER_REF);
    if (!StringUtils.isEmpty(authenticationFailureHandlerRef)) {
        oauth2LoginAuthenticationFilterBuilder.addPropertyReference("authenticationFailureHandler", authenticationFailureHandlerRef);
    } else {
        BeanDefinitionBuilder failureHandlerBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler");
        failureHandlerBuilder.addConstructorArgValue(DEFAULT_LOGIN_URI + "?" + DefaultLoginPageGeneratingFilter.ERROR_PARAMETER_NAME);
        failureHandlerBuilder.addPropertyValue("allowSessionCreation", this.allowSessionCreation);
        oauth2LoginAuthenticationFilterBuilder.addPropertyValue("authenticationFailureHandler", failureHandlerBuilder.getBeanDefinition());
    }
    // prepare loginlinks
    this.oauth2LoginLinks = BeanDefinitionBuilder.rootBeanDefinition(Map.class).setFactoryMethodOnBean("getLoginLinks", oauth2LoginBeanConfigId).getBeanDefinition();
    return oauth2LoginAuthenticationFilterBuilder.getBeanDefinition();
}
Also used : RequestHeaderRequestMatcher(org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) OrRequestMatcher(org.springframework.security.web.util.matcher.OrRequestMatcher) AndRequestMatcher(org.springframework.security.web.util.matcher.AndRequestMatcher) NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) MediaTypeRequestMatcher(org.springframework.security.web.util.matcher.MediaTypeRequestMatcher) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) BeanMetadataElement(org.springframework.beans.BeanMetadataElement) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) OAuth2LoginAuthenticationFilter(org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter) LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) DelegatingAuthenticationEntryPoint(org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint) AuthenticationEntryPoint(org.springframework.security.web.AuthenticationEntryPoint) BeanComponentDefinition(org.springframework.beans.factory.parsing.BeanComponentDefinition) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 10 with LoginUrlAuthenticationEntryPoint

use of org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint in project spring-security by spring-projects.

the class DefaultFilterChainValidator method checkLoginPageIsntProtected.

/*
	 * Checks for the common error of having a login page URL protected by the security
	 * interceptor
	 */
private void checkLoginPageIsntProtected(FilterChainProxy fcp, List<Filter> filterStack) {
    ExceptionTranslationFilter etf = getFilter(ExceptionTranslationFilter.class, filterStack);
    if (etf == null || !(etf.getAuthenticationEntryPoint() instanceof LoginUrlAuthenticationEntryPoint)) {
        return;
    }
    String loginPage = ((LoginUrlAuthenticationEntryPoint) etf.getAuthenticationEntryPoint()).getLoginFormUrl();
    this.logger.info("Checking whether login URL '" + loginPage + "' is accessible with your configuration");
    FilterInvocation loginRequest = new FilterInvocation(loginPage, "POST");
    List<Filter> filters = null;
    try {
        filters = fcp.getFilters(loginPage);
    } catch (Exception ex) {
        // May happen legitimately if a filter-chain request matcher requires more
        // request data than that provided
        // by the dummy request used when creating the filter invocation.
        this.logger.info("Failed to obtain filter chain information for the login page. Unable to complete check.");
    }
    if (filters == null || filters.isEmpty()) {
        this.logger.debug("Filter chain is empty for the login page");
        return;
    }
    if (getFilter(DefaultLoginPageGeneratingFilter.class, filters) != null) {
        this.logger.debug("Default generated login page is in use");
        return;
    }
    FilterSecurityInterceptor fsi = getFilter(FilterSecurityInterceptor.class, filters);
    FilterInvocationSecurityMetadataSource fids = fsi.getSecurityMetadataSource();
    Collection<ConfigAttribute> attributes = fids.getAttributes(loginRequest);
    if (attributes == null) {
        this.logger.debug("No access attributes defined for login page URL");
        if (fsi.isRejectPublicInvocations()) {
            this.logger.warn("FilterSecurityInterceptor is configured to reject public invocations." + " Your login page may not be accessible.");
        }
        return;
    }
    AnonymousAuthenticationFilter anonPF = getFilter(AnonymousAuthenticationFilter.class, filters);
    if (anonPF == null) {
        this.logger.warn("The login page is being protected by the filter chain, but you don't appear to have" + " anonymous authentication enabled. This is almost certainly an error.");
        return;
    }
    // Simulate an anonymous access with the supplied attributes.
    AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", anonPF.getPrincipal(), anonPF.getAuthorities());
    try {
        fsi.getAccessDecisionManager().decide(token, loginRequest, attributes);
    } catch (AccessDeniedException ex) {
        this.logger.warn("Anonymous access to the login page doesn't appear to be enabled. " + "This is almost certainly an error. Please check your configuration allows unauthenticated " + "access to the configured login page. (Simulated access was rejected: " + ex + ")");
    } catch (Exception ex) {
        // May happen legitimately if a filter-chain request matcher requires more
        // request data than that provided
        // by the dummy request used when creating the filter invocation. See SEC-1878
        this.logger.info("Unable to check access to the login page to determine if anonymous access is allowed. " + "This might be an error, but can happen under normal circumstances.", ex);
    }
}
Also used : DefaultLoginPageGeneratingFilter(org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ConfigAttribute(org.springframework.security.access.ConfigAttribute) FilterSecurityInterceptor(org.springframework.security.web.access.intercept.FilterSecurityInterceptor) ExceptionTranslationFilter(org.springframework.security.web.access.ExceptionTranslationFilter) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) FilterInvocationSecurityMetadataSource(org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource) AccessDeniedException(org.springframework.security.access.AccessDeniedException) SecurityContextPersistenceFilter(org.springframework.security.web.context.SecurityContextPersistenceFilter) Filter(jakarta.servlet.Filter) DefaultLoginPageGeneratingFilter(org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter) SessionManagementFilter(org.springframework.security.web.session.SessionManagementFilter) JaasApiIntegrationFilter(org.springframework.security.web.jaasapi.JaasApiIntegrationFilter) AnonymousAuthenticationFilter(org.springframework.security.web.authentication.AnonymousAuthenticationFilter) BasicAuthenticationFilter(org.springframework.security.web.authentication.www.BasicAuthenticationFilter) SecurityContextHolderAwareRequestFilter(org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter) ExceptionTranslationFilter(org.springframework.security.web.access.ExceptionTranslationFilter) UsernamePasswordAuthenticationFilter(org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter) AnonymousAuthenticationFilter(org.springframework.security.web.authentication.AnonymousAuthenticationFilter) FilterInvocation(org.springframework.security.web.FilterInvocation)

Aggregations

LoginUrlAuthenticationEntryPoint (org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint)12 AuthenticationEntryPoint (org.springframework.security.web.AuthenticationEntryPoint)4 AntPathRequestMatcher (org.springframework.security.web.util.matcher.AntPathRequestMatcher)4 RequestHeaderRequestMatcher (org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher)4 RequestMatcher (org.springframework.security.web.util.matcher.RequestMatcher)4 LinkedHashMap (java.util.LinkedHashMap)3 HttpSecurity (org.springframework.security.config.annotation.web.builders.HttpSecurity)3 DelegatingAuthenticationEntryPoint (org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint)3 AndRequestMatcher (org.springframework.security.web.util.matcher.AndRequestMatcher)3 MediaTypeRequestMatcher (org.springframework.security.web.util.matcher.MediaTypeRequestMatcher)3 NegatedRequestMatcher (org.springframework.security.web.util.matcher.NegatedRequestMatcher)3 OrRequestMatcher (org.springframework.security.web.util.matcher.OrRequestMatcher)3 Map (java.util.Map)2 BeanMetadataElement (org.springframework.beans.BeanMetadataElement)2 ExceptionTranslationFilter (org.springframework.security.web.access.ExceptionTranslationFilter)2 FilterSecurityInterceptor (org.springframework.security.web.access.intercept.FilterSecurityInterceptor)2 AnonymousAuthenticationFilter (org.springframework.security.web.authentication.AnonymousAuthenticationFilter)2 Route (com.vaadin.flow.router.Route)1 Filter (jakarta.servlet.Filter)1 HashMap (java.util.HashMap)1