Search in sources :

Example 6 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class UserInfoJWTResponse method getJWTSignatureAlgorithm.

private JWSAlgorithm getJWTSignatureAlgorithm() throws UserInfoEndpointException {
    JWSAlgorithm signatureAlgorithm = DEFAULT_SIGNATURE_ALGORITHM;
    String sigAlg = OAuthServerConfiguration.getInstance().getUserInfoJWTSignatureAlgorithm();
    if (isNotBlank(sigAlg)) {
        try {
            signatureAlgorithm = OAuth2Util.mapSignatureAlgorithmForJWSAlgorithm(sigAlg);
        } catch (IdentityOAuth2Exception e) {
            throw new UserInfoEndpointException("Provided signature algorithm : " + sigAlg + " is not supported.", e);
        }
    }
    return signatureAlgorithm;
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm)

Example 7 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class AbstractUserInfoResponseBuilder method filterOIDCClaims.

private Map<String, Object> filterOIDCClaims(OAuth2TokenValidationResponseDTO tokenResponse, String clientId, String spTenantDomain, Map<String, Object> userClaims) throws OAuthSystemException, UserInfoEndpointException {
    if (MapUtils.isEmpty(userClaims)) {
        if (log.isDebugEnabled()) {
            AuthenticatedUser authenticatedUser = getAuthenticatedUser(OAuth2Util.getAccessTokenIdentifier(tokenResponse));
            log.debug("No user claims available to be filtered for user: " + authenticatedUser.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
        }
        return new HashMap<>();
    }
    // Filter user claims based on the requested scopes
    Map<String, Object> userClaimsFilteredByScope = getUserClaimsFilteredByScope(tokenResponse, userClaims, tokenResponse.getScope(), clientId, spTenantDomain);
    // Handle essential claims
    Map<String, Object> essentialClaims = getEssentialClaims(tokenResponse, userClaims);
    userClaimsFilteredByScope.putAll(essentialClaims);
    // Handle essential claims of the request object
    Map<String, Object> filteredClaimsFromRequestObject = filterClaimsFromRequestObject(userClaims, OAuth2Util.getAccessTokenIdentifier(tokenResponse));
    userClaimsFilteredByScope.putAll(filteredClaimsFromRequestObject);
    // Filter the user claims based on user consent
    AuthenticatedUser authenticatedUser = getAuthenticatedUser(OAuth2Util.getAccessTokenIdentifier(tokenResponse));
    return getUserClaimsFilteredByConsent(tokenResponse, userClaimsFilteredByScope, authenticatedUser, clientId, spTenantDomain);
}
Also used : HashMap(java.util.HashMap) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 8 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class AbstractUserInfoResponseBuilder method getEssentialClaimUris.

private List<String> getEssentialClaimUris(OAuth2TokenValidationResponseDTO tokenResponse) throws UserInfoEndpointException {
    AuthorizationGrantCacheKey cacheKey = new AuthorizationGrantCacheKey(OAuth2Util.getAccessTokenIdentifier(tokenResponse));
    AuthorizationGrantCacheEntry cacheEntry = AuthorizationGrantCache.getInstance().getValueFromCacheByToken(cacheKey);
    if (cacheEntry != null) {
        if (isNotEmpty(cacheEntry.getEssentialClaims())) {
            return OAuth2Util.getEssentialClaims(cacheEntry.getEssentialClaims(), USERINFO);
        }
    }
    return new ArrayList<>();
}
Also used : AuthorizationGrantCacheEntry(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry) ArrayList(java.util.ArrayList) AuthorizationGrantCacheKey(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey)

Example 9 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class OpenIDConnectUserEndpoint method getUserClaims.

@GET
@Path("/")
@Consumes("application/x-www-form-urlencoded")
public Response getUserClaims(@Context HttpServletRequest request) throws OAuthSystemException {
    String userInfoResponse;
    String userInfoResponseContentType;
    try {
        // validate the request
        UserInfoRequestValidator requestValidator = UserInfoEndpointConfig.getInstance().getUserInfoRequestValidator();
        String accessToken = requestValidator.validateRequest(request);
        // validate the access token
        UserInfoAccessTokenValidator tokenValidator = UserInfoEndpointConfig.getInstance().getUserInfoAccessTokenValidator();
        OAuth2TokenValidationResponseDTO tokenResponse = tokenValidator.validateToken(accessToken, request);
        // build the claims
        // ToDO - Validate the grant type to be implicit or authorization_code before retrieving claims
        UserInfoResponseBuilder userInfoResponseBuilder = UserInfoEndpointConfig.getInstance().getUserInfoResponseBuilder();
        userInfoResponse = userInfoResponseBuilder.getResponseString(tokenResponse);
        userInfoResponseContentType = getUserInfoResponseMediaType(userInfoResponseBuilder);
    } catch (UserInfoEndpointException e) {
        return handleError(e);
    } catch (OAuthSystemException e) {
        log.error("UserInfoEndpoint Failed", e);
        throw new OAuthSystemException("UserInfoEndpoint Failed");
    }
    ResponseBuilder respBuilder = getResponseBuilderWithCacheControlHeaders();
    if (userInfoResponse != null) {
        return respBuilder.type(userInfoResponseContentType).entity(userInfoResponse).build();
    }
    return respBuilder.build();
}
Also used : UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) UserInfoRequestValidator(org.wso2.carbon.identity.oauth.user.UserInfoRequestValidator) UserInfoResponseBuilder(org.wso2.carbon.identity.oauth.user.UserInfoResponseBuilder) UserInfoResponseBuilder(org.wso2.carbon.identity.oauth.user.UserInfoResponseBuilder) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) UserInfoAccessTokenValidator(org.wso2.carbon.identity.oauth.user.UserInfoAccessTokenValidator) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) GET(javax.ws.rs.GET)

Example 10 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class ClaimUtil method getClaimsFromUserStore.

public static Map<String, Object> getClaimsFromUserStore(OAuth2TokenValidationResponseDTO tokenResponse) throws UserInfoEndpointException {
    try {
        String userId;
        String userTenantDomain;
        UserRealm realm;
        List<String> claimURIList = new ArrayList<>();
        Map<String, Object> mappedAppClaims = new HashMap<>();
        String subjectClaimValue = null;
        try {
            AccessTokenDO accessTokenDO = OAuth2Util.getAccessTokenDOfromTokenIdentifier(OAuth2Util.getAccessTokenIdentifier(tokenResponse));
            userId = accessTokenDO.getAuthzUser().getUserId();
            userTenantDomain = accessTokenDO.getAuthzUser().getTenantDomain();
            // retrieve claims from local userstore.
            if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal()) {
                AuthenticatedUser authenticatedUser = accessTokenDO.getAuthzUser();
                if (isNotEmpty(authenticatedUser.getUserStoreDomain())) {
                    String userstoreDomain = authenticatedUser.getUserStoreDomain();
                    if (OAuth2Util.isFederatedUser(authenticatedUser)) {
                        return handleClaimsForFederatedUser(tokenResponse, mappedAppClaims, userstoreDomain);
                    }
                }
            }
            Map<String, String> spToLocalClaimMappings;
            String clientId = getClientID(accessTokenDO);
            OAuthAppDO oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId);
            String spTenantDomain = OAuth2Util.getTenantDomainOfOauthApp(oAuthAppDO);
            ServiceProvider serviceProvider = getServiceProvider(clientId, spTenantDomain);
            ClaimMapping[] requestedLocalClaimMappings = serviceProvider.getClaimConfig().getClaimMappings();
            String subjectClaimURI = getSubjectClaimUri(serviceProvider, requestedLocalClaimMappings);
            if (subjectClaimURI != null) {
                claimURIList.add(subjectClaimURI);
            }
            boolean isSubjectClaimInRequested = false;
            if (subjectClaimURI != null || ArrayUtils.isNotEmpty(requestedLocalClaimMappings)) {
                if (requestedLocalClaimMappings != null) {
                    for (ClaimMapping claimMapping : requestedLocalClaimMappings) {
                        if (claimMapping.isRequested()) {
                            claimURIList.add(claimMapping.getLocalClaim().getClaimUri());
                            if (claimMapping.getLocalClaim().getClaimUri().equals(subjectClaimURI)) {
                                isSubjectClaimInRequested = true;
                            }
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Requested number of local claims: " + claimURIList.size());
                }
                spToLocalClaimMappings = ClaimMetadataHandler.getInstance().getMappingsMapFromOtherDialectToCarbon(SP_DIALECT, null, userTenantDomain, true);
                realm = getUserRealm(null, userTenantDomain);
                Map<String, String> userClaims = getUserClaimsFromUserStore(userId, realm, claimURIList);
                if (isNotEmpty(userClaims)) {
                    for (Map.Entry<String, String> entry : userClaims.entrySet()) {
                        // set local2sp role mappings
                        if (IdentityUtil.getRoleGroupClaims().stream().anyMatch(roleGroupClaimURI -> roleGroupClaimURI.equals(entry.getKey()))) {
                            String claimSeparator = getMultiAttributeSeparator(userId, realm);
                            entry.setValue(getSpMappedRoleClaim(serviceProvider, entry, claimSeparator));
                        }
                        String oidcClaimUri = spToLocalClaimMappings.get(entry.getKey());
                        if (oidcClaimUri != null) {
                            if (entry.getKey().equals(subjectClaimURI)) {
                                subjectClaimValue = entry.getValue();
                                if (!isSubjectClaimInRequested) {
                                    if (log.isDebugEnabled()) {
                                        log.debug("Subject claim: " + entry.getKey() + " is not a requested " + "claim. Not adding to claim map.");
                                    }
                                    continue;
                                }
                            }
                            mappedAppClaims.put(oidcClaimUri, entry.getValue());
                            if (log.isDebugEnabled() && isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                                log.debug("Mapped claim: key -  " + oidcClaimUri + " value -" + entry.getValue());
                            }
                        }
                    }
                }
            }
            if (StringUtils.isBlank(subjectClaimValue)) {
                if (log.isDebugEnabled()) {
                    log.debug("No subject claim found. Defaulting to username as the sub claim.");
                }
                subjectClaimValue = getUsernameFromTokenResponse(tokenResponse);
            }
            if (log.isDebugEnabled() && isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                log.debug("Subject claim(sub) value: " + subjectClaimValue + " set in returned claims.");
            }
            mappedAppClaims.put(OAuth2Util.SUB, subjectClaimValue);
        } catch (InvalidOAuthClientException e) {
            if (log.isDebugEnabled()) {
                log.debug(" Error while retrieving App information with provided client id.", e);
            }
            throw new IdentityOAuth2Exception(e.getMessage());
        } catch (Exception e) {
            String authorizedUserName = tokenResponse.getAuthorizedUser();
            if (e instanceof UserStoreException) {
                if (e.getMessage().contains("UserNotFound")) {
                    if (log.isDebugEnabled()) {
                        log.debug(StringUtils.isNotEmpty(authorizedUserName) ? "User with username: " + authorizedUserName + ", cannot be found in user store" : "User cannot " + "found in user store");
                    }
                }
            } else {
                String errMsg = StringUtils.isNotEmpty(authorizedUserName) ? "Error while retrieving the claims " + "from user store for the username: " + authorizedUserName : "Error while retrieving the " + "claims from user store";
                log.error(errMsg, e);
                throw new IdentityOAuth2Exception(errMsg);
            }
        }
        return mappedAppClaims;
    } catch (IdentityOAuth2Exception e) {
        throw new UserInfoEndpointException("Error while retrieving claims for user: " + tokenResponse.getAuthorizedUser(), e);
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) IdentityException(org.wso2.carbon.identity.base.IdentityException) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) UserRealm(org.wso2.carbon.user.core.UserRealm) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) UserStoreException(org.wso2.carbon.user.api.UserStoreException) HashMap(java.util.HashMap) Map(java.util.Map) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Aggregations

UserInfoEndpointException (org.wso2.carbon.identity.oauth.user.UserInfoEndpointException)11 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)5 HashMap (java.util.HashMap)3 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)3 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)3 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)3 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)3 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)2 ArrayList (java.util.ArrayList)2 Matchers.anyString (org.mockito.Matchers.anyString)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 BeforeTest (org.testng.annotations.BeforeTest)2 Test (org.testng.annotations.Test)2 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)2 ApplicationManagementService (org.wso2.carbon.identity.application.mgt.ApplicationManagementService)2 AuthorizationGrantCacheEntry (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry)2 AuthorizationGrantCacheKey (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey)2 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)2 OAuth2TokenValidationResponseDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO)2