Search in sources :

Example 6 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.

the class PostAuthenticatedSubjectIdentifierHandler method handle.

@Override
public PostAuthnHandlerFlowStatus handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) {
    if (!FrameworkUtils.isStepBasedSequenceHandlerExecuted(context)) {
        return SUCCESS_COMPLETED;
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    String subjectClaimURI = sequenceConfig.getApplicationConfig().getSubjectClaimUri();
    String subjectValue = (String) context.getProperty(FrameworkConstants.SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE);
    try {
        if (StringUtils.isNotBlank(subjectClaimURI)) {
            if (subjectValue != null) {
                handleUserStoreAndTenantDomain(sequenceConfig, subjectValue);
            } else {
                log.warn("Subject claim could not be found. Defaulting to Name Identifier.");
                setAuthenticatedSubjectIdentifierBasedOnUserId(sequenceConfig);
            }
        } else {
            setAuthenticatedSubjectIdentifierBasedOnUserId(sequenceConfig);
        }
    } catch (UserIdNotFoundException e) {
        return UNSUCCESS_COMPLETED;
    }
    return SUCCESS_COMPLETED;
}
Also used : SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 7 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.

the class PostAuthnMissingClaimHandler method handlePostAuthenticationForMissingClaimsResponse.

protected void handlePostAuthenticationForMissingClaimsResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
    if (log.isDebugEnabled()) {
        log.debug("Starting to process the response with missing claims");
    }
    Map<String, String> claims = new HashMap<String, String>();
    Map<String, String> claimsForContext = new HashMap<String, String>();
    Map<String, String[]> requestParams = request.getParameterMap();
    boolean persistClaims = false;
    AuthenticatedUser user = context.getSequenceConfig().getAuthenticatedUser();
    Map<String, String> carbonToSPClaimMapping = new HashMap<>();
    Object spToCarbonClaimMappingObject = context.getProperty(FrameworkConstants.SP_TO_CARBON_CLAIM_MAPPING);
    if (spToCarbonClaimMappingObject instanceof Map) {
        Map<String, String> spToCarbonClaimMapping = (Map<String, String>) spToCarbonClaimMappingObject;
        for (Map.Entry<String, String> entry : spToCarbonClaimMapping.entrySet()) {
            carbonToSPClaimMapping.put(entry.getValue(), entry.getKey());
        }
    }
    boolean doMandatoryClaimsExist = false;
    for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
        if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {
            doMandatoryClaimsExist = true;
            break;
        }
    }
    if (!doMandatoryClaimsExist) {
        // Check whether mandatory claims exist in the request. If not throw error.
        throw new PostAuthenticationFailedException("Mandatory missing claims are not found", "Mandatory missing " + "claims are not found in the request for the session with context identifier: " + context.getContextIdentifier());
    }
    List<String> missingClaims = new ArrayList<>();
    for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
        if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {
            String localClaimURI = entry.getKey().substring(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX.length());
            if (StringUtils.isBlank(entry.getValue()[0])) {
                missingClaims.add(localClaimURI);
                continue;
            }
            claims.put(localClaimURI, entry.getValue()[0]);
            if (spToCarbonClaimMappingObject != null) {
                String spClaimURI = carbonToSPClaimMapping.get(localClaimURI);
                claimsForContext.put(spClaimURI, entry.getValue()[0]);
            } else {
                claimsForContext.put(localClaimURI, entry.getValue()[0]);
            }
        }
    }
    if (CollectionUtils.isNotEmpty(missingClaims)) {
        String missingClaimURIs = StringUtils.join(missingClaims, ",");
        if (log.isDebugEnabled()) {
            log.debug("Claim values for the mandatory claims: " + missingClaimURIs + " are empty");
        }
        throw new PostAuthenticationFailedException("Mandatory claim is not found", "Claim " + "values for the claim URIs: " + missingClaimURIs + " are empty");
    }
    Map<ClaimMapping, String> authenticatedUserAttributes = FrameworkUtils.buildClaimMappings(claimsForContext);
    authenticatedUserAttributes.putAll(user.getUserAttributes());
    for (Map.Entry<Integer, StepConfig> entry : context.getSequenceConfig().getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        if (stepConfig.isSubjectAttributeStep()) {
            if (stepConfig.getAuthenticatedUser() != null) {
                user = stepConfig.getAuthenticatedUser();
            }
            if (!user.isFederatedUser()) {
                persistClaims = true;
            } else {
                String associatedID;
                String subject = user.getAuthenticatedSubjectIdentifier();
                try {
                    FederatedAssociationManager federatedAssociationManager = FrameworkUtils.getFederatedAssociationManager();
                    associatedID = federatedAssociationManager.getUserForFederatedAssociation(context.getTenantDomain(), stepConfig.getAuthenticatedIdP(), subject);
                    if (StringUtils.isNotBlank(associatedID)) {
                        String fullQualifiedAssociatedUserId = FrameworkUtils.prependUserStoreDomainToName(associatedID + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain());
                        UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(associatedID));
                        user = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(fullQualifiedAssociatedUserId);
                        persistClaims = true;
                    }
                } catch (FederatedAssociationManagerException | FrameworkException e) {
                    throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while getting association for " + subject, e);
                }
            }
            break;
        }
    }
    if (persistClaims) {
        if (log.isDebugEnabled()) {
            log.debug("Local user mapping found. Claims will be persisted");
        }
        try {
            Map<String, String> claimMapping = context.getSequenceConfig().getApplicationConfig().getClaimMappings();
            Map<String, String> localIdpClaims = new HashMap<>();
            for (Map.Entry<String, String> entry : claims.entrySet()) {
                String localClaim = claimMapping.get(entry.getKey());
                localIdpClaims.put(localClaim, entry.getValue());
            }
            if (log.isDebugEnabled()) {
                log.debug("Updating user profile of user : " + user.getLoggableUserId());
            }
            UserRealm realm = getUserRealm(user.getTenantDomain());
            AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) realm.getUserStoreManager();
            userStoreManager.setUserClaimValuesWithID(user.getUserId(), localIdpClaims, null);
        } catch (UserStoreException e) {
            if (e instanceof UserStoreClientException) {
                context.setProperty(POST_AUTH_MISSING_CLAIMS_ERROR, e.getMessage());
                if (StringUtils.isNotBlank(e.getErrorCode())) {
                    context.setProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE, e.getErrorCode());
                }
                /*
                    When the attribute update is disabled for JIT provisioned users, the mandatory claim update
                    request will be identified through the error code and handled it.
                     */
                if (ERROR_CODE_INVALID_ATTRIBUTE_UPDATE.equals(e.getErrorCode())) {
                    context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
                    return;
                }
            }
            if (ErrorMessages.ERROR_CODE_READONLY_USER_STORE.getCode().equals(e.getErrorCode())) {
                context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
                return;
            }
            throw new PostAuthenticationFailedException(e.getMessage(), "Error while updating claims for local user. Could not update profile", e);
        } catch (UserIdNotFoundException e) {
            throw new PostAuthenticationFailedException("User id not found", "User id not found for local user. Could not update profile", e);
        }
    }
    context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
}
Also used : HashMap(java.util.HashMap) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) ArrayList(java.util.ArrayList) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) FederatedAssociationManager(org.wso2.carbon.identity.user.profile.mgt.association.federation.FederatedAssociationManager) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.core.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) FederatedAssociationManagerException(org.wso2.carbon.identity.user.profile.mgt.association.federation.exception.FederatedAssociationManagerException) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) Map(java.util.Map) HashMap(java.util.HashMap)

Example 8 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.

the class DefaultClaimHandler method retrieveAllNunNullUserClaimValues.

private Map<String, String> retrieveAllNunNullUserClaimValues(AuthenticatedUser authenticatedUser, ClaimManager claimManager, ApplicationConfig appConfig, AbstractUserStoreManager userStore) throws FrameworkException {
    String tenantDomain = authenticatedUser.getTenantDomain();
    Map<String, String> allLocalClaims = new HashMap<>();
    try {
        org.wso2.carbon.user.api.ClaimMapping[] claimMappings = claimManager.getAllClaimMappings(ApplicationConstants.LOCAL_IDP_DEFAULT_CLAIM_DIALECT);
        List<String> localClaimURIs = new ArrayList<>();
        for (org.wso2.carbon.user.api.ClaimMapping mapping : claimMappings) {
            String claimURI = mapping.getClaim().getClaimUri();
            localClaimURIs.add(claimURI);
        }
        allLocalClaims = userStore.getUserClaimValuesWithID(authenticatedUser.getUserId(), localClaimURIs.toArray(new String[0]), null);
        if (allLocalClaims == null) {
            return new HashMap<>();
        }
    } catch (UserStoreException e) {
        if (e.getMessage().contains("UserNotFound")) {
            if (log.isDebugEnabled()) {
                log.debug("User " + authenticatedUser.getLoggableUserId() + " not found in user store");
            }
        } else {
            throw new FrameworkException("Error occurred while getting all user claims for " + authenticatedUser.getLoggableUserId() + " in " + tenantDomain, e);
        }
    } catch (UserIdNotFoundException e) {
        throw new FrameworkException("User id is not available for user: " + authenticatedUser.getLoggableUserId(), e);
    }
    return allLocalClaims;
}
Also used : FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 9 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.

the class ResponseTypeHandlerUtil method generateAccessToken.

/**
 * Generates access token for the given oauth issuer.
 *
 * @param oauthAuthzMsgCtx
 * @param cacheEnabled
 * @param oauthIssuerImpl
 * @return
 * @throws IdentityOAuth2Exception
 */
public static AccessTokenDO generateAccessToken(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
    String consumerKey = authorizationReqDTO.getConsumerKey();
    String authorizedUserId;
    try {
        authorizedUserId = authorizationReqDTO.getUser().getUserId();
    } catch (UserIdNotFoundException e) {
        throw new IdentityOAuth2Exception("Error occurred while retrieving the user id for user: " + authorizationReqDTO.getUser().getLoggableUserId());
    }
    synchronized ((consumerKey + ":" + authorizedUserId + ":" + scope).intern()) {
        AccessTokenDO existingTokenBean = getExistingToken(oauthAuthzMsgCtx, authorizedUserId, cacheEnabled);
        // Return a new access token in each request when JWTTokenIssuer is used.
        if (isNotRenewAccessTokenPerRequest(oauthIssuerImpl, oauthAuthzMsgCtx)) {
            if (existingTokenBean != null) {
                // Revoke token if RenewTokenPerRequest configuration is enabled.
                if (OAuthServerConfiguration.getInstance().isTokenRenewalPerRequestEnabled()) {
                    if (log.isDebugEnabled()) {
                        log.debug("RenewTokenPerRequest configuration active. " + "Proceeding to revoke any existing active tokens for client Id: " + consumerKey + ", user: " + authorizationReqDTO.getUser().getLoggableUserId() + " and scope: " + scope + ".");
                    }
                    revokeExistingToken(existingTokenBean.getConsumerKey(), existingTokenBean.getAccessToken());
                    // When revoking the token state will be set as REVOKED.
                    // existingTokenBean.setTokenState(TOKEN_STATE_REVOKED) can be used instead of 'null' but
                    // then the token state will again be updated to EXPIRED when a new token is generated.
                    existingTokenBean = null;
                }
                // Return existing token if it is still valid.
                if (isAccessTokenValid(existingTokenBean)) {
                    return existingTokenBean;
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("No active access token found for client Id: " + consumerKey + ", user: " + authorizationReqDTO.getUser().getLoggableUserId() + " and scope: " + scope + ". Therefore issuing new token");
            }
        }
        // Issue a new access token.
        return generateNewAccessToken(oauthAuthzMsgCtx, existingTokenBean, oauthIssuerImpl, authorizedUserId, cacheEnabled);
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 10 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.

the class ResponseTypeHandlerUtil method generateAuthorizationCode.

public static AuthzCodeDO generateAuthorizationCode(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String authorizationCode;
    String codeId = UUID.randomUUID().toString();
    Timestamp timestamp = new Timestamp(new Date().getTime());
    long validityPeriod = OAuthServerConfiguration.getInstance().getAuthorizationCodeValidityPeriodInSeconds();
    // if a VALID callback is set through the callback handler, use
    // it instead of the default one
    long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();
    if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) {
        validityPeriod = callbackValidityPeriod;
    }
    // convert to milliseconds
    validityPeriod = validityPeriod * 1000;
    // set the validity period. this is needed by downstream handlers.
    // if this is set before - then this will override it by the calculated new value.
    oauthAuthzMsgCtx.setValidityPeriod(validityPeriod);
    oauthAuthzMsgCtx.setAuthorizationCodeValidityPeriod(validityPeriod);
    // set code issued time.this is needed by downstream handlers.
    oauthAuthzMsgCtx.setCodeIssuedTime(timestamp.getTime());
    if (authorizationReqDTO.getUser() != null && authorizationReqDTO.getUser().isFederatedUser()) {
        // if a federated user, treat the tenant domain as similar to application domain.
        authorizationReqDTO.getUser().setTenantDomain(authorizationReqDTO.getTenantDomain());
    }
    try {
        authorizationCode = oauthIssuerImpl.authorizationCode(oauthAuthzMsgCtx);
    } catch (OAuthSystemException e) {
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-authz-code", null);
        throw new IdentityOAuth2Exception(e.getMessage(), e);
    }
    AuthzCodeDO authzCodeDO = new AuthzCodeDO(authorizationReqDTO.getUser(), oauthAuthzMsgCtx.getApprovedScope(), timestamp, validityPeriod, authorizationReqDTO.getCallbackUrl(), authorizationReqDTO.getConsumerKey(), authorizationCode, codeId, authorizationReqDTO.getPkceCodeChallenge(), authorizationReqDTO.getPkceCodeChallengeMethod());
    OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().insertAuthorizationCode(authorizationCode, authorizationReqDTO.getConsumerKey(), authorizationReqDTO.getCallbackUrl(), authzCodeDO);
    if (cacheEnabled) {
        // Cache the authz Code, here we prepend the client_key to avoid collisions with
        // AccessTokenDO instances. In database level, these are in two databases. But access
        // tokens and authorization codes are in a single cache.
        String cacheKeyString = OAuth2Util.buildCacheKeyStringForAuthzCode(authorizationReqDTO.getConsumerKey(), authorizationCode);
        OAuthCache.getInstance().addToCache(new OAuthCacheKey(cacheKeyString), authzCodeDO);
        if (log.isDebugEnabled()) {
            log.debug("Authorization Code info was added to the cache for client id : " + authorizationReqDTO.getConsumerKey());
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Issued Authorization Code to user : " + authorizationReqDTO.getUser() + ", Using the redirect url : " + authorizationReqDTO.getCallbackUrl() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", validity period : " + validityPeriod);
    }
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", authorizationReqDTO.getConsumerKey());
        if (authorizationReqDTO.getUser() != null) {
            try {
                params.put("user", authorizationReqDTO.getUser().getUserId());
            } catch (UserIdNotFoundException e) {
                if (StringUtils.isNotBlank(authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier())) {
                    params.put("user", authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier().replaceAll(".", "*"));
                }
            }
        }
        params.put("requestedScopes", OAuth2Util.buildScopeString(authorizationReqDTO.getScopes()));
        params.put("redirectUri", authorizationReqDTO.getCallbackUrl());
        Map<String, Object> configs = new HashMap<>();
        configs.put("authzCodeValidityPeriod", String.valueOf(validityPeriod));
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Issued Authorization Code to user.", "issue-authz-code", configs);
    }
    return authzCodeDO;
}
Also used : HashMap(java.util.HashMap) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) Timestamp(java.sql.Timestamp) Date(java.util.Date) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)

Aggregations

UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)29 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)14 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)9 HashMap (java.util.HashMap)8 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)7 UserStoreException (org.wso2.carbon.user.api.UserStoreException)7 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)6 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)6 OAuth2AuthorizeReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO)5 ArrayList (java.util.ArrayList)4 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)4 RealmService (org.wso2.carbon.user.core.service.RealmService)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)3 JSONObject (org.json.JSONObject)3 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)3 Timestamp (java.sql.Timestamp)2 Date (java.util.Date)2 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)2 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)2