Search in sources :

Example 1 with UserInfo

use of com.nimbusds.openid.connect.sdk.claims.UserInfo in project di-authentication-api by alphagov.

the class UserInfoHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        LOG.info("Request received to the UserInfoHandler");
        if (!headersContainValidHeader(input.getHeaders(), AUTHORIZATION_HEADER, configurationService.getHeadersCaseInsensitive())) {
            LOG.warn("AccessToken is missing from request");
            return generateApiGatewayProxyResponse(401, "", new UserInfoErrorResponse(MISSING_TOKEN).toHTTPResponse().getHeaderMap());
        }
        UserInfo userInfo;
        try {
            AccessTokenInfo accessTokenInfo = accessTokenService.parse(getHeaderValueFromHeaders(input.getHeaders(), AUTHORIZATION_HEADER, configurationService.getHeadersCaseInsensitive()), false);
            userInfo = userInfoService.populateUserInfo(accessTokenInfo);
        } catch (AccessTokenException e) {
            LOG.warn("AccessTokenException. Sending back UserInfoErrorResponse");
            return generateApiGatewayProxyResponse(401, "", new UserInfoErrorResponse(e.getError()).toHTTPResponse().getHeaderMap());
        }
        LOG.info("Successfully processed UserInfo request. Sending back UserInfo response");
        return generateApiGatewayProxyResponse(200, userInfo.toJSONString());
    });
}
Also used : AccessTokenInfo(uk.gov.di.authentication.oidc.entity.AccessTokenInfo) UserInfoErrorResponse(com.nimbusds.openid.connect.sdk.UserInfoErrorResponse) AccessTokenException(uk.gov.di.authentication.shared.exceptions.AccessTokenException) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo)

Example 2 with UserInfo

use of com.nimbusds.openid.connect.sdk.claims.UserInfo in project di-authentication-api by alphagov.

the class UserInfoServiceTest method shouldPopulateUserInfo.

@Test
void shouldPopulateUserInfo() {
    when(authenticationService.getUserProfileFromSubject(INTERNAL_SUBJECT.getValue())).thenReturn(generateUserprofile());
    AccessTokenStore accessTokenStore = new AccessTokenStore(accessToken.getValue(), INTERNAL_SUBJECT.getValue());
    AccessTokenInfo accessTokenInfo = new AccessTokenInfo(accessTokenStore, SUBJECT.getValue(), SCOPES);
    UserInfo userInfo = userInfoService.populateUserInfo(accessTokenInfo);
    assertEquals(userInfo.getEmailAddress(), EMAIL);
    assertEquals(userInfo.getEmailVerified(), true);
    assertEquals(userInfo.getPhoneNumber(), PHONE_NUMBER);
    assertEquals(userInfo.getPhoneNumberVerified(), true);
}
Also used : AccessTokenInfo(uk.gov.di.authentication.oidc.entity.AccessTokenInfo) AccessTokenStore(uk.gov.di.authentication.shared.entity.AccessTokenStore) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) Test(org.junit.jupiter.api.Test)

Example 3 with UserInfo

use of com.nimbusds.openid.connect.sdk.claims.UserInfo in project di-authentication-api by alphagov.

the class UserInfoIntegrationTest method shouldCallUserInfoWithAccessTokenAndReturn200.

@Test
public void shouldCallUserInfoWithAccessTokenAndReturn200() throws JsonProcessingException {
    Subject internalSubject = new Subject();
    Subject publicSubject = new Subject();
    LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(10);
    Date expiryDate = Date.from(localDateTime.atZone(ZoneId.of("UTC")).toInstant());
    List<String> scopes = new ArrayList<>();
    scopes.add("email");
    scopes.add("phone");
    scopes.add("openid");
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("scope", scopes).issuer("issuer-id").expirationTime(expiryDate).issueTime(Date.from(LocalDateTime.now().atZone(ZoneId.of("UTC")).toInstant())).claim("client_id", "client-id-one").subject(publicSubject.getValue()).jwtID(UUID.randomUUID().toString()).build();
    SignedJWT signedJWT = tokenSigner.signJwt(claimsSet);
    AccessToken accessToken = new BearerAccessToken(signedJWT.serialize());
    AccessTokenStore accessTokenStore = new AccessTokenStore(accessToken.getValue(), internalSubject.getValue());
    String accessTokenStoreString = new ObjectMapper().writeValueAsString(accessTokenStore);
    redis.addToRedis(ACCESS_TOKEN_PREFIX + CLIENT_ID + "." + publicSubject, accessTokenStoreString, 300L);
    setUpDynamo(internalSubject);
    var response = makeRequest(Optional.empty(), Map.of("Authorization", accessToken.toAuthorizationHeader()), Map.of());
    assertThat(response, hasStatus(200));
    UserInfo expectedUserInfoResponse = new UserInfo(publicSubject);
    expectedUserInfoResponse.setEmailAddress(TEST_EMAIL_ADDRESS);
    expectedUserInfoResponse.setEmailVerified(true);
    expectedUserInfoResponse.setPhoneNumber(FORMATTED_PHONE_NUMBER);
    expectedUserInfoResponse.setPhoneNumberVerified(true);
    assertThat(response.getBody(), equalTo(expectedUserInfoResponse.toJSONString()));
    assertNoAuditEventsReceived(auditTopic);
}
Also used : LocalDateTime(java.time.LocalDateTime) ArrayList(java.util.ArrayList) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) SignedJWT(com.nimbusds.jwt.SignedJWT) Subject(com.nimbusds.oauth2.sdk.id.Subject) Date(java.util.Date) AccessTokenStore(uk.gov.di.authentication.shared.entity.AccessTokenStore) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test) ApiGatewayHandlerIntegrationTest(uk.gov.di.authentication.sharedtest.basetest.ApiGatewayHandlerIntegrationTest)

Example 4 with UserInfo

use of com.nimbusds.openid.connect.sdk.claims.UserInfo in project dataverse by IQSS.

the class OIDCAuthProvider method getUserRecord.

/**
 * Receive user data from OIDC provider after authn/z has been successfull. (Callback view uses this)
 * Request a token and access the resource, parse output and return user details.
 * @param code The authz code sent from the provider
 * @param redirectUrl The redirect URL (some providers require this when fetching the access token, e. g. Google)
 * @return A user record containing all user details accessible for us
 * @throws IOException Thrown when communication with the provider fails
 * @throws OAuth2Exception Thrown when we cannot access the user details for some reason
 * @throws InterruptedException Thrown when the requests thread is failing
 * @throws ExecutionException Thrown when the requests thread is failing
 */
@Override
public OAuth2UserRecord getUserRecord(String code, String redirectUrl) throws IOException, OAuth2Exception, InterruptedException, ExecutionException {
    // Create grant object
    AuthorizationGrant codeGrant = new AuthorizationCodeGrant(new AuthorizationCode(code), URI.create(redirectUrl));
    // Get Access Token first
    Optional<BearerAccessToken> accessToken = getAccessToken(codeGrant);
    // Now retrieve User Info
    if (accessToken.isPresent()) {
        Optional<UserInfo> userInfo = getUserInfo(accessToken.get());
        // Construct our internal user representation
        if (userInfo.isPresent()) {
            return getUserRecord(userInfo.get());
        }
    }
    // this should never happen, as we are throwing exceptions like champs before.
    throw new OAuth2Exception(-1, "", "auth.providers.token.failGetUser");
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) OAuth2Exception(edu.harvard.iq.dataverse.authorization.providers.oauth2.OAuth2Exception)

Example 5 with UserInfo

use of com.nimbusds.openid.connect.sdk.claims.UserInfo in project di-authentication-api by alphagov.

the class UserInfoService method populateUserInfo.

public UserInfo populateUserInfo(AccessTokenInfo accessTokenInfo, boolean identityEnabled) {
    LOG.info("Populating UserInfo");
    var userInfo = new UserInfo(new Subject(accessTokenInfo.getSubject()));
    if (accessTokenInfo.getScopes().contains(CustomScopeValue.DOC_CHECKING_APP.getValue())) {
        return populateDocAppUserInfo(accessTokenInfo, userInfo);
    }
    var userProfile = authenticationService.getUserProfileFromSubject(accessTokenInfo.getAccessTokenStore().getInternalSubjectId());
    if (accessTokenInfo.getScopes().contains(OIDCScopeValue.EMAIL.getValue())) {
        userInfo.setEmailAddress(userProfile.getEmail());
        userInfo.setEmailVerified(userProfile.isEmailVerified());
    }
    if (accessTokenInfo.getScopes().contains(OIDCScopeValue.PHONE.getValue())) {
        userInfo.setPhoneNumber(userProfile.getPhoneNumber());
        userInfo.setPhoneNumberVerified(userProfile.isPhoneNumberVerified());
    }
    if (accessTokenInfo.getScopes().contains(CustomScopeValue.GOVUK_ACCOUNT.getValue())) {
        userInfo.setClaim("legacy_subject_id", userProfile.getLegacySubjectID());
    }
    if (identityEnabled && Objects.nonNull(accessTokenInfo.getIdentityClaims())) {
        return populateIdentityInfo(accessTokenInfo, userInfo);
    } else {
        LOG.info("No identity claims present");
        return userInfo;
    }
}
Also used : UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) Subject(com.nimbusds.oauth2.sdk.id.Subject)

Aggregations

UserInfo (com.nimbusds.openid.connect.sdk.claims.UserInfo)18 Test (org.junit.jupiter.api.Test)5 Subject (com.nimbusds.oauth2.sdk.id.Subject)3 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)3 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)3 UserInfoResponse (com.nimbusds.openid.connect.sdk.UserInfoResponse)3 JSONObject (net.minidev.json.JSONObject)3 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)3 Test (org.testng.annotations.Test)3 OAuth2ServiceAbstractIntegrationTest (org.wso2.identity.integration.test.oauth2.OAuth2ServiceAbstractIntegrationTest)3 AccessTokenInfo (uk.gov.di.authentication.oidc.entity.AccessTokenInfo)3 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)2 UserInfoErrorResponse (com.nimbusds.openid.connect.sdk.UserInfoErrorResponse)2 AccessTokenStore (uk.gov.di.authentication.shared.entity.AccessTokenStore)2 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)1 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)1 User (com.authlete.common.types.User)1 Federation (com.authlete.jaxrs.server.federation.Federation)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 JWT (com.nimbusds.jwt.JWT)1