Search in sources :

Example 46 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-ipv-cri-uk-passport-back by alphagov.

the class AuthorizationCodeHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    Map<String, List<String>> queryStringParameters = getQueryStringParametersAsMap(input);
    String userId = RequestHelper.getHeaderByKey(input.getHeaders(), "user_id");
    try {
        var validationResult = authRequestValidator.validateRequest(queryStringParameters, userId);
        if (validationResult.isPresent()) {
            return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_BAD_REQUEST, validationResult.get());
        }
        AuthenticationRequest authenticationRequest = AuthenticationRequest.parse(queryStringParameters);
        PassportAttributes passportAttributes = parsePassportFormRequest(input.getBody());
        JWSObject preparedDcsPayload = preparePayload(passportAttributes);
        DcsSignedEncryptedResponse dcsResponse = doPassportCheck(preparedDcsPayload);
        auditService.sendAuditEvent(AuditEventTypes.PASSPORT_REQUEST_SENT_TO_DCS);
        DcsResponse unwrappedDcsResponse = unwrapDcsResponse(dcsResponse);
        passportAttributes.setDcsResponse(unwrappedDcsResponse);
        validateDcsResponse(unwrappedDcsResponse);
        PassportCheckDao passportCheckDao = new PassportCheckDao(UUID.randomUUID().toString(), passportAttributes, generateGpg45Score(unwrappedDcsResponse), userId);
        passportService.persistDcsResponse(passportCheckDao);
        AuthorizationCode authorizationCode = authorizationCodeService.generateAuthorizationCode();
        authorizationCodeService.persistAuthorizationCode(authorizationCode.getValue(), passportCheckDao.getResourceId(), authenticationRequest.getRedirectionURI().toString());
        return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_OK, Map.of(AUTHORIZATION_CODE, authorizationCode));
    } catch (HttpResponseExceptionWithErrorBody e) {
        return ApiGatewayResponseGenerator.proxyJsonResponse(e.getStatusCode(), e.getErrorBody());
    } catch (ParseException e) {
        LOGGER.error("Authentication request could not be parsed", e);
        return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_BAD_REQUEST, ErrorResponse.FAILED_TO_PARSE_OAUTH_QUERY_STRING_PARAMETERS);
    } catch (SqsException e) {
        LOGGER.error("Failed to send audit event to SQS queue because: {}", e.getMessage());
        return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_BAD_REQUEST, ErrorResponse.FAILED_TO_SEND_AUDIT_MESSAGE_TO_SQS_QUEUE);
    }
}
Also used : DcsResponse(uk.gov.di.ipv.cri.passport.library.domain.DcsResponse) DcsSignedEncryptedResponse(uk.gov.di.ipv.cri.passport.library.domain.DcsSignedEncryptedResponse) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) HttpResponseExceptionWithErrorBody(uk.gov.di.ipv.cri.passport.library.exceptions.HttpResponseExceptionWithErrorBody) SqsException(uk.gov.di.ipv.cri.passport.library.exceptions.SqsException) PassportAttributes(uk.gov.di.ipv.cri.passport.library.domain.PassportAttributes) List(java.util.List) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) JWSObject(com.nimbusds.jose.JWSObject) PassportCheckDao(uk.gov.di.ipv.cri.passport.library.persistence.item.PassportCheckDao)

Example 47 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project OpenConext-oidcng by OpenConext.

the class AuthorizationEndpoint method doAuthorization.

private ModelAndView doAuthorization(MultiValueMap<String, String> parameters, OidcSamlAuthentication samlAuthentication, HttpServletRequest request, boolean consentRequired) throws ParseException, CertificateException, JOSEException, IOException, BadJOSEException, java.text.ParseException, URISyntaxException {
    AuthorizationRequest authenticationRequest = AuthorizationRequest.parse(parameters);
    Scope scope = authenticationRequest.getScope();
    boolean isOpenIdClient = scope != null && isOpenIDRequest(scope.toStringList());
    String clientId = authenticationRequest.getClientID().getValue();
    OpenIDClient client = openIDClientRepository.findOptionalByClientId(clientId).orElseThrow(() -> new UnknownClientException(clientId));
    MDCContext.mdcContext("action", "Authorize", "rp", client.getClientId());
    if (isOpenIdClient) {
        AuthenticationRequest oidcAuthenticationRequest = AuthenticationRequest.parse(parameters);
        if (oidcAuthenticationRequest.specifiesRequestObject()) {
            oidcAuthenticationRequest = JWTRequest.parse(oidcAuthenticationRequest, client);
            LOG.debug("/oidc/authorize with JWT 'request'");
        }
        // swap reference
        authenticationRequest = oidcAuthenticationRequest;
    }
    State state = authenticationRequest.getState();
    String redirectURI = validateRedirectionURI(authenticationRequest.getRedirectionURI(), client).getRedirectURI();
    List<String> scopes = validateScopes(openIDClientRepository, authenticationRequest.getScope(), client);
    ResponseType responseType = validateGrantType(authenticationRequest, client);
    User user = samlAuthentication.getUser();
    MDCContext.mdcContext(user);
    if (scope != null) {
        List<String> scopeList = scope.toStringList();
        boolean apiScopeRequested = !(scopeList.size() == 0 || (scopeList.size() == 1 && scopeList.contains("openid")));
        Set<String> filteredScopes = scopeList.stream().filter(s -> !s.equalsIgnoreCase("openid")).map(String::toLowerCase).collect(toSet());
        List<OpenIDClient> resourceServers = openIDClientRepository.findByScopes_NameIn(filteredScopes);
        Prompt prompt = authenticationRequest.getPrompt();
        boolean consentFromPrompt = prompt != null && prompt.toStringList().contains("consent");
        /*
             * We prompt for consent when the following conditions are met:
             *   Consent feature toggle is on
             *   The RP has requested scope(s) other then openid
             *   Manage attribute "oidc:consentRequired" is true for the RP or the RP has explicitly asked for consent
             *   There is at least one ResourceServer that has the requested scope(s) configured in manage
             */
        if (consentRequired && apiScopeRequested && (consentFromPrompt || client.isConsentRequired()) && resourceServers.size() > 0) {
            LOG.info("Asking for consent for User " + user + " and scopes " + scopes);
            return doConsent(parameters, client, filteredScopes, resourceServers);
        }
    }
    // We do not provide SSO as does EB not - up to the identity provider
    logout(request);
    ResponseMode responseMode = authenticationRequest.impliedResponseMode();
    if (responseType.impliesCodeFlow()) {
        AuthorizationCode authorizationCode = createAndSaveAuthorizationCode(authenticationRequest, client, user);
        LOG.debug(String.format("Returning authorizationCode flow %s %s", ResponseMode.FORM_POST, redirectURI));
        if (responseMode.equals(ResponseMode.FORM_POST)) {
            Map<String, String> body = new HashMap<>();
            body.put("redirect_uri", redirectURI);
            body.put("code", authorizationCode.getCode());
            if (state != null && StringUtils.hasText(state.getValue())) {
                body.put("state", state.getValue());
            }
            return new ModelAndView("form_post", body);
        }
        return new ModelAndView(new RedirectView(authorizationRedirect(redirectURI, state, authorizationCode.getCode(), responseMode.equals(ResponseMode.FRAGMENT))));
    } else if (responseType.impliesImplicitFlow() || responseType.impliesHybridFlow()) {
        if (responseType.impliesImplicitFlow()) {
            // User information is encrypted in access token
            LOG.debug("Deleting user " + user.getSub());
            userRepository.delete(user);
        }
        Map<String, Object> body = authorizationEndpointResponse(user, client, authenticationRequest, scopes, responseType, state);
        LOG.debug(String.format("Returning implicit flow %s %s", ResponseMode.FORM_POST, redirectURI));
        if (responseMode.equals(ResponseMode.FORM_POST)) {
            body.put("redirect_uri", redirectURI);
            return new ModelAndView("form_post", body);
        }
        if (responseMode.equals(ResponseMode.QUERY)) {
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectURI);
            body.forEach(builder::queryParam);
            return new ModelAndView(new RedirectView(builder.toUriString()));
        }
        if (responseMode.equals(ResponseMode.FRAGMENT)) {
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectURI);
            String fragment = body.entrySet().stream().map(entry -> String.format("%s=%s", entry.getKey(), entry.getValue())).collect(Collectors.joining("&"));
            builder.fragment(fragment);
            return new ModelAndView(new RedirectView(builder.toUriString()));
        }
        throw new IllegalArgumentException("Response mode " + responseMode + " not supported");
    }
    throw new IllegalArgumentException("Not yet implemented response_type: " + responseType.toString());
}
Also used : AuthorizationCode(oidc.model.AuthorizationCode) AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) User(oidc.model.User) UnknownClientException(oidc.exceptions.UnknownClientException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) OpenIDClient(oidc.model.OpenIDClient) ModelAndView(org.springframework.web.servlet.ModelAndView) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) Scope(com.nimbusds.oauth2.sdk.Scope) ResponseMode(com.nimbusds.oauth2.sdk.ResponseMode) State(com.nimbusds.oauth2.sdk.id.State) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RedirectView(org.springframework.web.servlet.view.RedirectView) Prompt(com.nimbusds.openid.connect.sdk.Prompt) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 48 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project OpenConext-oidcng by OpenConext.

the class OidcEndpoint method getClaims.

default List<String> getClaims(AuthorizationRequest authorizationRequest) {
    List<String> idTokenClaims = new ArrayList<>();
    if (isOpenIDRequest(authorizationRequest)) {
        AuthenticationRequest authenticationRequest = (AuthenticationRequest) authorizationRequest;
        ClaimsRequest claimsRequest = authenticationRequest.getClaims();
        if (claimsRequest != null) {
            idTokenClaims.addAll(claimsRequest.getIDTokenClaims().stream().map(entry -> entry.getClaimName()).collect(Collectors.toList()));
        }
    }
    return idTokenClaims;
}
Also used : ArrayList(java.util.ArrayList) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ClaimsRequest(com.nimbusds.openid.connect.sdk.ClaimsRequest)

Example 49 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project Application-Gateway by gianlucafrei.

the class LoginLogoutTest method testLoginGetRedirectUrl.

@Test
void testLoginGetRedirectUrl() throws Exception {
    // TWO Step test
    // ACT1: Start the login
    var loginResult = webClient.get().uri("/auth/local/login").exchange().expectStatus().isFound().returnResult(String.class);
    var redirectUriString = loginResult.getResponseHeaders().getFirst("Location");
    URI redirectUri = new URI(redirectUriString);
    AuthenticationRequest oidcRequest = AuthenticationRequest.parse(redirectUri);
    LoginProvider provider = mainConfig.getLoginProviders().get("local");
    assertTrue(redirectUriString.startsWith((String) provider.getWith().get("authEndpoint")));
    assertEquals(provider.getWith().get("clientId"), oidcRequest.getClientID().toString());
    var loginStateCookie = loginResult.getResponseCookies().getFirst(LoginStateCookie.NAME);
    // ACT 2: Call the callback url
    // Arrange
    String authorizationResponse = String.format("?state=%s&code=%s", oidcRequest.getState().getValue(), "authCode");
    var callbackResult = webClient.get().uri("/auth/local/callback" + authorizationResponse).cookie(loginStateCookie.getName(), loginStateCookie.getValue()).exchange().expectStatus().isFound().returnResult(String.class);
    var sessionCookie = callbackResult.getResponseCookies().getFirst(LoginCookie.NAME);
    var csrfCookie = callbackResult.getResponseCookies().getFirst(CsrfCookie.NAME);
    // ACT 3: Call the session endpoint
    webClient.get().uri("/auth/session").cookie(sessionCookie.getName(), sessionCookie.getValue()).exchange().expectStatus().isOk().expectBody().jsonPath("$.state").isEqualTo(SessionInformation.SESSION_STATE_AUTHENTICATED);
    // ACT 4: Logout
    var logoutResult = webClient.get().uri("/auth/logout").cookie(sessionCookie.getName(), sessionCookie.getValue()).cookie(csrfCookie.getName(), csrfCookie.getValue()).exchange().expectStatus().isFound().returnResult(String.class);
    // Expect that the cookie is deleted
    var sessionCookie2 = logoutResult.getResponseCookies().getFirst(LoginCookie.NAME);
    assertEquals(0, sessionCookie2.getMaxAge().getSeconds());
    assertEquals(sessionCookie.getName(), sessionCookie2.getName());
    assertEquals(sessionCookie.getPath(), sessionCookie2.getPath());
    assertEquals(sessionCookie.getDomain(), sessionCookie2.getDomain());
}
Also used : AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) LoginProvider(org.owasp.oag.config.configuration.LoginProvider) URI(java.net.URI) WiremockTest(org.owasp.oag.integration.testInfrastructure.WiremockTest) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 50 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project OpenConext-oidcng by OpenConext.

the class JWTRequestTest method parseWithRequestUrl.

@Test
public void parseWithRequestUrl() throws Exception {
    OpenIDClient client = getClient();
    String keyID = getCertificateKeyID(client);
    SignedJWT signedJWT = signedJWT(client.getClientId(), keyID, client.getRedirectUrls().get(0));
    stubFor(get(urlPathMatching("/request")).willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(signedJWT.serialize())));
    AuthenticationRequest authenticationRequest = new AuthenticationRequest.Builder(ResponseType.getDefault(), new Scope("openid"), new ClientID(client.getClientId()), new URI("http://localhost:8080")).requestURI(new URI("http://localhost:8089/request")).build();
    callParse(client, authenticationRequest);
}
Also used : Scope(com.nimbusds.oauth2.sdk.Scope) OpenIDClient(oidc.model.OpenIDClient) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) SignedJWT(com.nimbusds.jwt.SignedJWT) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) URI(java.net.URI) Test(org.junit.Test)

Aggregations

AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)73 Scope (com.nimbusds.oauth2.sdk.Scope)44 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)34 State (com.nimbusds.oauth2.sdk.id.State)29 Nonce (com.nimbusds.openid.connect.sdk.Nonce)27 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)24 Test (org.junit.jupiter.api.Test)19 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)16 URI (java.net.URI)16 ParseException (com.nimbusds.oauth2.sdk.ParseException)12 ClientSession (uk.gov.di.authentication.shared.entity.ClientSession)12 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)11 VectorOfTrust (uk.gov.di.authentication.shared.entity.VectorOfTrust)10 AuthenticationSuccessResponse (com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse)8 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)7 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)7 MethodSource (org.junit.jupiter.params.provider.MethodSource)6 SignedJWT (com.nimbusds.jwt.SignedJWT)5 OIDCClaimsRequest (com.nimbusds.openid.connect.sdk.OIDCClaimsRequest)5 HashMap (java.util.HashMap)5