Search in sources :

Example 6 with AuthorizationRequest

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

the class TokenHandlerTest method generateRequestObjectAuthRequest.

private static AuthorizationRequest generateRequestObjectAuthRequest() throws JOSEException {
    var keyPair = KeyPairHelper.GENERATE_RSA_KEY_PAIR();
    Scope scope = new Scope(DOC_CHECKING_APP, OIDCScopeValue.OPENID);
    var jwtClaimsSet = new JWTClaimsSet.Builder().audience(AUDIENCE).claim("redirect_uri", REDIRECT_URI).claim("response_type", ResponseType.CODE.toString()).claim("scope", scope.toString()).claim("client_id", DOC_APP_CLIENT_ID.getValue()).claim("state", STATE.getValue()).issuer(CLIENT_ID).build();
    var signedJWT = generateSignedJWT(jwtClaimsSet, keyPair);
    return generateAuthRequest(signedJWT);
}
Also used : Scope(com.nimbusds.oauth2.sdk.Scope)

Example 7 with AuthorizationRequest

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

the class TokenHandlerTest method shouldReturn200ForSuccessfulDocAppJourneyTokenRequest.

@Test
void shouldReturn200ForSuccessfulDocAppJourneyTokenRequest() throws JOSEException {
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    SignedJWT signedJWT = generateIDToken(DOC_APP_CLIENT_ID.getValue(), PUBLIC_SUBJECT, "issuer-url", new ECKeyGenerator(Curve.P_256).algorithm(JWSAlgorithm.ES256).generate());
    OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(signedJWT, accessToken, refreshToken));
    PrivateKeyJWT privateKeyJWT = generatePrivateKeyJWT(keyPair.getPrivate());
    ClientRegistry clientRegistry = generateClientRegistry(keyPair, false);
    when(tokenService.validateTokenRequestParams(anyString())).thenReturn(Optional.empty());
    when(clientService.getClient(DOC_APP_CLIENT_ID.getValue())).thenReturn(Optional.of(clientRegistry));
    when(tokenService.getClientIDFromPrivateKeyJWT(anyString())).thenReturn(Optional.of(DOC_APP_CLIENT_ID.getValue()));
    when(tokenService.validatePrivateKeyJWT(anyString(), eq(clientRegistry.getPublicKey()), eq(BASE_URI), eq(DOC_APP_CLIENT_ID.getValue()))).thenReturn(Optional.empty());
    String authCode = new AuthorizationCode().toString();
    AuthorizationRequest authenticationRequest = generateRequestObjectAuthRequest();
    VectorOfTrust vtr = VectorOfTrust.parseFromAuthRequestAttribute(authenticationRequest.getCustomParameter("vtr"));
    ClientSession clientSession = new ClientSession(authenticationRequest.toParameters(), LocalDateTime.now(), vtr);
    clientSession.setDocAppSubjectId(DOC_APP_USER_PUBLIC_SUBJECT);
    when(authorisationCodeService.getExchangeDataForCode(authCode)).thenReturn(Optional.of(new AuthCodeExchangeData().setEmail(TEST_EMAIL).setClientSessionId(CLIENT_SESSION_ID).setClientSession(clientSession)));
    when(dynamoService.getUserProfileByEmail(TEST_EMAIL)).thenReturn(userProfile);
    when(tokenService.generateTokenResponse(DOC_APP_CLIENT_ID.getValue(), DOC_APP_USER_PUBLIC_SUBJECT, new Scope(OIDCScopeValue.OPENID, DOC_CHECKING_APP), Map.of(), DOC_APP_USER_PUBLIC_SUBJECT, vtr.retrieveVectorOfTrustForToken(), null, false, null, true)).thenReturn(tokenResponse);
    APIGatewayProxyResponseEvent result = generateApiGatewayRequest(privateKeyJWT, authCode, DOC_APP_CLIENT_ID.getValue(), true);
    assertThat(result, hasStatus(200));
    assertTrue(result.getBody().contains(refreshToken.getValue()));
    assertTrue(result.getBody().contains(accessToken.getValue()));
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) KeyPair(java.security.KeyPair) AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) VectorOfTrust(uk.gov.di.authentication.shared.entity.VectorOfTrust) RequestObjectTestHelper.generateSignedJWT(uk.gov.di.authentication.oidc.helper.RequestObjectTestHelper.generateSignedJWT) SignedJWT(com.nimbusds.jwt.SignedJWT) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) AuthCodeExchangeData(uk.gov.di.authentication.shared.entity.AuthCodeExchangeData) Scope(com.nimbusds.oauth2.sdk.Scope) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 8 with AuthorizationRequest

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

the class UpdateProfileHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, UpdateProfileRequest request, UserContext userContext) {
    Session session = userContext.getSession();
    String persistentSessionId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
    LogLineHelper.attachSessionIdToLogs(session);
    attachLogFieldToLogs(PERSISTENT_SESSION_ID, persistentSessionId);
    LOG.info("Processing request");
    String ipAddress = IpAddressHelper.extractIpAddress(input);
    if (!session.validateSession(request.getEmail())) {
        LOG.info("Invalid session");
        return generateErrorResponse(ErrorResponse.ERROR_1000, context);
    }
    AuditableEvent auditableEvent;
    String auditablePhoneNumber = userContext.getUserProfile().map(UserProfile::getPhoneNumber).orElse(AuditService.UNKNOWN);
    String auditableClientId = userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN);
    switch(request.getUpdateProfileType()) {
        case ADD_PHONE_NUMBER:
            {
                String phoneNumber = PhoneNumberHelper.removeWhitespaceFromPhoneNumber(request.getProfileInformation());
                Optional<ErrorResponse> errorResponse = ValidationHelper.validatePhoneNumber(phoneNumber);
                if (errorResponse.isPresent()) {
                    return generateErrorResponse(errorResponse.get(), context);
                }
                authenticationService.updatePhoneNumber(request.getEmail(), request.getProfileInformation());
                auditableEvent = UPDATE_PROFILE_PHONE_NUMBER;
                auditablePhoneNumber = request.getProfileInformation();
                LOG.info("Phone number updated");
                break;
            }
        case CAPTURE_CONSENT:
            {
                ClientSession clientSession = userContext.getClientSession();
                if (clientSession == null) {
                    return generateErrorResponse(ErrorResponse.ERROR_1000, context);
                }
                AuthenticationRequest authorizationRequest;
                try {
                    authorizationRequest = AuthenticationRequest.parse(clientSession.getAuthRequestParams());
                } catch (ParseException e) {
                    LOG.info("Cannot retrieve auth request params from client session id");
                    return generateErrorResponse(ErrorResponse.ERROR_1001, context);
                }
                String clientId = authorizationRequest.getClientID().getValue();
                attachLogFieldToLogs(CLIENT_ID, clientId);
                Set<String> claimsConsented;
                if (!Boolean.parseBoolean(request.getProfileInformation())) {
                    claimsConsented = OIDCScopeValue.OPENID.getClaimNames();
                } else {
                    claimsConsented = ValidScopes.getClaimsForListOfScopes(authorizationRequest.getScope().toStringList());
                }
                processAndUpdateClientConsent(request.getEmail(), userContext, clientId, claimsConsented);
                auditableEvent = UPDATE_PROFILE_CONSENT_UPDATED;
                auditableClientId = clientId;
                LOG.info("Consent updated");
                break;
            }
        case UPDATE_TERMS_CONDS:
            {
                authenticationService.updateTermsAndConditions(request.getEmail(), configurationService.getTermsAndConditionsVersion());
                auditableEvent = UPDATE_PROFILE_TERMS_CONDS_ACCEPTANCE;
                LOG.info("Updated terms and conditions for Version: {}", configurationService.getTermsAndConditionsVersion());
                break;
            }
        default:
            LOG.error("Encountered unexpected error while processing session: {}", session.getSessionId());
            return generateErrorResponse(ErrorResponse.ERROR_1013, context);
    }
    auditService.submitAuditEvent(auditableEvent, context.getAwsRequestId(), session.getSessionId(), auditableClientId, userContext.getUserProfile().map(UserProfile::getSubjectID).orElse(AuditService.UNKNOWN), userContext.getSession().getEmailAddress(), ipAddress, auditablePhoneNumber, persistentSessionId);
    return generateEmptySuccessApiGatewayResponse();
}
Also used : Set(java.util.Set) Optional(java.util.Optional) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) Session(uk.gov.di.authentication.shared.entity.Session) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) AuditableEvent(uk.gov.di.authentication.shared.domain.AuditableEvent)

Example 9 with AuthorizationRequest

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

the class StartServiceTest method buildUserContext.

private UserContext buildUserContext(String vtrValue, boolean consentRequired, boolean cookieConsentShared, ClientType clientType, SignedJWT requestObject, boolean identityVerificationSupport, boolean isAuthenticated) {
    AuthorizationRequest authRequest;
    var clientSessionVTR = VectorOfTrust.getDefaults();
    if (Objects.nonNull(requestObject)) {
        authRequest = new AuthorizationRequest.Builder(new ResponseType(ResponseType.Value.CODE), CLIENT_ID).requestObject(requestObject).build();
    } else {
        clientSessionVTR = VectorOfTrust.parseFromAuthRequestAttribute(Collections.singletonList(vtrValue));
        authRequest = new AuthenticationRequest.Builder(new ResponseType(ResponseType.Value.CODE), SCOPES, CLIENT_ID, REDIRECT_URI).state(new State()).nonce(new Nonce()).customParameter("vtr", vtrValue).build();
    }
    var clientSession = new ClientSession(authRequest.toParameters(), LocalDateTime.now(), clientSessionVTR);
    var clientRegistry = new ClientRegistry().setClientID(CLIENT_ID.getValue()).setClientName(CLIENT_NAME).setConsentRequired(consentRequired).setCookieConsentShared(cookieConsentShared).setClientType(clientType.getValue()).setIdentityVerificationSupported(identityVerificationSupport);
    return UserContext.builder(SESSION.setAuthenticated(isAuthenticated)).withClientSession(clientSession).withClient(clientRegistry).build();
}
Also used : Nonce(com.nimbusds.openid.connect.sdk.Nonce) AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) State(com.nimbusds.oauth2.sdk.id.State) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 10 with AuthorizationRequest

use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project sandbox by backpaper0.

the class OAuth2Filter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) request;
    final HttpServletResponse resp = (HttpServletResponse) response;
    // OAuth 2.0のコールバック
    if (req.getRequestURI().equals("/oauth2/callback")) {
        try {
            doCallback(req, resp);
        } catch (IOException | ServletException e) {
            throw e;
        } catch (final Exception e) {
            throw new ServletException(e);
        }
        return;
    }
    // セッションにユーザーがあるならログイン済み
    final HttpSession session = req.getSession();
    final Object user = session.getAttribute("user");
    if (user != null) {
        chain.doFilter(request, response);
        return;
    }
    // 認可へ進む
    final State state = new State();
    final AuthorizationRequest authorizationRequest = new AuthorizationRequest.Builder(new ResponseType(ResponseType.Value.CODE), clientID).scope(new Scope(scope)).state(state).redirectionURI(callbackURI).endpointURI(authzURI).build();
    final URI requestURI = authorizationRequest.toURI();
    session.setAttribute(state.getValue(), req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : ""));
    resp.sendRedirect(requestURI.toString());
}
Also used : AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) URI(java.net.URI) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Scope(com.nimbusds.oauth2.sdk.Scope) State(com.nimbusds.oauth2.sdk.id.State) JSONObject(net.minidev.json.JSONObject)

Aggregations

AuthorizationRequest (com.nimbusds.oauth2.sdk.AuthorizationRequest)13 Scope (com.nimbusds.oauth2.sdk.Scope)9 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)7 URI (java.net.URI)6 OpenIDClient (oidc.model.OpenIDClient)6 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)5 State (com.nimbusds.oauth2.sdk.id.State)4 ParseException (com.nimbusds.oauth2.sdk.ParseException)3 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)3 Nonce (com.nimbusds.openid.connect.sdk.Nonce)3 Prompt (com.nimbusds.openid.connect.sdk.Prompt)3 Map (java.util.Map)3 ProvidedRedirectURI (oidc.model.ProvidedRedirectURI)3 OpenIDClientRepository (oidc.repository.OpenIDClientRepository)3 ClientSession (uk.gov.di.authentication.shared.entity.ClientSession)3 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)2 IOException (java.io.IOException)2 URISyntaxException (java.net.URISyntaxException)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2