Search in sources :

Example 56 with HttpServletRequest

use of jakarta.servlet.http.HttpServletRequest in project spring-security by spring-projects.

the class CsrfTokenHandshakeInterceptor method beforeHandshake.

@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
    HttpServletRequest httpRequest = ((ServletServerHttpRequest) request).getServletRequest();
    CsrfToken token = (CsrfToken) httpRequest.getAttribute(CsrfToken.class.getName());
    if (token == null) {
        return true;
    }
    attributes.put(CsrfToken.class.getName(), token);
    return true;
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) CsrfToken(org.springframework.security.web.csrf.CsrfToken)

Example 57 with HttpServletRequest

use of jakarta.servlet.http.HttpServletRequest in project spring-security by spring-projects.

the class DefaultOAuth2AuthorizedClientManagerTests method authorizeWhenRequestParameterUsernamePasswordThenMappedToContext.

@Test
public void authorizeWhenRequestParameterUsernamePasswordThenMappedToContext() {
    given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))).willReturn(this.clientRegistration);
    given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(this.authorizedClient);
    // Set custom contextAttributesMapper
    this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
        Map<String, Object> contextAttributes = new HashMap<>();
        HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
        String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
        String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
            contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
        }
        return contextAttributes;
    });
    this.request.addParameter(OAuth2ParameterNames.USERNAME, "username");
    this.request.addParameter(OAuth2ParameterNames.PASSWORD, "password");
    // @formatter:off
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).attributes((attrs) -> {
        attrs.put(HttpServletRequest.class.getName(), this.request);
        attrs.put(HttpServletResponse.class.getName(), this.response);
    }).build();
    // @formatter:on
    this.authorizedClientManager.authorize(authorizeRequest);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    String username = authorizationContext.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME);
    assertThat(username).isEqualTo("username");
    String password = authorizationContext.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME);
    assertThat(password).isEqualTo("password");
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Authentication(org.springframework.security.core.Authentication) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) StringUtils(org.springframework.util.StringUtils) Mockito.mock(org.mockito.Mockito.mock) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) HashMap(java.util.HashMap) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) Test(org.junit.jupiter.api.Test)

Example 58 with HttpServletRequest

use of jakarta.servlet.http.HttpServletRequest in project spring-security by spring-projects.

the class DefaultOAuth2AuthorizedClientManagerTests method setup.

@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
    this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    this.authorizedClientProvider = mock(OAuth2AuthorizedClientProvider.class);
    this.contextAttributesMapper = mock(Function.class);
    this.authorizationSuccessHandler = spy(new OAuth2AuthorizationSuccessHandler() {

        @Override
        public void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal, Map<String, Object> attributes) {
            DefaultOAuth2AuthorizedClientManagerTests.this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, (HttpServletRequest) attributes.get(HttpServletRequest.class.getName()), (HttpServletResponse) attributes.get(HttpServletResponse.class.getName()));
        }
    });
    this.authorizationFailureHandler = spy(new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler((clientRegistrationId, principal, attributes) -> this.authorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal, (HttpServletRequest) attributes.get(HttpServletRequest.class.getName()), (HttpServletResponse) attributes.get(HttpServletResponse.class.getName()))));
    this.authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
    this.authorizedClientManager.setContextAttributesMapper(this.contextAttributesMapper);
    this.authorizedClientManager.setAuthorizationSuccessHandler(this.authorizationSuccessHandler);
    this.authorizedClientManager.setAuthorizationFailureHandler(this.authorizationFailureHandler);
    this.clientRegistration = TestClientRegistrations.clientRegistration().build();
    this.principal = new TestingAuthenticationToken("principal", "password");
    this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.scopes("read", "write"), TestOAuth2RefreshTokens.refreshToken());
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    this.authorizationContextCaptor = ArgumentCaptor.forClass(OAuth2AuthorizationContext.class);
}
Also used : OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Function(java.util.function.Function) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) HashMap(java.util.HashMap) Map(java.util.Map) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 59 with HttpServletRequest

use of jakarta.servlet.http.HttpServletRequest in project spring-security by spring-projects.

the class HttpSessionSecurityContextRepositoryTests method startAsyncRequestResponseDisablesSaveOnCommit.

@Test
public void startAsyncRequestResponseDisablesSaveOnCommit() throws Exception {
    HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
    HttpServletRequest request = mock(HttpServletRequest.class);
    MockHttpServletResponse response = new MockHttpServletResponse();
    HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
    repo.loadContext(holder);
    reset(request);
    holder.getRequest().startAsync(request, response);
    holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
    // ensure that sendError did cause interaction with the HttpSession
    verify(request, never()).getSession(anyBoolean());
    verify(request, never()).getSession();
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 60 with HttpServletRequest

use of jakarta.servlet.http.HttpServletRequest in project spring-security by spring-projects.

the class ConcurrentSessionFilterTests method doFilterWhenOverrideThenCustomRedirectStrategyUsed.

@Test
public void doFilterWhenOverrideThenCustomRedirectStrategyUsed() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpSession session = new MockHttpSession();
    request.setSession(session);
    MockHttpServletResponse response = new MockHttpServletResponse();
    RedirectStrategy redirect = mock(RedirectStrategy.class);
    SessionRegistry registry = mock(SessionRegistry.class);
    SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000));
    information.expireNow();
    given(registry.getSessionInformation(anyString())).willReturn(information);
    final String expiredUrl = "/expired";
    ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl + "will-be-overrridden") {

        @Override
        protected String determineExpiredUrl(HttpServletRequest request, SessionInformation info) {
            return expiredUrl;
        }
    };
    filter.setRedirectStrategy(redirect);
    filter.doFilter(request, response, new MockFilterChain());
    verify(redirect).sendRedirect(request, response, expiredUrl);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) SessionInformation(org.springframework.security.core.session.SessionInformation) SessionRegistry(org.springframework.security.core.session.SessionRegistry) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpSession(org.springframework.mock.web.MockHttpSession) ConcurrentSessionFilter(org.springframework.security.web.session.ConcurrentSessionFilter) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) RedirectStrategy(org.springframework.security.web.RedirectStrategy) MockFilterChain(org.springframework.mock.web.MockFilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Date(java.util.Date) Test(org.junit.jupiter.api.Test)

Aggregations

HttpServletRequest (jakarta.servlet.http.HttpServletRequest)289 Test (org.junit.jupiter.api.Test)160 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)93 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)88 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)67 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)44 Authentication (org.springframework.security.core.Authentication)31 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)31 Test (org.junit.Test)28 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)26 IOException (java.io.IOException)21 ServletException (jakarta.servlet.ServletException)20 HttpServlet (jakarta.servlet.http.HttpServlet)19 HashMap (java.util.HashMap)17 FilterDef (org.apache.tomcat.util.descriptor.web.FilterDef)16 FilterChain (jakarta.servlet.FilterChain)15 HttpSession (jakarta.servlet.http.HttpSession)14 MockFilterChain (org.springframework.mock.web.MockFilterChain)14 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)14 ServletRequest (jakarta.servlet.ServletRequest)13