Search in sources :

Example 11 with UserInfo

use of com.nimbusds.openid.connect.sdk.claims.UserInfo in project chipster-web-server by chipster.

the class OidcResource method checkUserInfo.

private void checkUserInfo(OidcConfig oidcConfig, String accessTokenString, String issuer, String clientId, String sub) {
    if (oidcConfig.getRequiredUserinfoClaimKey().isEmpty()) {
        if (this.isDebug) {
            logger.info("no required userinfo claims");
        }
        return;
    }
    if (accessTokenString == null) {
        throw new NotAuthorizedException("cannot check userinfo endpoint without an access token");
    }
    UserInfo userInfo = oidcProviders.getUserInfo(oidcConfig, accessTokenString, isDebug);
    Map<String, Object> userinfoClaims;
    try {
        userinfoClaims = userInfo.toJWTClaimsSet().getClaims();
    } catch (com.nimbusds.oauth2.sdk.ParseException e) {
        throw new InternalServerErrorException("parsing userinfo failed", e);
    }
    if (this.isDebug) {
        logger.info("claims from userinfo endpoint: ");
        for (String k : userinfoClaims.keySet()) {
            logger.info("claim " + k + ": " + userinfoClaims.get(k));
        }
    }
    if (!userInfo.getSubject().getValue().equals(sub)) {
        throw new InternalServerErrorException("id_token and userinfo subjects differ");
    }
    if (!hasRequiredClaim(oidcConfig.getOidcName(), oidcConfig.getRequiredUserinfoClaimKey(), oidcConfig.getRequiredUserinfoClaimValue(), oidcConfig.getRequiredUserinfoClaimValueComparison(), userinfoClaims)) {
        if (this.isDebug) {
            logger.info("access denied. Required userinfo claim not found: " + oidcConfig.getRequiredUserinfoClaimKey());
        }
        throw new ForbiddenException(oidcConfig.getRequiredUserinfoClaimError());
    }
}
Also used : ForbiddenException(jakarta.ws.rs.ForbiddenException) InternalServerErrorException(jakarta.ws.rs.InternalServerErrorException) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) NotAuthorizedException(jakarta.ws.rs.NotAuthorizedException)

Example 12 with UserInfo

use of com.nimbusds.openid.connect.sdk.claims.UserInfo in project java-oauth-server by authlete.

the class FederationEndpoint method callback.

@GET
@Path("callback/{federationId}")
public Response callback(@Context HttpServletRequest req, @PathParam("federationId") String federationId) {
    // Authentication response from the OpenID Provider.
    URI authenticationResponse = getFullUri(req);
    // Get the Federation instance that corresponds to the federation ID.
    Federation federation = getFederation(federationId);
    // Data used to render the authorization page.
    AuthzPageModel model = getAuthzPageModel(req);
    // "state" and "code_verifier" which were generated in initiation().
    String state = takeFromSession(req, KEY_STATE);
    String verifier = takeFromSession(req, KEY_VERIFIER);
    // Ensure that 'state' is available.
    ensureState(state);
    // Communicate with the OpenID Provider to get information about the user.
    UserInfo userInfo = getUserInfo(federation, authenticationResponse, state, verifier, model);
    // Register the user into this server (or overwrite the existing info).
    User user = registerUser(federation, userInfo);
    // Make the user login.
    makeUserLogin(req, user);
    // Go back to the authorization page.
    return authorizationPage(model, user, null);
}
Also used : User(com.authlete.common.types.User) Federation(com.authlete.jaxrs.server.federation.Federation) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) URI(java.net.URI) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 13 with UserInfo

use of com.nimbusds.openid.connect.sdk.claims.UserInfo in project java-oauth-server by authlete.

the class Federation method processFederationResponse.

/**
 * Process the authentication response from the authorization endpoint of
 * the OpenID Provider and retrieve user information from the userinfo
 * endpoint of the OpenID Provider.
 */
public UserInfo processFederationResponse(URI authenticationResponse, String state, String codeVerifier) throws IOException {
    // state
    State st = (state != null) ? new State(state) : null;
    // code_verifier
    CodeVerifier verifier = (codeVerifier != null) ? new CodeVerifier(codeVerifier) : null;
    // Extract the authorization code from the authentication response.
    AuthorizationCode authorizationCode = extractAuthorizationCode(authenticationResponse, st);
    // Send a token request to the token endpoint and receive a response.
    OIDCTokenResponse tokenResponse = makeTokenRequest(authorizationCode, verifier);
    // ID token issued from the token endpoint.
    JWT idToken = tokenResponse.getOIDCTokens().getIDToken();
    // Validate the ID token.
    IDTokenClaimsSet idTokenClaims = validateIdToken(idToken);
    // Access token issued from the token endpoint.
    AccessToken accessToken = tokenResponse.getOIDCTokens().getAccessToken();
    // Send a request to the userinfo endpoint and receive a response.
    UserInfo userInfo = makeUserInfoRequest(accessToken);
    // Validate the userinfo.
    validateUserInfo(userInfo, idTokenClaims.getSubject());
    // User information obtained from the OpenID Provider.
    return userInfo;
}
Also used : CodeVerifier(com.nimbusds.oauth2.sdk.pkce.CodeVerifier) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) State(com.nimbusds.oauth2.sdk.id.State) JWT(com.nimbusds.jwt.JWT) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)

Example 14 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) {
    LOG.info("Populating UserInfo");
    UserProfile userProfile = authenticationService.getUserProfileFromSubject(accessTokenInfo.getAccessTokenStore().getInternalSubjectId());
    UserInfo userInfo = new UserInfo(new Subject(accessTokenInfo.getPublicSubject()));
    if (accessTokenInfo.getScopes().contains("email")) {
        userInfo.setEmailAddress(userProfile.getEmail());
        userInfo.setEmailVerified(userProfile.isEmailVerified());
    }
    if (accessTokenInfo.getScopes().contains("phone")) {
        userInfo.setPhoneNumber(userProfile.getPhoneNumber());
        userInfo.setPhoneNumberVerified(userProfile.isPhoneNumberVerified());
    }
    if (accessTokenInfo.getScopes().contains("govuk-account")) {
        userInfo.setClaim("legacy_subject_id", userProfile.getLegacySubjectID());
    }
    return userInfo;
}
Also used : UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) Subject(com.nimbusds.oauth2.sdk.id.Subject)

Example 15 with UserInfo

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

the class IPVCallbackHandlerTest method shouldNotInvokeSPOTAndReturnAccessDeniedErrorToRPWhenP0.

@Test
void shouldNotInvokeSPOTAndReturnAccessDeniedErrorToRPWhenP0() {
    usingValidSession();
    usingValidClientSession();
    var userIdentityUserInfo = new UserInfo(new JSONObject(Map.of("sub", "sub-val", "vot", "P0", "vtm", OIDC_BASE_URL + "/trustmark")));
    var response = makeHandlerRequest(getApiGatewayProxyRequestEvent(userIdentityUserInfo));
    var expectedURI = new AuthenticationErrorResponse(URI.create(REDIRECT_URI.toString()), OAuth2Error.ACCESS_DENIED, RP_STATE, null).toURI().toString();
    assertThat(response, hasStatus(302));
    assertThat(response.getHeaders().get(ResponseHeaders.LOCATION), equalTo(expectedURI));
    verifyNoInteractions(dynamoIdentityService);
    verifyAuditEvent(IPVAuditableEvent.IPV_AUTHORISATION_RESPONSE_RECEIVED);
    verifyAuditEvent(IPVAuditableEvent.IPV_SUCCESSFUL_TOKEN_RESPONSE_RECEIVED);
    verifyAuditEvent(IPVAuditableEvent.IPV_SUCCESSFUL_IDENTITY_RESPONSE_RECEIVED);
    verifyNoInteractions(awsSqsClient);
}
Also used : AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) JSONObject(net.minidev.json.JSONObject) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

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