Search in sources :

Example 41 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project obiba-commons by obiba.

the class OIDCCallbackFilter method validate.

private OIDCCredentials validate(J2EContext context, OIDCConfiguration config, AuthenticationSuccessResponse authResponse) {
    AuthorizationCode code = authResponse.getAuthorizationCode();
    ClientAuthentication clientAuthentication = new ClientSecretBasic(new ClientID(config.getClientId()), new Secret(config.getSecret()));
    try {
        // Token request
        final TokenRequest request = new TokenRequest(config.findProviderMetaData().getTokenEndpointURI(), clientAuthentication, new AuthorizationCodeGrant(code, new URI(callbackURL + config.getName())));
        HTTPRequest tokenHttpRequest = request.toHTTPRequest();
        tokenHttpRequest.setConnectTimeout(config.getConnectTimeout());
        tokenHttpRequest.setReadTimeout(config.getReadTimeout());
        final HTTPResponse httpResponse = tokenHttpRequest.send();
        log.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
        final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
        if (response instanceof TokenErrorResponse) {
            String error = ((TokenErrorResponse) response).getErrorObject().toJSONObject().toString();
            OIDCSession session = oidcSessionManager.getSession(context.getClientId());
            onAuthenticationError(session, error, context.getResponse());
            throw new OIDCSessionException("Bad token response, error=" + error, session);
        }
        log.debug("Token response successful");
        final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;
        final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens();
        if (config.isUseNonce()) {
            OIDCTokenValidator validator = new OIDCTokenValidator(config);
            OIDCSession session = oidcSessionManager.getSession(context.getClientId());
            IDTokenClaimsSet claimsSet = validator.validate(oidcTokens.getIDToken(), session.getNonce());
            if (claimsSet == null) {
                onAuthenticationError(session, "ID token cannot be validated", context.getResponse());
                throw new OIDCSessionException("ID token cannot be validated", session);
            }
        }
        // save tokens in credentials
        OIDCCredentials credentials = new OIDCCredentials();
        credentials.setAuthorizationCode(authResponse.getAuthorizationCode());
        credentials.setAccessToken(oidcTokens.getAccessToken());
        credentials.setRefreshToken(oidcTokens.getRefreshToken());
        credentials.setIdToken(oidcTokens.getIDToken());
        return credentials;
    } catch (Exception e) {
        throw new OIDCException(e);
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Secret(com.nimbusds.oauth2.sdk.auth.Secret) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) OIDCTokenValidator(org.obiba.oidc.utils.OIDCTokenValidator)

Example 42 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project di-authentication-api by alphagov.

the class TokenHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        LOG.info("Token request received");
        Optional<ErrorObject> invalidRequestParamError = tokenService.validateTokenRequestParams(input.getBody());
        if (invalidRequestParamError.isPresent()) {
            LOG.warn("Invalid Token Request. ErrorCode: {}. ErrorDescription: {}", invalidRequestParamError.get().getCode(), invalidRequestParamError.get().getDescription());
            return generateApiGatewayProxyResponse(400, invalidRequestParamError.get().toJSONObject().toJSONString());
        }
        Map<String, String> requestBody = parseRequestBody(input.getBody());
        String clientID = requestBody.get("client_id");
        ClientRegistry client;
        try {
            client = clientService.getClient(clientID).orElseThrow();
        } catch (NoSuchElementException e) {
            LOG.warn("Client not found in Client Registry with Client ID {}", clientID);
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_CLIENT.toJSONObject().toJSONString());
        }
        String baseUrl = configurationService.getBaseURL().orElseThrow(() -> {
            LOG.error("Application was not configured with baseURL");
            // exceptions
            return new RuntimeException("Application was not configured with baseURL");
        });
        String tokenUrl = buildURI(baseUrl, TOKEN_PATH).toString();
        Optional<ErrorObject> invalidPrivateKeyJwtError = tokenService.validatePrivateKeyJWT(input.getBody(), client.getPublicKey(), tokenUrl, clientID);
        if (invalidPrivateKeyJwtError.isPresent()) {
            LOG.warn("Private Key JWT is not valid for Client ID: {}", clientID);
            return generateApiGatewayProxyResponse(400, invalidPrivateKeyJwtError.get().toJSONObject().toJSONString());
        }
        if (requestBody.get("grant_type").equals(GrantType.REFRESH_TOKEN.getValue())) {
            LOG.info("Processing refresh token request");
            return processRefreshTokenRequest(requestBody, client.getScopes(), new RefreshToken(requestBody.get("refresh_token")));
        }
        AuthCodeExchangeData authCodeExchangeData;
        try {
            authCodeExchangeData = authorisationCodeService.getExchangeDataForCode(requestBody.get("code")).orElseThrow();
        } catch (NoSuchElementException e) {
            LOG.warn("Could not retrieve client session ID from code", e);
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
        }
        ClientSession clientSession = clientSessionService.getClientSession(authCodeExchangeData.getClientSessionId());
        AuthenticationRequest authRequest;
        try {
            authRequest = AuthenticationRequest.parse(clientSession.getAuthRequestParams());
        } catch (ParseException e) {
            LOG.warn("Could not parse authentication request from client session", e);
            throw new RuntimeException(format("Unable to parse Auth Request\n Auth Request Params: %s \n Exception: %s", clientSession.getAuthRequestParams(), e));
        }
        if (!authRequest.getRedirectionURI().toString().equals(requestBody.get("redirect_uri"))) {
            LOG.warn("Redirect URI for auth request ({}) does not match redirect URI for request body ({})", authRequest.getRedirectionURI(), requestBody.get("redirect_uri"));
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
        }
        UserProfile userProfile = dynamoService.getUserProfileByEmail(authCodeExchangeData.getEmail());
        Subject publicSubject = ClientSubjectHelper.getSubject(userProfile, client, dynamoService);
        Map<String, Object> additionalTokenClaims = new HashMap<>();
        if (authRequest.getNonce() != null) {
            additionalTokenClaims.put("nonce", authRequest.getNonce());
        }
        String vot = clientSession.getEffectiveVectorOfTrust().retrieveVectorOfTrustForToken();
        OIDCClaimsRequest claimsRequest = null;
        if (Objects.nonNull(clientSession.getEffectiveVectorOfTrust().getLevelOfConfidence()) && Objects.nonNull(authRequest.getOIDCClaims())) {
            claimsRequest = authRequest.getOIDCClaims();
        }
        var tokenResponse = tokenService.generateTokenResponse(clientID, new Subject(userProfile.getSubjectID()), authRequest.getScope(), additionalTokenClaims, publicSubject, vot, userProfile.getClientConsent(), client.isConsentRequired(), claimsRequest);
        clientSessionService.saveClientSession(authCodeExchangeData.getClientSessionId(), clientSession.setIdTokenHint(tokenResponse.getOIDCTokens().getIDToken().serialize()));
        LOG.info("Successfully generated tokens");
        return generateApiGatewayProxyResponse(200, tokenResponse.toJSONObject().toJSONString());
    });
}
Also used : UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) HashMap(java.util.HashMap) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Subject(com.nimbusds.oauth2.sdk.id.Subject) AuthCodeExchangeData(uk.gov.di.authentication.shared.entity.AuthCodeExchangeData) OIDCClaimsRequest(com.nimbusds.openid.connect.sdk.OIDCClaimsRequest) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) NoSuchElementException(java.util.NoSuchElementException)

Example 43 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project di-authentication-api by alphagov.

the class IPVCallbackHandlerTest method getApiGatewayProxyRequestEvent.

private APIGatewayProxyRequestEvent getApiGatewayProxyRequestEvent(UserInfo userIdentityUserInfo) {
    var successfulTokenResponse = new AccessTokenResponse(new Tokens(new BearerAccessToken(), null));
    var tokenRequest = mock(TokenRequest.class);
    Map<String, String> responseHeaders = new HashMap<>();
    responseHeaders.put("code", AUTH_CODE.getValue());
    responseHeaders.put("state", STATE.getValue());
    when(dynamoClientService.getClient(CLIENT_ID.getValue())).thenReturn(Optional.of(clientRegistry));
    when(responseService.validateResponse(responseHeaders, SESSION_ID)).thenReturn(Optional.empty());
    when(dynamoService.getUserProfileFromEmail(TEST_EMAIL_ADDRESS)).thenReturn(Optional.of(userProfile));
    when(dynamoService.getOrGenerateSalt(userProfile)).thenReturn(salt);
    when(ipvTokenService.constructTokenRequest(AUTH_CODE.getValue())).thenReturn(tokenRequest);
    when(ipvTokenService.sendTokenRequest(tokenRequest)).thenReturn(successfulTokenResponse);
    when(ipvTokenService.sendIpvUserIdentityRequest(ArgumentMatchers.any())).thenReturn(userIdentityUserInfo);
    var event = new APIGatewayProxyRequestEvent();
    event.setQueryStringParameters(responseHeaders);
    event.setHeaders(Map.of(COOKIE, buildCookieString()));
    return event;
}
Also used : APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) HashMap(java.util.HashMap) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Matchers.containsString(org.hamcrest.Matchers.containsString) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) Tokens(com.nimbusds.oauth2.sdk.token.Tokens)

Aggregations

URI (java.net.URI)18 OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)17 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)15 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)15 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)15 TokenResponse (com.nimbusds.oauth2.sdk.TokenResponse)14 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)13 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)13 Secret (com.nimbusds.oauth2.sdk.auth.Secret)12 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)12 Tokens (com.nimbusds.oauth2.sdk.token.Tokens)11 TokenErrorResponse (com.nimbusds.oauth2.sdk.TokenErrorResponse)10 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)10 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)10 IOException (java.io.IOException)10 AccessTokenResponse (com.nimbusds.oauth2.sdk.AccessTokenResponse)8 Scope (com.nimbusds.oauth2.sdk.Scope)8 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)8 HashMap (java.util.HashMap)8 Test (org.testng.annotations.Test)8