Search in sources :

Example 76 with RequestMatcher

use of org.springframework.security.web.util.matcher.RequestMatcher in project spring-security by spring-projects.

the class Saml2WebSsoAuthenticationFilterTests method doFilterWhenPathStartsWithRegistrationIdThenAuthenticates.

@Test
public void doFilterWhenPathStartsWithRegistrationIdThenAuthenticates() throws Exception {
    RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build();
    Authentication authentication = new TestingAuthenticationToken("user", "password");
    given(this.repository.findByRegistrationId("registration-id")).willReturn(registration);
    given(this.authenticationManager.authenticate(authentication)).willReturn(authentication);
    String loginProcessingUrl = "/{registrationId}/login/saml2/sso";
    RequestMatcher matcher = new AntPathRequestMatcher(loginProcessingUrl);
    DefaultRelyingPartyRegistrationResolver delegate = new DefaultRelyingPartyRegistrationResolver(this.repository);
    RelyingPartyRegistrationResolver resolver = (request, id) -> {
        String registrationId = matcher.matcher(request).getVariables().get("registrationId");
        return delegate.resolve(request, registrationId);
    };
    Saml2AuthenticationTokenConverter authenticationConverter = new Saml2AuthenticationTokenConverter(resolver);
    this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, loginProcessingUrl);
    this.filter.setAuthenticationManager(this.authenticationManager);
    this.request.setPathInfo("/registration-id/login/saml2/sso");
    this.request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response");
    this.filter.doFilter(this.request, this.response, new MockFilterChain());
    verify(this.repository).findByRegistrationId("registration-id");
}
Also used : RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) Saml2AuthenticationRequestRepository(org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) BeforeEach(org.junit.jupiter.api.BeforeEach) MockFilterChain(org.springframework.mock.web.MockFilterChain) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) RelyingPartyRegistrationRepository(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) Assertions.assertThatNoException(org.assertj.core.api.Assertions.assertThatNoException) BDDMockito.given(org.mockito.BDDMockito.given) AbstractSaml2AuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest) AuthenticationDetailsSource(org.springframework.security.authentication.AuthenticationDetailsSource) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) DefaultRelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.DefaultRelyingPartyRegistrationResolver) Saml2AuthenticationToken(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) RelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver) TestSaml2AuthenticationTokens(org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationTokens) Saml2AuthenticationTokenConverter(org.springframework.security.saml2.provider.service.web.Saml2AuthenticationTokenConverter) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Saml2ParameterNames(org.springframework.security.saml2.core.Saml2ParameterNames) Assertions(org.junit.jupiter.api.Assertions) AuthenticationConverter(org.springframework.security.web.authentication.AuthenticationConverter) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) Saml2AuthenticationException(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Authentication(org.springframework.security.core.Authentication) TestRelyingPartyRegistrations(org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) Mockito.mock(org.mockito.Mockito.mock) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) Saml2AuthenticationTokenConverter(org.springframework.security.saml2.provider.service.web.Saml2AuthenticationTokenConverter) Authentication(org.springframework.security.core.Authentication) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) DefaultRelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.DefaultRelyingPartyRegistrationResolver) DefaultRelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.DefaultRelyingPartyRegistrationResolver) RelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) MockFilterChain(org.springframework.mock.web.MockFilterChain) Test(org.junit.jupiter.api.Test)

Example 77 with RequestMatcher

use of org.springframework.security.web.util.matcher.RequestMatcher in project spring-security by spring-projects.

the class RequestMatcherDelegatingAuthorizationManager method check.

/**
 * Delegates to a specific {@link AuthorizationManager} based on a
 * {@link RequestMatcher} evaluation.
 * @param authentication the {@link Supplier} of the {@link Authentication} to check
 * @param request the {@link HttpServletRequest} to check
 * @return an {@link AuthorizationDecision}. If there is no {@link RequestMatcher}
 * matching the request, or the {@link AuthorizationManager} could not decide, then
 * null is returned
 */
@Override
public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) {
    if (this.logger.isTraceEnabled()) {
        this.logger.trace(LogMessage.format("Authorizing %s", request));
    }
    for (Map.Entry<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings.entrySet()) {
        RequestMatcher matcher = mapping.getKey();
        MatchResult matchResult = matcher.matcher(request);
        if (matchResult.isMatch()) {
            AuthorizationManager<RequestAuthorizationContext> manager = mapping.getValue();
            if (this.logger.isTraceEnabled()) {
                this.logger.trace(LogMessage.format("Checking authorization on %s using %s", request, manager));
            }
            return manager.check(authentication, new RequestAuthorizationContext(request, matchResult.getVariables()));
        }
    }
    this.logger.trace("Abstaining since did not find matching RequestMatcher");
    return null;
}
Also used : RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) AuthorizationManager(org.springframework.security.authorization.AuthorizationManager) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) MatchResult(org.springframework.security.web.util.matcher.RequestMatcher.MatchResult)

Example 78 with RequestMatcher

use of org.springframework.security.web.util.matcher.RequestMatcher in project spring-security by spring-projects.

the class DefaultFilterInvocationSecurityMetadataSource method getAttributes.

@Override
public Collection<ConfigAttribute> getAttributes(Object object) {
    final HttpServletRequest request = ((FilterInvocation) object).getRequest();
    int count = 0;
    for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : this.requestMap.entrySet()) {
        if (entry.getKey().matches(request)) {
            return entry.getValue();
        } else {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace(LogMessage.format("Did not match request to %s - %s (%d/%d)", entry.getKey(), entry.getValue(), ++count, this.requestMap.size()));
            }
        }
    }
    return null;
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) Collection(java.util.Collection) FilterInvocation(org.springframework.security.web.FilterInvocation) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 79 with RequestMatcher

use of org.springframework.security.web.util.matcher.RequestMatcher in project spring-security by spring-projects.

the class ExpressionBasedFilterInvocationSecurityMetadataSourceTests method expectedAttributeIsReturned.

@Test
public void expectedAttributeIsReturned() {
    final String expression = "hasRole('X')";
    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>();
    requestMap.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList(expression));
    ExpressionBasedFilterInvocationSecurityMetadataSource mds = new ExpressionBasedFilterInvocationSecurityMetadataSource(requestMap, new DefaultWebSecurityExpressionHandler());
    assertThat(mds.getAllConfigAttributes()).hasSize(1);
    Collection<ConfigAttribute> attrs = mds.getAttributes(new FilterInvocation("/path", "GET"));
    assertThat(attrs).hasSize(1);
    WebExpressionConfigAttribute attribute = (WebExpressionConfigAttribute) attrs.toArray()[0];
    assertThat(attribute.getAttribute()).isNull();
    assertThat(attribute.getAuthorizeExpression().getExpressionString()).isEqualTo(expression);
    assertThat(attribute.toString()).isEqualTo(expression);
}
Also used : AnyRequestMatcher(org.springframework.security.web.util.matcher.AnyRequestMatcher) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) ConfigAttribute(org.springframework.security.access.ConfigAttribute) Collection(java.util.Collection) FilterInvocation(org.springframework.security.web.FilterInvocation) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.jupiter.api.Test)

Example 80 with RequestMatcher

use of org.springframework.security.web.util.matcher.RequestMatcher in project spring-security by spring-projects.

the class DefaultFilterInvocationSecurityMetadataSourceTests method mixingPatternsWithAndWithoutHttpMethodsIsSupported.

// SEC-1236
@Test
public void mixingPatternsWithAndWithoutHttpMethodsIsSupported() {
    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>();
    Collection<ConfigAttribute> userAttrs = SecurityConfig.createList("A");
    requestMap.put(new AntPathRequestMatcher("/user/**", null), userAttrs);
    requestMap.put(new AntPathRequestMatcher("/teller/**", "GET"), SecurityConfig.createList("B"));
    this.fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
    FilterInvocation fi = createFilterInvocation("/user", null, null, "GET");
    Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi);
    assertThat(attrs).isEqualTo(userAttrs);
}
Also used : RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) ConfigAttribute(org.springframework.security.access.ConfigAttribute) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) Collection(java.util.Collection) FilterInvocation(org.springframework.security.web.FilterInvocation) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.jupiter.api.Test)

Aggregations

RequestMatcher (org.springframework.security.web.util.matcher.RequestMatcher)85 Test (org.junit.jupiter.api.Test)40 AntPathRequestMatcher (org.springframework.security.web.util.matcher.AntPathRequestMatcher)27 LinkedHashMap (java.util.LinkedHashMap)16 AndRequestMatcher (org.springframework.security.web.util.matcher.AndRequestMatcher)14 NegatedRequestMatcher (org.springframework.security.web.util.matcher.NegatedRequestMatcher)12 RequestHeaderRequestMatcher (org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher)12 ArrayList (java.util.ArrayList)11 AuthenticationEntryPoint (org.springframework.security.web.AuthenticationEntryPoint)10 OrRequestMatcher (org.springframework.security.web.util.matcher.OrRequestMatcher)10 MediaTypeRequestMatcher (org.springframework.security.web.util.matcher.MediaTypeRequestMatcher)9 Collection (java.util.Collection)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 ConfigAttribute (org.springframework.security.access.ConfigAttribute)7 AnyRequestMatcher (org.springframework.security.web.util.matcher.AnyRequestMatcher)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)6 DelegatingAuthenticationEntryPoint (org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint)6 ContentNegotiationStrategy (org.springframework.web.accept.ContentNegotiationStrategy)6 HeaderContentNegotiationStrategy (org.springframework.web.accept.HeaderContentNegotiationStrategy)6