Search in sources :

Example 6 with HttpServletResponse

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

the class OAuth2AuthorizedClientArgumentResolver method resolveArgument.

@NonNull
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) {
    String clientRegistrationId = this.resolveClientRegistrationId(parameter);
    if (StringUtils.isEmpty(clientRegistrationId)) {
        throw new IllegalArgumentException("Unable to resolve the Client Registration Identifier. " + "It must be provided via @RegisteredOAuth2AuthorizedClient(\"client1\") or " + "@RegisteredOAuth2AuthorizedClient(registrationId = \"client1\").");
    }
    Authentication principal = SecurityContextHolder.getContext().getAuthentication();
    if (principal == null) {
        principal = ANONYMOUS_AUTHENTICATION;
    }
    HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
    HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
    // @formatter:off
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId).principal(principal).attribute(HttpServletRequest.class.getName(), servletRequest).attribute(HttpServletResponse.class.getName(), servletResponse).build();
    // @formatter:on
    return this.authorizedClientManager.authorize(authorizeRequest);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) NonNull(org.springframework.lang.NonNull)

Example 7 with HttpServletResponse

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunction method authorizeClient.

private Mono<OAuth2AuthorizedClient> authorizeClient(String clientRegistrationId, ClientRequest request) {
    if (this.authorizedClientManager == null) {
        return Mono.empty();
    }
    Map<String, Object> attrs = request.attributes();
    Authentication authentication = getAuthentication(attrs);
    if (authentication == null) {
        authentication = ANONYMOUS_AUTHENTICATION;
    }
    HttpServletRequest servletRequest = getRequest(attrs);
    HttpServletResponse servletResponse = getResponse(attrs);
    OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId).principal(authentication);
    builder.attributes((attributes) -> addToAttributes(attributes, servletRequest, servletResponse));
    OAuth2AuthorizeRequest authorizeRequest = builder.build();
    // blocking I/O operation using RestTemplate internally
    return Mono.fromSupplier(() -> this.authorizedClientManager.authorize(authorizeRequest)).subscribeOn(Schedulers.boundedElastic());
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest)

Example 8 with HttpServletResponse

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunction method removeAuthorizedClient.

private void removeAuthorizedClient(OAuth2AuthorizedClientRepository authorizedClientRepository, String clientRegistrationId, Authentication principal, Map<String, Object> attributes) {
    HttpServletRequest request = getRequest(attributes);
    HttpServletResponse response = getResponse(attributes);
    authorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal, request, response);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpServletResponse(jakarta.servlet.http.HttpServletResponse)

Example 9 with HttpServletResponse

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

the class Saml2LogoutResponseFilter method doFilterInternal.

/**
 * {@inheritDoc}
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    if (!this.logoutRequestMatcher.matches(request)) {
        chain.doFilter(request, response);
        return;
    }
    if (request.getParameter(Saml2ParameterNames.SAML_RESPONSE) == null) {
        chain.doFilter(request, response);
        return;
    }
    Saml2LogoutRequest logoutRequest = this.logoutRequestRepository.removeLogoutRequest(request, response);
    if (logoutRequest == null) {
        this.logger.trace("Did not process logout response since could not find associated LogoutRequest");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to find associated LogoutRequest");
        return;
    }
    RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, logoutRequest.getRelyingPartyRegistrationId());
    if (registration == null) {
        this.logger.trace("Did not process logout request since failed to find associated RelyingPartyRegistration");
        Saml2Error error = new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, "Failed to find associated RelyingPartyRegistration");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, error.toString());
        return;
    }
    if (registration.getSingleLogoutServiceResponseLocation() == null) {
        this.logger.trace("Did not process logout response since RelyingPartyRegistration has not been configured with a logout response endpoint");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
    if (!isCorrectBinding(request, registration)) {
        this.logger.trace("Did not process logout request since used incorrect binding");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
    String serialized = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
    Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration).samlResponse(serialized).relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE)).binding(registration.getSingleLogoutServiceBinding()).location(registration.getSingleLogoutServiceResponseLocation()).parameters((params) -> params.put(Saml2ParameterNames.SIG_ALG, request.getParameter(Saml2ParameterNames.SIG_ALG))).parameters((params) -> params.put(Saml2ParameterNames.SIGNATURE, request.getParameter(Saml2ParameterNames.SIGNATURE))).build();
    Saml2LogoutResponseValidatorParameters parameters = new Saml2LogoutResponseValidatorParameters(logoutResponse, logoutRequest, registration);
    Saml2LogoutValidatorResult result = this.logoutResponseValidator.validate(parameters);
    if (result.hasErrors()) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, result.getErrors().iterator().next().toString());
        this.logger.debug(LogMessage.format("Failed to validate LogoutResponse: %s", result.getErrors()));
        return;
    }
    this.logoutSuccessHandler.onLogoutSuccess(request, response, null);
}
Also used : RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) Saml2Error(org.springframework.security.saml2.core.Saml2Error) Saml2ErrorCodes(org.springframework.security.saml2.core.Saml2ErrorCodes) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) RelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver) FilterChain(jakarta.servlet.FilterChain) Saml2Error(org.springframework.security.saml2.core.Saml2Error) OncePerRequestFilter(org.springframework.web.filter.OncePerRequestFilter) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) Saml2LogoutResponse(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) Saml2LogoutResponseValidatorParameters(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponseValidatorParameters) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) Saml2MessageBinding(org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding) LogMessage(org.springframework.core.log.LogMessage) Saml2LogoutValidatorResult(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutValidatorResult) Saml2ParameterNames(org.springframework.security.saml2.core.Saml2ParameterNames) Saml2LogoutResponseValidator(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponseValidator) LogoutSuccessHandler(org.springframework.security.web.authentication.logout.LogoutSuccessHandler) Log(org.apache.commons.logging.Log) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) LogFactory(org.apache.commons.logging.LogFactory) Saml2LogoutRequest(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) Assert(org.springframework.util.Assert) Saml2LogoutValidatorResult(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutValidatorResult) Saml2LogoutResponseValidatorParameters(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponseValidatorParameters) Saml2LogoutRequest(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest) Saml2LogoutResponse(org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse)

Example 10 with HttpServletResponse

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

the class HttpSessionSecurityContextRepository method loadContext.

/**
 * Gets the security context for the current request (if available) and returns it.
 * <p>
 * If the session is null, the context object is null or the context object stored in
 * the session is not an instance of {@code SecurityContext}, a new context object
 * will be generated and returned.
 */
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
    HttpServletRequest request = requestResponseHolder.getRequest();
    HttpServletResponse response = requestResponseHolder.getResponse();
    HttpSession httpSession = request.getSession(false);
    SecurityContext context = readSecurityContextFromSession(httpSession);
    if (context == null) {
        context = generateNewContext();
        if (this.logger.isTraceEnabled()) {
            this.logger.trace(LogMessage.format("Created %s", context));
        }
    }
    SaveToSessionResponseWrapper wrappedResponse = new SaveToSessionResponseWrapper(response, request, httpSession != null, context);
    requestResponseHolder.setResponse(wrappedResponse);
    requestResponseHolder.setRequest(new SaveToSessionRequestWrapper(request, wrappedResponse));
    return context;
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpSession(jakarta.servlet.http.HttpSession) SecurityContext(org.springframework.security.core.context.SecurityContext) HttpServletResponse(jakarta.servlet.http.HttpServletResponse)

Aggregations

HttpServletResponse (jakarta.servlet.http.HttpServletResponse)118 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)76 Test (org.junit.jupiter.api.Test)47 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)34 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)31 FilterChain (jakarta.servlet.FilterChain)22 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)18 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)16 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)15 ServletException (jakarta.servlet.ServletException)14 StandardCharsets (java.nio.charset.StandardCharsets)14 HttpServlet (jakarta.servlet.http.HttpServlet)13 IOException (java.io.IOException)12 HashMap (java.util.HashMap)12 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)10 Test (org.junit.Test)10 Authentication (org.springframework.security.core.Authentication)10 FileCopyUtils (org.springframework.util.FileCopyUtils)9 BeforeEach (org.junit.jupiter.api.BeforeEach)8 Collections (java.util.Collections)7