Search in sources :

Example 1 with ContextSaml2AuthenticationException

use of oidc.saml.ContextSaml2AuthenticationException in project OpenConext-oidcng by OpenConext.

the class ErrorController method error.

@SneakyThrows
@RequestMapping("${server.error.path:${error.path:/error}}")
public Object error(HttpServletRequest request) {
    ServletWebRequest webRequest = new ServletWebRequest(request);
    Map<String, Object> result = errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());
    Throwable error = errorAttributes.getError(webRequest);
    if (error instanceof CookiesNotSupportedException) {
        return new ModelAndView("no_session_found", HttpStatus.OK);
    }
    if (error != null && error.getCause() != null) {
        error = error.getCause();
    }
    boolean status = result.containsKey("status") && !result.get("status").equals(999) && !result.get("status").equals(500);
    HttpStatus statusCode = status ? HttpStatus.resolve((Integer) result.get("status")) : BAD_REQUEST;
    if (error != null) {
        String message = error.getMessage();
        // Not be considered an error that we want to report
        if (!"AccessToken not found".equals(message)) {
            LOG.error("Error has occurred", error);
        }
        result.put("error_description", message);
        result.put("message", message);
        ResponseStatus annotation = AnnotationUtils.getAnnotation(error.getClass(), ResponseStatus.class);
        statusCode = annotation != null ? annotation.value() : statusCode;
        if (error instanceof JOSEException || (error instanceof EmptyResultDataAccessException && result.getOrDefault("path", "/oidc/token").toString().contains("token"))) {
            return new ResponseEntity<>(Collections.singletonMap("error", "invalid_grant"), BAD_REQUEST);
        }
    }
    result.put("error", errorCode(error));
    result.put("status", statusCode.value());
    // https://openid.net/specs/openid-connect-core-1_0.html#AuthError
    Object redirectUriValid = request.getAttribute(REDIRECT_URI_VALID);
    String redirectUri = request.getParameter("redirect_uri");
    Map<String, String[]> parameterMap = request.getParameterMap();
    SavedRequest savedRequest = requestCache.getRequest(request, null);
    boolean redirect = false;
    if (error instanceof ContextSaml2AuthenticationException) {
        ContextSaml2AuthenticationException ctxE = (ContextSaml2AuthenticationException) error;
        String originalRequestUrl = ctxE.getAuthenticationRequest().getOriginalRequestUrl();
        UriComponents uriComponent = UriComponentsBuilder.fromUriString(originalRequestUrl).build();
        redirectUri = uriComponent.getQueryParams().getFirst("redirect_uri");
        redirect = true;
    } else if (savedRequest == null) {
        LOG.warn("No saved request found. Check the cookie flow");
    }
    if (savedRequest instanceof DefaultSavedRequest) {
        parameterMap = savedRequest.getParameterMap();
        String requestURI = ((DefaultSavedRequest) savedRequest).getRequestURI();
        String[] redirectUris = parameterMap.get("redirect_uri");
        if (requestURI != null && requestURI.contains("authorize") && redirectUris != null) {
            redirectUri = redirectUris[0];
            redirect = true;
        }
    }
    if (redirectUriValid != null && (boolean) redirectUriValid && (statusCode.is3xxRedirection() || redirect || StringUtils.hasText(redirectUri))) {
        return redirectErrorResponse(parameterMap, result, error, redirectUri);
    }
    return new ResponseEntity<>(result, statusCode);
}
Also used : HttpStatus(org.springframework.http.HttpStatus) ModelAndView(org.springframework.web.servlet.ModelAndView) ContextSaml2AuthenticationException(oidc.saml.ContextSaml2AuthenticationException) ResponseEntity(org.springframework.http.ResponseEntity) UriComponents(org.springframework.web.util.UriComponents) CookiesNotSupportedException(oidc.exceptions.CookiesNotSupportedException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) DefaultSavedRequest(org.springframework.security.web.savedrequest.DefaultSavedRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) JOSEException(com.nimbusds.jose.JOSEException) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) DefaultSavedRequest(org.springframework.security.web.savedrequest.DefaultSavedRequest) SneakyThrows(lombok.SneakyThrows) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with ContextSaml2AuthenticationException

use of oidc.saml.ContextSaml2AuthenticationException in project OpenConext-oidcng by OpenConext.

the class ErrorControllerTest method errorAuthorizationRequestContext.

@Test
@SuppressWarnings("unchecked")
public void errorAuthorizationRequestContext() throws URISyntaxException {
    String originalUrl = "http://localhost:9195/oidc/authorize?scope=openid&acr_values=https://eduid.nl/trust/affiliation-student&response_type=code&redirect_uri=https://oidc-playground.test2.surfconext.nl/redirect&state=example&prompt=login&nonce=example&client_id=playground_client&response_mode=query";
    ContextSaml2AuthenticationException exception = new ContextSaml2AuthenticationException(new AuthenticationRequest("id", new Date(), "client_id", originalUrl), "Error description");
    MockHttpServletRequest request = MockMvcRequestBuilders.get(new URI("http://localhost:8080/oidc/authorize?response_type=code&client_id=http@//mock-sp&scope=openid&redirect_uri=http://localhost:8080")).requestAttr("javax.servlet.error.exception", exception).buildRequest(null);
    request.setAttribute(REDIRECT_URI_VALID, true);
    ResponseEntity responseEntity = (ResponseEntity) subject.error(request);
    assertEquals(302, responseEntity.getStatusCodeValue());
    String location = responseEntity.getHeaders().getLocation().toString();
    assertEquals("https://oidc-playground.test2.surfconext.nl/redirect?error=access_denied&error_description=Error+description", location);
}
Also used : ContextSaml2AuthenticationException(oidc.saml.ContextSaml2AuthenticationException) ResponseEntity(org.springframework.http.ResponseEntity) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AuthenticationRequest(oidc.model.AuthenticationRequest) URI(java.net.URI) Date(java.util.Date) Test(org.junit.Test)

Example 3 with ContextSaml2AuthenticationException

use of oidc.saml.ContextSaml2AuthenticationException in project OpenConext-oidcng by OpenConext.

the class RedirectAuthenticationFailureHandlerTest method onAuthenticationFailureContextRequest.

@Test
void onAuthenticationFailureContextRequest() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    assertThrows(ContextSaml2AuthenticationException.class, () -> subject.onAuthenticationFailure(request, null, new ContextSaml2AuthenticationException(null, "Not ok")));
    assertEquals(true, request.getAttribute(REDIRECT_URI_VALID));
}
Also used : ContextSaml2AuthenticationException(oidc.saml.ContextSaml2AuthenticationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Test(org.junit.jupiter.api.Test)

Example 4 with ContextSaml2AuthenticationException

use of oidc.saml.ContextSaml2AuthenticationException in project OpenConext-oidcng by OpenConext.

the class RedirectAuthenticationFailureHandler method onAuthenticationFailure.

@SneakyThrows
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    HttpSession session = request.getSession(false);
    SavedRequest savedRequest = null;
    if (session != null) {
        savedRequest = (SavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
    }
    if (savedRequest == null) {
        savedRequest = requestCache.getRequest(request, response);
    }
    if (savedRequest != null) {
        Map<String, String[]> parameterMap = savedRequest.getParameterMap();
        Map<String, List<String>> parameters = parameterMap.keySet().stream().collect(Collectors.toMap(key -> key, key -> Arrays.asList(parameterMap.get(key))));
        List<String> redirectUris = parameters.get("redirect_uri");
        URI redirectURI = CollectionUtils.isEmpty(redirectUris) ? null : new URI(redirectUris.get(0));
        List<String> clientIds = parameters.get("client_id");
        String clientId = CollectionUtils.isEmpty(clientIds) ? null : clientIds.get(0);
        OpenIDClient openIDClient = openIDClientRepository.findOptionalByClientId(clientId).orElseThrow(() -> new UnknownClientException(clientId));
        AuthorizationEndpoint.validateRedirectionURI(redirectURI, openIDClient);
        request.setAttribute(REDIRECT_URI_VALID, true);
    } else if (exception instanceof ContextSaml2AuthenticationException) {
        request.setAttribute(REDIRECT_URI_VALID, true);
        throw exception;
    }
    /*
         * Will be picked up by the ErrorController. Do note that if the user has stepped up his account in eduID, then
         * the initial session is no longer around.
         */
    if (exception instanceof Saml2AuthenticationException) {
        throw new Saml2AuthenticationException(new Saml2Error(Saml2ErrorCodes.INTERNAL_VALIDATION_ERROR, "The requesting service has indicated that the authenticated user is required to have validated attributes. Your institution has not provided this."), "The requesting service has indicated that the authenticated user is required to have validated attributes. Your institution has not provided this.", exception);
    }
    throw exception;
}
Also used : RequestCache(org.springframework.security.web.savedrequest.RequestCache) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) ServletException(javax.servlet.ServletException) UnknownClientException(oidc.exceptions.UnknownClientException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Map(java.util.Map) AuthenticationException(org.springframework.security.core.AuthenticationException) OpenIDClient(oidc.model.OpenIDClient) URI(java.net.URI) Saml2ErrorCodes(org.springframework.security.saml2.core.Saml2ErrorCodes) HttpSession(javax.servlet.http.HttpSession) REDIRECT_URI_VALID(oidc.saml.AuthnRequestConverter.REDIRECT_URI_VALID) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) ContextSaml2AuthenticationException(oidc.saml.ContextSaml2AuthenticationException) Saml2Error(org.springframework.security.saml2.core.Saml2Error) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) List(java.util.List) AuthenticationRequest(oidc.model.AuthenticationRequest) CollectionUtils(org.springframework.util.CollectionUtils) OpenIDClientRepository(oidc.repository.OpenIDClientRepository) AuthenticationFailureHandler(org.springframework.security.web.authentication.AuthenticationFailureHandler) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) Saml2AuthenticationException(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException) AuthorizationEndpoint(oidc.endpoints.AuthorizationEndpoint) UnknownClientException(oidc.exceptions.UnknownClientException) HttpSession(javax.servlet.http.HttpSession) OpenIDClient(oidc.model.OpenIDClient) URI(java.net.URI) Saml2Error(org.springframework.security.saml2.core.Saml2Error) ContextSaml2AuthenticationException(oidc.saml.ContextSaml2AuthenticationException) ContextSaml2AuthenticationException(oidc.saml.ContextSaml2AuthenticationException) Saml2AuthenticationException(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException) List(java.util.List) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) SneakyThrows(lombok.SneakyThrows)

Aggregations

ContextSaml2AuthenticationException (oidc.saml.ContextSaml2AuthenticationException)4 URI (java.net.URI)2 SneakyThrows (lombok.SneakyThrows)2 AuthenticationRequest (oidc.model.AuthenticationRequest)2 ResponseEntity (org.springframework.http.ResponseEntity)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 SavedRequest (org.springframework.security.web.savedrequest.SavedRequest)2 JOSEException (com.nimbusds.jose.JOSEException)1 IOException (java.io.IOException)1 Arrays (java.util.Arrays)1 Date (java.util.Date)1 List (java.util.List)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpSession (javax.servlet.http.HttpSession)1 AuthorizationEndpoint (oidc.endpoints.AuthorizationEndpoint)1 CookiesNotSupportedException (oidc.exceptions.CookiesNotSupportedException)1