Search in sources :

Example 16 with UserIdNotFoundException

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

the class RefreshGrantHandler method updateCacheIfEnabled.

private void updateCacheIfEnabled(OAuthTokenReqMessageContext tokReqMsgCtx, AccessTokenDO accessTokenBean, String clientId, RefreshTokenValidationDataDO oldAccessToken) throws IdentityOAuth2Exception {
    if (isHashDisabled && cacheEnabled) {
        // Remove old access token from the OAuthCache
        String scope = OAuth2Util.buildScopeString(tokReqMsgCtx.getScope());
        String userId;
        try {
            userId = tokReqMsgCtx.getAuthorizedUser().getUserId();
        } catch (UserIdNotFoundException e) {
            throw new IdentityOAuth2Exception("User id is not available for user: " + tokReqMsgCtx.getAuthorizedUser().getLoggableUserId(), e);
        }
        String authenticatedIDP = tokReqMsgCtx.getAuthorizedUser().getFederatedIdPName();
        String cacheKeyString = buildCacheKeyStringForTokenWithUserId(clientId, scope, userId, authenticatedIDP, oldAccessToken.getTokenBindingReference());
        OAuthCacheKey oauthCacheKey = new OAuthCacheKey(cacheKeyString);
        OAuthCache.getInstance().clearCacheEntry(oauthCacheKey, accessTokenBean.getAuthzUser().getTenantDomain());
        // Remove old access token from the AccessTokenCache
        OAuthCacheKey accessTokenCacheKey = new OAuthCacheKey(oldAccessToken.getAccessToken());
        OAuthCache.getInstance().clearCacheEntry(accessTokenCacheKey, oldAccessToken.getAuthorizedUser().getTenantDomain());
        // Add new access token to the OAuthCache
        OAuthCache.getInstance().addToCache(oauthCacheKey, accessTokenBean);
        // Add new access token to the AccessTokenCache
        OAuth2Util.addTokenDOtoCache(accessTokenBean);
        if (log.isDebugEnabled()) {
            log.debug("Access Token info for the refresh token was added to the cache for " + "the client id : " + clientId + ". Old access token entry was " + "also removed from the cache.");
        }
    }
}
Also used : OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 17 with UserIdNotFoundException

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

the class JsClaims method setLocalUserClaim.

/**
 * Sets a local claim directly at the userstore for the given user by given claim uri
 *
 * @param claimUri   Local claim URI
 * @param claimValue Claim value
 */
private void setLocalUserClaim(String claimUri, Object claimValue) {
    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimUriMap = new HashMap<>();
        claimUriMap.put(claimUri, String.valueOf(claimValue));
        ((AbstractUserStoreManager) userRealm.getUserStoreManager()).setUserClaimValuesWithID(authenticatedUser.getUserId(), claimUriMap, null);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when setting claim : %s of user: %s to value: %s", claimUri, authenticatedUser, String.valueOf(claimValue)), e);
    } catch (UserIdNotFoundException e) {
        LOG.error("User id is not available for the user: " + authenticatedUser.getLoggableUserId(), e);
    }
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) HashMap(java.util.HashMap) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 18 with UserIdNotFoundException

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

the class TokenResponseTypeHandler method issue.

@Override
public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception {
    OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy();
    if (oAuthEventInterceptorProxy != null && oAuthEventInterceptorProxy.isEnabled()) {
        Map<String, Object> paramMap = new HashMap<>();
        oAuthEventInterceptorProxy.onPreTokenIssue(oauthAuthzMsgCtx, paramMap);
    }
    OAuth2AuthorizeRespDTO respDTO = new OAuth2AuthorizeRespDTO();
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
    respDTO.setCallbackURI(authorizationReqDTO.getCallbackUrl());
    String consumerKey = authorizationReqDTO.getConsumerKey();
    String authorizedUserId = null;
    try {
        authorizedUserId = authorizationReqDTO.getUser().getUserId();
    } catch (UserIdNotFoundException e) {
        throw new IdentityOAuth2Exception("Error occurred while retrieving the user id for user: " + authorizationReqDTO.getUser().getLoggableUserId());
    }
    String oAuthCacheKeyString;
    String responseType = oauthAuthzMsgCtx.getAuthorizationReqDTO().getResponseType();
    String grantType;
    // Loading the stored application data.
    OAuthAppDO oAuthAppDO;
    try {
        oAuthAppDO = OAuth2Util.getAppInformationByClientId(consumerKey);
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Error while retrieving app information for clientId: " + consumerKey, e);
    }
    if (StringUtils.contains(responseType, OAuthConstants.GrantTypes.TOKEN)) {
        grantType = OAuthConstants.GrantTypes.IMPLICIT;
    } else {
        grantType = responseType;
    }
    oAuthCacheKeyString = consumerKey + ":" + authorizedUserId + ":" + scope;
    OAuthCacheKey cacheKey = new OAuthCacheKey(oAuthCacheKeyString);
    String userStoreDomain = null;
    // Select the user store domain when multiple user stores are configured.
    if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) {
        userStoreDomain = OAuth2Util.getUserStoreForFederatedUser(authorizationReqDTO.getUser());
    }
    if (log.isDebugEnabled()) {
        log.debug("Service Provider specific expiry time enabled for application : " + consumerKey + ". Application access token expiry time : " + oAuthAppDO.getApplicationAccessTokenExpiryTime() + ", User access token expiry time : " + oAuthAppDO.getUserAccessTokenExpiryTime() + ", Refresh token expiry time : " + oAuthAppDO.getRefreshTokenExpiryTime());
    }
    String refreshToken = null;
    Timestamp refreshTokenIssuedTime = null;
    long refreshTokenValidityPeriodInMillis = 0;
    AccessTokenDO tokenDO = null;
    synchronized ((consumerKey + ":" + authorizedUserId + ":" + scope).intern()) {
        AccessTokenDO existingAccessTokenDO = null;
        // check if valid access token exists in cache
        if (isHashDisabled && cacheEnabled) {
            existingAccessTokenDO = (AccessTokenDO) OAuthCache.getInstance().getValueFromCache(cacheKey);
            if (existingAccessTokenDO != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved active Access Token for Client Id : " + consumerKey + ", User ID :" + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope + " from cache");
                }
                long expireTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO);
                if ((expireTime > 0 || expireTime < 0)) {
                    // Return still valid existing access token when JWTTokenIssuer is not used.
                    if (isNotRenewAccessTokenPerRequest(oauthAuthzMsgCtx)) {
                        if (log.isDebugEnabled()) {
                            if (expireTime > 0) {
                                log.debug("Access Token is valid for another " + expireTime + "ms");
                            } else {
                                log.debug("Infinite lifetime Access Token found in cache");
                            }
                        }
                        respDTO.setAccessToken(existingAccessTokenDO.getAccessToken());
                        if (expireTime > 0) {
                            respDTO.setValidityPeriod(expireTime / 1000);
                        } else {
                            respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
                        }
                        respDTO.setScope(oauthAuthzMsgCtx.getApprovedScope());
                        respDTO.setTokenType(existingAccessTokenDO.getTokenType());
                        // We only need to deal with id_token and user attributes if the request is OIDC
                        if (isOIDCRequest(oauthAuthzMsgCtx)) {
                            buildIdToken(oauthAuthzMsgCtx, respDTO);
                        }
                        triggerPostListeners(oauthAuthzMsgCtx, existingAccessTokenDO, respDTO);
                        return respDTO;
                    }
                } else {
                    long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(existingAccessTokenDO);
                    if (refreshTokenExpiryTime < 0 || refreshTokenExpiryTime > 0) {
                        if (log.isDebugEnabled()) {
                            log.debug("Access token has expired, But refresh token is still valid. User existing " + "refresh token.");
                        }
                        refreshToken = existingAccessTokenDO.getRefreshToken();
                        refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime();
                        refreshTokenValidityPeriodInMillis = existingAccessTokenDO.getRefreshTokenValidityPeriodInMillis();
                    }
                    // Token is expired. Clear it from cache
                    OAuthCache.getInstance().clearCacheEntry(cacheKey);
                    if (log.isDebugEnabled()) {
                        log.debug("Access Token is expired. Therefore cleared it from cache and marked it as" + " expired in database");
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("No active access token found in cache for Client ID : " + consumerKey + ", User " + "ID" + " : " + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope);
                }
            }
        }
        // in the database
        if (isHashDisabled && existingAccessTokenDO == null) {
            existingAccessTokenDO = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(consumerKey, authorizationReqDTO.getUser(), userStoreDomain, scope, false);
            if (existingAccessTokenDO != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved latest Access Token for Client ID : " + consumerKey + ", User ID :" + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope + " from database");
                }
                long expiryTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO);
                long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(existingAccessTokenDO);
                if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(existingAccessTokenDO.getTokenState()) && (expiryTime > 0 || expiryTime < 0)) {
                    // Return still valid existing access token when JWTTokenIssuer is not used.
                    if (isNotRenewAccessTokenPerRequest(oauthAuthzMsgCtx)) {
                        // token is active and valid
                        if (log.isDebugEnabled()) {
                            if (expiryTime > 0) {
                                log.debug("Access token is valid for another " + expiryTime + "ms");
                            } else {
                                log.debug("Infinite lifetime Access Token found in cache");
                            }
                        }
                        if (cacheEnabled) {
                            OAuthCache.getInstance().addToCache(cacheKey, existingAccessTokenDO);
                            if (log.isDebugEnabled()) {
                                log.debug("Access Token was added to cache for cache key : " + cacheKey.getCacheKeyString());
                            }
                        }
                        respDTO.setAccessToken(existingAccessTokenDO.getAccessToken());
                        if (expiryTime > 0) {
                            respDTO.setValidityPeriod(expiryTime / 1000);
                        } else {
                            respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
                        }
                        respDTO.setScope(oauthAuthzMsgCtx.getApprovedScope());
                        respDTO.setTokenType(existingAccessTokenDO.getTokenType());
                        // we only need to deal with id_token and user attributes if the request is OIDC
                        if (isOIDCRequest(oauthAuthzMsgCtx)) {
                            buildIdToken(oauthAuthzMsgCtx, respDTO);
                        }
                        triggerPostListeners(oauthAuthzMsgCtx, existingAccessTokenDO, respDTO);
                        return respDTO;
                    }
                } else {
                    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                        log.debug("Access Token is " + existingAccessTokenDO.getTokenState());
                    }
                    String tokenState = existingAccessTokenDO.getTokenState();
                    if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(tokenState)) {
                        // Token is expired. If refresh token is still valid, use it.
                        if (refreshTokenExpiryTime > 0 || refreshTokenExpiryTime < 0) {
                            if (log.isDebugEnabled()) {
                                log.debug("Access token has expired, But refresh token is still valid. User " + "existing refresh token.");
                            }
                            refreshToken = existingAccessTokenDO.getRefreshToken();
                            refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime();
                            refreshTokenValidityPeriodInMillis = existingAccessTokenDO.getRefreshTokenValidityPeriodInMillis();
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("Marked Access Token as expired");
                        }
                    } else {
                        // Token is revoked or inactive
                        if (log.isDebugEnabled()) {
                            log.debug("Access Token is " + existingAccessTokenDO.getTokenState());
                        }
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("No access token found in database for Client ID : " + consumerKey + ", User ID : " + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope);
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Issuing a new access token for client id: " + consumerKey + ", user : " + authorizationReqDTO.getUser().getLoggableUserId() + "and scope : " + scope);
        }
        Timestamp timestamp = new Timestamp(new Date().getTime());
        // if reusing existing refresh token, use its original issued time
        if (refreshTokenIssuedTime == null) {
            refreshTokenIssuedTime = timestamp;
        }
        // Default token validity Period
        long validityPeriodInMillis = OAuthServerConfiguration.getInstance().getUserAccessTokenValidityPeriodInSeconds() * 1000;
        if (oAuthAppDO.getUserAccessTokenExpiryTime() != 0) {
            validityPeriodInMillis = oAuthAppDO.getUserAccessTokenExpiryTime() * 1000;
        }
        // if a VALID validity period is set through the callback, then use it
        long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();
        if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) {
            validityPeriodInMillis = callbackValidityPeriod * 1000;
        }
        // otherwise use existing refresh token's validity period
        if (refreshTokenValidityPeriodInMillis == 0) {
            if (oAuthAppDO.getRefreshTokenExpiryTime() != 0) {
                refreshTokenValidityPeriodInMillis = oAuthAppDO.getRefreshTokenExpiryTime() * 1000;
            } else {
                refreshTokenValidityPeriodInMillis = OAuthServerConfiguration.getInstance().getRefreshTokenValidityPeriodInSeconds() * 1000;
            }
        }
        // issue a new access token
        String accessToken;
        // 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(validityPeriodInMillis);
        // set the refresh token validity period. this is needed by downstream handlers.
        // if this is set before - then this will override it by the calculated new value.
        oauthAuthzMsgCtx.setRefreshTokenvalidityPeriod(refreshTokenValidityPeriodInMillis);
        // set access token issued time.this is needed by downstream handlers.
        oauthAuthzMsgCtx.setAccessTokenIssuedTime(timestamp.getTime());
        // set refresh token issued time.this is needed by downstream handlers.
        oauthAuthzMsgCtx.setRefreshTokenIssuedTime(refreshTokenIssuedTime.getTime());
        try {
            OauthTokenIssuer oauthIssuerImpl = OAuth2Util.getOAuthTokenIssuerForOAuthApp(oAuthAppDO);
            accessToken = oauthIssuerImpl.accessToken(oauthAuthzMsgCtx);
            // regenerate only if refresh token is null
            if (refreshToken == null) {
                refreshToken = oauthIssuerImpl.refreshToken(oauthAuthzMsgCtx);
            }
        } catch (OAuthSystemException e) {
            throw new IdentityOAuth2Exception("Error occurred while generating access token and refresh token", e);
        }
        if (OAuth2Util.checkUserNameAssertionEnabled()) {
            accessToken = OAuth2Util.addUsernameToToken(authorizationReqDTO.getUser(), accessToken);
            refreshToken = OAuth2Util.addUsernameToToken(authorizationReqDTO.getUser(), refreshToken);
        }
        AccessTokenDO newAccessTokenDO = new AccessTokenDO(consumerKey, authorizationReqDTO.getUser(), oauthAuthzMsgCtx.getApprovedScope(), timestamp, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodInMillis, OAuthConstants.UserType.APPLICATION_USER);
        newAccessTokenDO.setAccessToken(accessToken);
        newAccessTokenDO.setRefreshToken(refreshToken);
        newAccessTokenDO.setTokenState(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE);
        newAccessTokenDO.setGrantType(grantType);
        String tokenId = UUID.randomUUID().toString();
        newAccessTokenDO.setTokenId(tokenId);
        oauthAuthzMsgCtx.addProperty(OAuth2Util.ACCESS_TOKEN_DO, newAccessTokenDO);
        // Persist the access token in database
        try {
            OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().insertAccessToken(accessToken, authorizationReqDTO.getConsumerKey(), newAccessTokenDO, existingAccessTokenDO, userStoreDomain);
            deactivateCurrentAuthorizationCode(newAccessTokenDO.getAuthorizationCode(), newAccessTokenDO.getTokenId());
            if (!accessToken.equals(newAccessTokenDO.getAccessToken())) {
                // Using latest active token.
                accessToken = newAccessTokenDO.getAccessToken();
                refreshToken = newAccessTokenDO.getRefreshToken();
            }
        } catch (IdentityException e) {
            throw new IdentityOAuth2Exception("Error occurred while storing new access token : " + accessToken, e);
        }
        tokenDO = newAccessTokenDO;
        if (log.isDebugEnabled()) {
            log.debug("Persisted Access Token for " + "Client ID : " + authorizationReqDTO.getConsumerKey() + ", Authorized User : " + authorizationReqDTO.getUser().getLoggableUserId() + ", Timestamp : " + timestamp + ", Validity period (s) : " + newAccessTokenDO.getValidityPeriod() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", Callback URL : " + authorizationReqDTO.getCallbackUrl() + ", Token State : " + OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE + " and User Type : " + OAuthConstants.UserType.APPLICATION_USER);
        }
        // Add the access token to the cache, if cacheEnabled and the hashing oauth key feature turn on.
        if (isHashDisabled && cacheEnabled) {
            OAuthCache.getInstance().addToCache(cacheKey, newAccessTokenDO);
            // Adding AccessTokenDO to improve validation performance
            OAuthCacheKey accessTokenCacheKey = new OAuthCacheKey(accessToken);
            OAuthCache.getInstance().addToCache(accessTokenCacheKey, newAccessTokenDO);
            if (log.isDebugEnabled()) {
                log.debug("Access Token was added to OAuthCache for cache key : " + cacheKey.getCacheKeyString());
                log.debug("Access Token was added to OAuthCache for cache key : " + accessTokenCacheKey.getCacheKeyString());
            }
        }
        if (StringUtils.contains(responseType, ResponseType.TOKEN.toString())) {
            respDTO.setAccessToken(accessToken);
            if (validityPeriodInMillis > 0) {
                respDTO.setValidityPeriod(newAccessTokenDO.getValidityPeriod());
            } else {
                respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
            }
            respDTO.setScope(newAccessTokenDO.getScope());
            respDTO.setTokenType(newAccessTokenDO.getTokenType());
        }
    }
    // we only need to deal with id_token and user attributes if the request is OIDC
    if (isOIDCRequest(oauthAuthzMsgCtx)) {
        buildIdToken(oauthAuthzMsgCtx, respDTO);
    }
    triggerPostListeners(oauthAuthzMsgCtx, tokenDO, respDTO);
    return respDTO;
}
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) IdentityException(org.wso2.carbon.identity.base.IdentityException) Timestamp(java.sql.Timestamp) Date(java.util.Date) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) OAuthEventInterceptor(org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 19 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 getExistingTokenFromDB.

private static AccessTokenDO getExistingTokenFromDB(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled) throws IdentityOAuth2Exception {
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
    String consumerKey = authorizationReqDTO.getConsumerKey();
    AuthenticatedUser authorizedUser = authorizationReqDTO.getUser();
    AccessTokenDO existingToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(consumerKey, authorizedUser, getUserStoreDomain(authorizedUser), scope, false);
    if (existingToken != null) {
        if (log.isDebugEnabled()) {
            if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                log.debug("Retrieved latest access token(hashed): " + DigestUtils.sha256Hex(existingToken.getAccessToken()) + " in state: " + existingToken.getTokenState() + " for client Id: " + consumerKey + " user: " + authorizedUser + " and scope: " + scope + " from db");
            } else {
                log.debug("Retrieved latest access token for client Id: " + consumerKey + " user: " + authorizedUser + " and scope: " + scope + " from db");
            }
        }
        long expireTime = getAccessTokenExpiryTimeMillis(existingToken);
        if (TOKEN_STATE_ACTIVE.equals(existingToken.getTokenState()) && expireTime != 0 && cacheEnabled) {
            // Active token retrieved from db, adding to cache if cacheEnabled
            try {
                addTokenToCache(getOAuthCacheKey(consumerKey, scope, authorizedUser.getUserId(), OAuth2Util.getAuthenticatedIDP(authorizedUser)), existingToken);
            } catch (UserIdNotFoundException e) {
                throw new IdentityOAuth2Exception("Error occurred while retrieving the user id for user: " + authorizationReqDTO.getUser().getLoggableUserId());
            }
        }
    }
    return existingToken;
}
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) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 20 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 addUserAttributesToCache.

private static void addUserAttributesToCache(String accessToken, OAuthAuthzReqMessageContext msgCtx) throws IdentityOAuth2Exception {
    OAuth2AuthorizeReqDTO authorizeReqDTO = msgCtx.getAuthorizationReqDTO();
    Map<ClaimMapping, String> userAttributes = authorizeReqDTO.getUser().getUserAttributes();
    AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(accessToken);
    AuthorizationGrantCacheEntry authorizationGrantCacheEntry = new AuthorizationGrantCacheEntry(userAttributes);
    if (StringUtils.isNotBlank(authorizeReqDTO.getEssentialClaims())) {
        authorizationGrantCacheEntry.setEssentialClaims(authorizeReqDTO.getEssentialClaims());
    }
    ClaimMapping key = new ClaimMapping();
    Claim claimOfKey = new Claim();
    claimOfKey.setClaimUri(OAuth2Util.SUB);
    key.setRemoteClaim(claimOfKey);
    String sub = null;
    try {
        sub = authorizeReqDTO.getUser().getUserId();
    } catch (UserIdNotFoundException e) {
    // Ignoring the unavailability of the user id, since it is handled later.
    }
    AccessTokenDO accessTokenDO = getAccessTokenDO(accessToken, msgCtx);
    if (accessTokenDO != null && StringUtils.isNotBlank(accessTokenDO.getTokenId())) {
        authorizationGrantCacheEntry.setTokenId(accessTokenDO.getTokenId());
    }
    if (StringUtils.isBlank(sub)) {
        sub = authorizeReqDTO.getUser().getAuthenticatedSubjectIdentifier();
    }
    if (StringUtils.isNotBlank(sub)) {
        userAttributes.put(key, sub);
    }
    authorizationGrantCacheEntry.setValidityPeriod(TimeUnit.MILLISECONDS.toNanos(accessTokenDO.getValidityPeriodInMillis()));
    AuthorizationGrantCache.getInstance().addToCacheByToken(authorizationGrantCacheKey, authorizationGrantCacheEntry);
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) AuthorizationGrantCacheEntry(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) AuthorizationGrantCacheKey(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) Claim(org.wso2.carbon.identity.application.common.model.Claim)

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