Search in sources :

Example 1 with CookiesNotSupportedException

use of oidc.exceptions.CookiesNotSupportedException in project OpenConext-oidcng by OpenConext.

the class ErrorControllerTest method noCookies.

@Test
@SuppressWarnings("unchecked")
public void noCookies() throws URISyntaxException {
    ModelAndView modelAndView = (ModelAndView) doError(new CookiesNotSupportedException());
    assertEquals("no_session_found", modelAndView.getViewName());
}
Also used : CookiesNotSupportedException(oidc.exceptions.CookiesNotSupportedException) ModelAndView(org.springframework.web.servlet.ModelAndView) Test(org.junit.Test)

Example 2 with CookiesNotSupportedException

use of oidc.exceptions.CookiesNotSupportedException 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 3 with CookiesNotSupportedException

use of oidc.exceptions.CookiesNotSupportedException in project OpenConext-oidcng by OpenConext.

the class AuthnRequestConverter method convert.

@SneakyThrows
@Override
public AuthnRequest convert(Saml2AuthenticationRequestContext ctx) {
    CustomSaml2AuthenticationRequestContext context = (CustomSaml2AuthenticationRequestContext) ctx;
    HttpServletRequest request = context.getRequest();
    HttpSession session = request.getSession(false);
    if (session == null) {
        LOG.warn("There is no session in the HttpServletRequest. CookiesNotSupportedException will be thrown");
    } else {
        Enumeration<String> attributeNames = session.getAttributeNames();
        List<String> list = Collections.list(attributeNames);
        if (!list.contains("SPRING_SECURITY_SAVED_REQUEST")) {
            LOG.info("There is a session in the HttpServletRequest with ID " + session.getId() + " which does not contain a saved request. Attribute names are: " + list.toString());
        }
    }
    SavedRequest savedRequest = requestCache.getRequest(request, null);
    if (savedRequest == null) {
        throw new CookiesNotSupportedException();
    }
    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);
    AuthorizationRequest authorizationRequest = AuthorizationRequest.parse(parameters);
    validateAuthorizationRequest(authorizationRequest, openIDClient);
    RelyingPartyRegistration relyingParty = context.getRelyingPartyRegistration();
    AuthnRequestBuilder authnRequestBuilder = (AuthnRequestBuilder) registry.getBuilderFactory().getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    AuthnRequest authnRequest = authnRequestBuilder.buildObject();
    authnRequest.setID("ARQ" + UUID.randomUUID().toString().substring(1));
    authnRequest.setIssueInstant(Instant.now());
    authnRequest.setProtocolBinding(POST.getUrn());
    IssuerBuilder issuerBuilder = (IssuerBuilder) registry.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(relyingParty.getEntityId());
    authnRequest.setIssuer(issuer);
    authnRequest.setDestination(context.getDestination());
    authnRequest.setAssertionConsumerServiceURL(context.getAssertionConsumerServiceUrl());
    saveAuthenticationRequestUrl(savedRequest, authnRequest, authorizationRequest.getClientID());
    enhanceAuthenticationRequest(authnRequest, parameters);
    return authnRequest;
}
Also used : URLCoding(oidc.web.URLCoding) RequestCache(org.springframework.security.web.savedrequest.RequestCache) java.util(java.util) Prompt(com.nimbusds.openid.connect.sdk.Prompt) URLDecoder(java.net.URLDecoder) SneakyThrows(lombok.SneakyThrows) URISyntaxException(java.net.URISyntaxException) LocalDateTime(java.time.LocalDateTime) UnknownClientException(oidc.exceptions.UnknownClientException) org.opensaml.saml.saml2.core.impl(org.opensaml.saml.saml2.core.impl) XMLObjectProviderRegistry(org.opensaml.core.xml.config.XMLObjectProviderRegistry) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) HttpServletRequest(javax.servlet.http.HttpServletRequest) Charset(java.nio.charset.Charset) Saml2AuthenticationRequestContext(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext) ParseException(com.nimbusds.oauth2.sdk.ParseException) OpenIDClient(oidc.model.OpenIDClient) URI(java.net.URI) MDCContext(oidc.log.MDCContext) Converter(org.springframework.core.convert.converter.Converter) HttpSession(javax.servlet.http.HttpSession) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) JWTRequest(oidc.secure.JWTRequest) org.opensaml.saml.saml2.core(org.opensaml.saml.saml2.core) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) ConfigurationService(org.opensaml.core.config.ConfigurationService) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) POST(org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.POST) ZoneId(java.time.ZoneId) AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) AuthenticationRequestRepository(oidc.repository.AuthenticationRequestRepository) ServiceProviderTranslation(oidc.manage.ServiceProviderTranslation) Stream(java.util.stream.Stream) CookiesNotSupportedException(oidc.exceptions.CookiesNotSupportedException) CollectionUtils(org.springframework.util.CollectionUtils) OpenIDClientRepository(oidc.repository.OpenIDClientRepository) ACR(com.nimbusds.openid.connect.sdk.claims.ACR) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AuthorizationEndpoint(oidc.endpoints.AuthorizationEndpoint) StringUtils(org.springframework.util.StringUtils) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) UnknownClientException(oidc.exceptions.UnknownClientException) HttpSession(javax.servlet.http.HttpSession) OpenIDClient(oidc.model.OpenIDClient) URI(java.net.URI) HttpServletRequest(javax.servlet.http.HttpServletRequest) CookiesNotSupportedException(oidc.exceptions.CookiesNotSupportedException) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) SneakyThrows(lombok.SneakyThrows)

Aggregations

CookiesNotSupportedException (oidc.exceptions.CookiesNotSupportedException)3 SneakyThrows (lombok.SneakyThrows)2 ModelAndView (org.springframework.web.servlet.ModelAndView)2 JOSEException (com.nimbusds.jose.JOSEException)1 AuthorizationRequest (com.nimbusds.oauth2.sdk.AuthorizationRequest)1 ParseException (com.nimbusds.oauth2.sdk.ParseException)1 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)1 Prompt (com.nimbusds.openid.connect.sdk.Prompt)1 ACR (com.nimbusds.openid.connect.sdk.claims.ACR)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 URLDecoder (java.net.URLDecoder)1 Charset (java.nio.charset.Charset)1 Instant (java.time.Instant)1 LocalDateTime (java.time.LocalDateTime)1 ZoneId (java.time.ZoneId)1 java.util (java.util)1 Collectors (java.util.stream.Collectors)1 Stream (java.util.stream.Stream)1