org.wso2.carbon.identity.oauth2.model.AccessTokenDO Java Examples

The following examples show how to use org.wso2.carbon.identity.oauth2.model.AccessTokenDO. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CellerySignedJWTGenerator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private String getEndUserName(TokenValidationContext validationContext) throws APIManagementException {

        try {
            String accessToken = validationContext.getAccessToken();
            AccessTokenDO tokenInfo = OAuth2Util.getAccessTokenDOfromTokenIdentifier(accessToken);
            AuthenticatedUser authzUser = tokenInfo.getAuthzUser();
            String endUserName = validationContext.getValidationInfoDTO().getEndUserName();
            if (authzUser.isFederatedUser()) {
                return endUserName;
            } else {
                return MultitenantUtils.getTenantAwareUsername(endUserName);
            }
        } catch (IdentityOAuth2Exception e) {
            throw new APIManagementException("Error while retrieving authenticated user metadata.", e);
        }

    }
 
Example #2
Source File: OAuthUserStoreConfigListenerImpl.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public void onUserStoreNamePreUpdate(int tenantId, String currentUserStoreName, String newUserStoreName) throws
        UserStoreException {
    TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
    try {
        Set<AccessTokenDO> accessTokenDOs = tokenMgtDAO.getAccessTokensOfUserStore(tenantId, currentUserStoreName);
        for (AccessTokenDO accessTokenDO : accessTokenDOs) {
            //Clear cache
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser(),
                    OAuth2Util.buildScopeString(accessTokenDO.getScope()));
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser());
            OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
        }
        tokenMgtDAO.renameUserStoreDomainInAccessTokenTable(tenantId, currentUserStoreName, newUserStoreName);
        tokenMgtDAO.renameUserStoreDomainInAuthorizationCodeTable(tenantId, currentUserStoreName, newUserStoreName);
    } catch (IdentityOAuth2Exception e) {
        throw new UserStoreException("Error occurred while renaming user store : " + currentUserStoreName +
                " in tenant :" + tenantId, e);
    }
}
 
Example #3
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static AccessTokenDO validateAccessTokenDO(AccessTokenDO accessTokenDO) {

        long validityPeriodMillis = accessTokenDO.getValidityPeriodInMillis();
        long issuedTime = accessTokenDO.getIssuedTime().getTime();
        long currentTime = System.currentTimeMillis();

        //check the validity of cached OAuth2AccessToken Response
        long skew = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
        if (issuedTime + validityPeriodMillis - (currentTime + skew) > 1000) {
            long refreshValidity = OAuthServerConfiguration.getInstance()
                    .getRefreshTokenValidityPeriodInSeconds() * 1000;
            if (issuedTime + refreshValidity - currentTime + skew > 1000) {
                //Set new validity period to response object
                accessTokenDO.setValidityPeriod((issuedTime + validityPeriodMillis - (currentTime + skew)) / 1000);
                accessTokenDO.setValidityPeriodInMillis(issuedTime + validityPeriodMillis - (currentTime + skew));
                //Set issued time period to response object
                accessTokenDO.setIssuedTime(new Timestamp(currentTime));
                return accessTokenDO;
            }
        }
        //returns null if cached OAuth2AccessToken response object is expired
        return null;
    }
 
Example #4
Source File: TokenValidationHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
    * 
    * @param accessTokenDO
    * @return
    * @throws IdentityOAuth2Exception 
    */
   private boolean hasAcessTokenExpired(AccessTokenDO accessTokenDO) {
// check whether the grant is expired
if (accessTokenDO.getValidityPeriod() < 0) {
    if (log.isDebugEnabled()) {
	log.debug("Access Token has infinite lifetime");
    }
} else {
    if (OAuth2Util.getAccessTokenExpireMillis(accessTokenDO) == 0) {
	if (log.isDebugEnabled()) {
	    log.debug("Access Token has expired");
	}
	return true;
    }
}

return false;
   }
 
Example #5
Source File: TokenValidationHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
    * 
    * @param accessTokenDO
    * @return
    */
   private long getAccessTokenExpirationTime(AccessTokenDO accessTokenDO) {
long expiryTime = OAuth2Util.getAccessTokenExpireMillis(accessTokenDO);

if (OAuthConstants.UserType.APPLICATION_USER.equals(accessTokenDO.getTokenType())
	&& OAuthServerConfiguration.getInstance().getUserAccessTokenValidityPeriodInSeconds() < 0) {
    return Long.MAX_VALUE;
} else if (OAuthConstants.UserType.APPLICATION.equals(accessTokenDO.getTokenType())
	&& OAuthServerConfiguration.getInstance().getApplicationAccessTokenValidityPeriodInSeconds() < 0) {
    return Long.MAX_VALUE;
} else if (expiryTime < 0) {
    return Long.MAX_VALUE;
}

return expiryTime / 1000;
   }
 
Example #6
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static long getTokenExpireTimeMillis(AccessTokenDO accessTokenDO) {

        if (accessTokenDO == null) {
            throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'");
        }

        long currentTime;
        long validityPeriodMillis = accessTokenDO.getValidityPeriodInMillis();

        if(validityPeriodMillis < 0){
            log.debug("Access Token : " + accessTokenDO.getAccessToken() + " has infinite lifetime");
            return -1;
        }

        long refreshTokenValidityPeriodMillis = accessTokenDO.getRefreshTokenValidityPeriodInMillis();
        long issuedTime = accessTokenDO.getIssuedTime().getTime();
        currentTime = System.currentTimeMillis();
        long refreshTokenIssuedTime = accessTokenDO.getRefreshTokenIssuedTime().getTime();
        long accessTokenValidity = issuedTime + validityPeriodMillis - (currentTime + timestampSkew);
        long refreshTokenValidity = (refreshTokenIssuedTime + refreshTokenValidityPeriodMillis)
                                    - (currentTime + timestampSkew);
        if(accessTokenValidity > 1000 && refreshTokenValidity > 1000){
            return accessTokenValidity;
        }
        return 0;
    }
 
Example #7
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static long getRefreshTokenExpireTimeMillis(AccessTokenDO accessTokenDO) {

        if (accessTokenDO == null) {
            throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'");
        }

        long currentTime;
        long refreshTokenValidityPeriodMillis = accessTokenDO.getRefreshTokenValidityPeriodInMillis();

        if (refreshTokenValidityPeriodMillis < 0) {
            log.debug("Refresh Token has infinite lifetime");
            return -1;
        }

        currentTime = System.currentTimeMillis();
        long refreshTokenIssuedTime = accessTokenDO.getRefreshTokenIssuedTime().getTime();
        long refreshTokenValidity = (refreshTokenIssuedTime + refreshTokenValidityPeriodMillis)
                                    - (currentTime + timestampSkew);
        if(refreshTokenValidity > 1000){
            return refreshTokenValidity;
        }
        return 0;
    }
 
Example #8
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static long getAccessTokenExpireMillis(AccessTokenDO accessTokenDO) {

        if(accessTokenDO == null){
            throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'");
        }
        long currentTime;
        long validityPeriodMillis = accessTokenDO.getValidityPeriodInMillis();

        if (validityPeriodMillis < 0) {
            log.debug("Access Token has infinite lifetime");
            return -1;
        }

        long issuedTime = accessTokenDO.getIssuedTime().getTime();
        currentTime = System.currentTimeMillis();
        long validityMillis = issuedTime + validityPeriodMillis - (currentTime + timestampSkew);
        if (validityMillis > 1000) {
            return validityMillis;
        } else {
            return 0;
        }
    }
 
Example #9
Source File: APIMOAuthEventInterceptor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Overridden method to handle the post processing of token revocation
 *
 * @param revokeRequestDTO requested revoke request object
 * @param revokeRespDTO requested revoke request object
 * @param accessTokenDO requested Access token object
 * @param params requested params Map<String,Object>
 */
@Override
public void onPostTokenRevocationByResourceOwner(
        org.wso2.carbon.identity.oauth.dto.OAuthRevocationRequestDTO revokeRequestDTO,
        org.wso2.carbon.identity.oauth.dto.OAuthRevocationResponseDTO revokeRespDTO, AccessTokenDO accessTokenDO,
        Map<String, Object> params) {

    if(accessTokenDO != null) { // if accessTokenDO is not null, it implies the revocation was a success
        String revokedToken = accessTokenDO.getAccessToken();
        Long expiryTime = 0L;
        boolean isJwtToken = false;
        if (revokedToken.contains(APIConstants.DOT) && APIUtil.isValidJWT(revokedToken)) {
            expiryTime = APIUtil.getExpiryifJWT(revokedToken);
            isJwtToken = true;
        }
        revocationRequestPublisher.publishRevocationEvents(revokedToken, expiryTime, null);
        if (isJwtToken) {
            // Persist revoked JWT token to database.
            persistRevokedJWTSignature(revokedToken, expiryTime);
        }
    }
}
 
Example #10
Source File: APIMOAuthEventInterceptor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Overridden method to handle the post processing of token revocation
 * Called after revoking a token by oauth client
 *
 * @param revokeRequestDTO requested revoke request object
 * @param revokeResponseDTO requested revoke response object
 * @param accessTokenDO requested access token object
 * @param refreshTokenDO requested refresh token object
 * @param params requested params Map<String,Object>
 */
@Override
public void onPostTokenRevocationByClient(OAuthRevocationRequestDTO revokeRequestDTO,
        OAuthRevocationResponseDTO revokeResponseDTO, AccessTokenDO accessTokenDO,
        RefreshTokenValidationDataDO refreshTokenDO, Map<String, Object> params) {

    // If the response header contains RevokedAccessToken header, it implies the token revocation was a success.
    ResponseHeader[] responseHeaders = revokeResponseDTO.getResponseHeaders();
    boolean isRevokedAccessTokenHeaderExists = false;
    if(responseHeaders != null) {
        for (ResponseHeader responseHeader : responseHeaders) {
            if (responseHeader.getKey().equals(REVOKED_ACCESS_TOKEN) && responseHeader.getValue() != null){
                isRevokedAccessTokenHeaderExists = true; // indicates a successful revocation
                break;
            }
        }
    }

    if(isRevokedAccessTokenHeaderExists) {
        String revokedToken = revokeRequestDTO.getToken();
        Long expiryTime = 0L;
        boolean isJwtToken = false;
        if (revokedToken.contains(APIConstants.DOT) && APIUtil.isValidJWT(revokedToken)) {
             expiryTime = APIUtil.getExpiryifJWT(revokedToken);
             isJwtToken = true;
        }
        revocationRequestPublisher.publishRevocationEvents(revokedToken, expiryTime, null);
        if (isJwtToken) {
            // Persist revoked JWT token to database.
            persistRevokedJWTSignature(revokedToken, expiryTime);
        }
    }

}
 
Example #11
Source File: AbstractAuthorizationGrantHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected void storeAccessToken(OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO, String userStoreDomain,
                                AccessTokenDO newAccessTokenDO, String newAccessToken, AccessTokenDO
                                        existingAccessTokenDO) throws IdentityOAuth2Exception {
    try {
        tokenMgtDAO.storeAccessToken(newAccessToken, oAuth2AccessTokenReqDTO.getClientId(),
                                     newAccessTokenDO, existingAccessTokenDO, userStoreDomain);
    } catch (IdentityException e) {
        throw new IdentityOAuth2Exception(
                "Error occurred while storing new access token : " + newAccessToken, e);
    }
}
 
Example #12
Source File: AuthorizationCodeGrantHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
protected void storeAccessToken(OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO, String userStoreDomain,
                                AccessTokenDO newAccessTokenDO, String newAccessToken, AccessTokenDO
                                            existingAccessTokenDO)
        throws IdentityOAuth2Exception {
    try {
        newAccessTokenDO.setAuthorizationCode(oAuth2AccessTokenReqDTO.getAuthorizationCode());
        tokenMgtDAO.storeAccessToken(newAccessToken, oAuth2AccessTokenReqDTO.getClientId(),
                                     newAccessTokenDO, existingAccessTokenDO, userStoreDomain);
    } catch (IdentityException e) {
        throw new IdentityOAuth2Exception(
                "Error occurred while storing new access token", e);
    }
}
 
Example #13
Source File: DefaultOAuth2TokenValidator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateScope(OAuth2TokenValidationMessageContext messageContext)
        throws IdentityOAuth2Exception {

    OAuth2ScopeValidator scopeValidator = OAuthServerConfiguration.getInstance().getoAuth2ScopeValidator();

    //If a scope validator is engaged through the configuration
    if (scopeValidator != null && messageContext.getRequestDTO() != null &&
        messageContext.getRequestDTO().getContext() != null) {
        
        String resource = null;

        //Iterate the array of context params to find the 'resource' context param.
        for (OAuth2TokenValidationRequestDTO.TokenValidationContextParam resourceParam :
                messageContext.getRequestDTO().getContext()) {
            //If the context param is the resource that is being accessed
            if (resourceParam != null && "resource".equals(resourceParam.getKey())) {
                resource = resourceParam.getValue();
                break;
            }
        }

        //Return True if there is no resource to validate the token against
        //OR if the token has a valid scope to access the resource. False otherwise.
        return resource == null ||
                scopeValidator.validateScope((AccessTokenDO) messageContext.getProperty("AccessTokenDO"), resource);
    }
    return true;
}
 
Example #14
Source File: AccessContextTokenDO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public AccessContextTokenDO(String accessToken, String consumerKey, AccessTokenDO newAccessTokenDO, AccessTokenDO
        existingAccessTokenDO, String userStoreDomain) {
    this.accessToken = accessToken;
    this.consumerKey = consumerKey;
    this.newAccessTokenDO = newAccessTokenDO;
    this.existingAccessTokenDO = existingAccessTokenDO;
    this.userStoreDomain = userStoreDomain;
}
 
Example #15
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used invalidate the existing token and generate a new toke within one DB transaction.
 *
    * @param oldAccessTokenId     access token need to be updated.
    * @param tokenState      token state before generating new token.
 * @param consumerKey     consumer key of the existing token
 * @param tokenStateId    new token state id to be updated
 * @param accessTokenDO   new access token details
 * @param userStoreDomain user store domain which is related to this consumer
 * @throws IdentityOAuth2Exception
 */
   public void invalidateAndCreateNewToken(String oldAccessTokenId, String tokenState,
                                           String consumerKey, String tokenStateId,
                                        AccessTokenDO accessTokenDO, String userStoreDomain)
		throws IdentityOAuth2Exception {

       Connection connection = IdentityDatabaseUtil.getDBConnection();
	try {
		connection.setAutoCommit(false);

		// update existing token as inactive
           setAccessTokenState(connection, oldAccessTokenId, tokenState, tokenStateId, userStoreDomain);

           String newAccessToken = accessTokenDO.getAccessToken();
           // store new token in the DB
           storeAccessToken(newAccessToken, consumerKey, accessTokenDO, connection,
                   userStoreDomain);

           // update new access token against authorization code if token obtained via authorization code grant type
           updateTokenIdIfAutzCodeGrantType(oldAccessTokenId, accessTokenDO.getTokenId(), connection);

		// commit both transactions
		connection.commit();
	} catch (SQLException e) {
		String errorMsg = "Error while regenerating access token";
		throw new IdentityOAuth2Exception(errorMsg, e);
	} finally {
		IdentityDatabaseUtil.closeConnection(connection);
	}
}
 
Example #16
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public boolean persistAccessToken(String accessToken, String consumerKey,
                                  AccessTokenDO newAccessTokenDO, AccessTokenDO existingAccessTokenDO,
                                  String userStoreDomain) throws IdentityOAuth2Exception {
    if (!enablePersist) {
        return false;
    }
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    try {
        if (existingAccessTokenDO != null) {
            //  Mark the existing access token as expired on database if a token exist for the user
            setAccessTokenState(connection, existingAccessTokenDO.getTokenId(), OAuthConstants.TokenStates
                    .TOKEN_STATE_EXPIRED, UUID.randomUUID().toString(), userStoreDomain);
        }

        if (newAccessTokenDO.getAuthorizationCode() != null) {
            storeAccessToken(accessToken, consumerKey, newAccessTokenDO, connection, userStoreDomain);
            // expire authz code and insert issued access token against authz code
            AuthzCodeDO authzCodeDO = new AuthzCodeDO();
            authzCodeDO.setAuthorizationCode(newAccessTokenDO.getAuthorizationCode());
            authzCodeDO.setOauthTokenId(newAccessTokenDO.getTokenId());
            List<AuthzCodeDO> authzCodeDOList = new ArrayList<>(Arrays.asList(authzCodeDO));
            deactivateAuthorizationCode(authzCodeDOList);
        } else {
            storeAccessToken(accessToken, consumerKey, newAccessTokenDO, connection, userStoreDomain);
        }
        connection.commit();
        return true;
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error occurred while persisting access token", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, null);
    }
}
 
Example #17
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void storeAccessToken(String accessToken, String consumerKey, AccessTokenDO newAccessTokenDO,
                             AccessTokenDO existingAccessTokenDO, String userStoreDomain)
        throws IdentityException {

    if (!enablePersist) {
        return;
    }
    if (maxPoolSize > 0) {
        accessContextTokenQueue.push(new AccessContextTokenDO(accessToken, consumerKey, newAccessTokenDO
                , existingAccessTokenDO, userStoreDomain));
    } else {
        persistAccessToken(accessToken, consumerKey, newAccessTokenDO, existingAccessTokenDO, userStoreDomain);
    }
}
 
Example #18
Source File: OAuthCacheRemoveListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void entryRemoved(CacheEntryEvent<? extends OAuthCacheKey, ? extends CacheEntry> cacheEntryEvent)
        throws CacheEntryListenerException {

    CacheEntry cacheEntry = cacheEntryEvent.getValue();
    if(cacheEntry == null || !(cacheEntry instanceof AccessTokenDO)){
        return;
    }
    AccessTokenDO accessTokenDO = (AccessTokenDO) cacheEntryEvent.getValue();

    if (accessTokenDO != null) {

        if (log.isDebugEnabled()) {
            log.debug("OAuth cache removed for consumer id : " + accessTokenDO.getConsumerKey());
        }

        boolean isUsernameCaseSensitive = IdentityUtil
                .isUserStoreInUsernameCaseSensitive(accessTokenDO.getAuthzUser().getUserName());
        String cacheKeyString;
        if (isUsernameCaseSensitive){
            cacheKeyString = accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser().getUserName() + ":"
                    + OAuth2Util.buildScopeString(accessTokenDO.getScope());
        }else {
            cacheKeyString =
                    accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser().getUserName().toLowerCase()
                            + ":" + OAuth2Util.buildScopeString(accessTokenDO.getScope());
        }

        OAuthCacheKey oauthcacheKey = new OAuthCacheKey(cacheKeyString);
        OAuthCache oauthCache = OAuthCache.getInstance();

        oauthCache.clearCacheEntry(oauthcacheKey);
        oauthcacheKey = new OAuthCacheKey(accessTokenDO.getAccessToken());

        oauthCache.clearCacheEntry(oauthcacheKey);

    }
}
 
Example #19
Source File: ScopeValidationHandler.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
public boolean validateScope(AccessTokenDO accessTokenDO, String resource) throws IdentityOAuth2Exception {

        //returns true if scope validators are not defined
        if (scopeValidators == null || scopeValidators.isEmpty()) {
            if(log.isDebugEnabled()){
                log.debug("OAuth2 scope validators are not loaded");
            }
            return true;
        }

        String resourceScope = getResourceScope(resource);

        //returns true if scope does not exist for the resource
        if (resourceScope == null) {
            if(log.isDebugEnabled()){
                log.debug("Resource '" + resource + "' is not protected with a scope");
            }
            return true;
        }

        String scope[] = resourceScope.split(":");
        String scopePrefix = scope[0];

        OAuth2ScopeValidator scopeValidator = scopeValidators.get(scopePrefix);

        if (scopeValidator == null) {
            if(log.isDebugEnabled()){
                log.debug("OAuth2 scope validator cannot be identified for '" + scopePrefix + "' scope prefix");
            }

            // loading default scope validator if matching validator is not found
            scopeValidator = scopeValidators.get(DEFAULT_PREFIX);
            if(log.isDebugEnabled()){
                log.debug("Loading default scope validator");
            }

            if (scopeValidator == null) {
                if(log.isDebugEnabled()){
                    log.debug("Default scope validator is not available");
                }
                return true;
            }
        }

        // validate scope via relevant scope validator that matches with the prefix
        return scopeValidator.validateScope(accessTokenDO, resource);
    }
 
Example #20
Source File: OAuthUserStoreConfigListenerImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onUserStorePreDelete(int tenantId, String userStoreName) throws UserStoreException {
    TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
    try {
        Set<AccessTokenDO> accessTokenDOs = tokenMgtDAO.getAccessTokensOfUserStore(tenantId, userStoreName);
        Map<String, AccessTokenDO> latestAccessTokens = new HashMap<>();
        for (AccessTokenDO accessTokenDO : accessTokenDOs) {
            String keyString = accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser() + ":" +
                    OAuth2Util.buildScopeString(accessTokenDO.getScope());
            AccessTokenDO accessTokenDOFromMap = latestAccessTokens.get(keyString);
            if (accessTokenDOFromMap != null) {
                if (accessTokenDOFromMap.getIssuedTime().before(accessTokenDO.getIssuedTime())) {
                    latestAccessTokens.put(keyString, accessTokenDO);
                }
            } else {
                latestAccessTokens.put(keyString, accessTokenDO);
            }

            //Clear cache
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser(),
                    OAuth2Util.buildScopeString(accessTokenDO.getScope()));
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser());
            OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
        }
        ArrayList<String> tokensToRevoke = new ArrayList<>();
        for (Map.Entry entry : latestAccessTokens.entrySet()) {
            tokensToRevoke.add(((AccessTokenDO) entry.getValue()).getAccessToken());
        }
        tokenMgtDAO.revokeTokens(tokensToRevoke.toArray(new String[tokensToRevoke.size()]));
        List<AuthzCodeDO> latestAuthzCodes = tokenMgtDAO.getLatestAuthorizationCodesOfUserStore(tenantId,
                userStoreName);
        for (AuthzCodeDO authzCodeDO : latestAuthzCodes) {
            // remove the authorization code from the cache
            OAuthUtil.clearOAuthCache(authzCodeDO.getConsumerKey() + ":" + authzCodeDO.getAuthorizationCode());

        }
        tokenMgtDAO.deactivateAuthorizationCode(latestAuthzCodes);
    } catch (IdentityOAuth2Exception e) {
        throw new UserStoreException("Error occurred while revoking Access Token of user store : " +
                userStoreName + " in tenant :" + tenantId, e);
    }
}
 
Example #21
Source File: OAuthTenantMgtListenerImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onPreDelete(int tenantId) throws StratosException {
    TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
    try {
        Set<AccessTokenDO> accessTokenDOs = tokenMgtDAO.getAccessTokensOfTenant(tenantId);
        Map<String, AccessTokenDO> latestAccessTokens = new HashMap<>();
        for (AccessTokenDO accessTokenDO : accessTokenDOs) {
            String keyString = accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser() + ":" +
                    OAuth2Util.buildScopeString(accessTokenDO.getScope());
            AccessTokenDO accessTokenDOFromMap = latestAccessTokens.get(keyString);
            if (accessTokenDOFromMap != null) {
                if (accessTokenDOFromMap.getIssuedTime().before(accessTokenDO.getIssuedTime())) {
                    latestAccessTokens.put(keyString, accessTokenDO);
                }
            } else {
                latestAccessTokens.put(keyString, accessTokenDO);
            }

            //Clear cache
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser(),
                    OAuth2Util.buildScopeString(accessTokenDO.getScope()));
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser());
            OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
        }
        ArrayList<String> tokensToRevoke = new ArrayList<>();
        for (Map.Entry entry : latestAccessTokens.entrySet()) {
            tokensToRevoke.add(((AccessTokenDO) entry.getValue()).getAccessToken());
        }
        tokenMgtDAO.revokeTokens(tokensToRevoke.toArray(new String[tokensToRevoke.size()]));
        List<AuthzCodeDO> latestAuthzCodes = tokenMgtDAO.getLatestAuthorizationCodesOfTenant(tenantId);
        for (AuthzCodeDO authzCodeDO : latestAuthzCodes) {
            // remove the authorization code from the cache
            OAuthUtil.clearOAuthCache(authzCodeDO.getConsumerKey() + ":" +
                    authzCodeDO.getAuthorizationCode());

        }
        tokenMgtDAO.deactivateAuthorizationCode(latestAuthzCodes);
    } catch (IdentityOAuth2Exception e) {
        throw new StratosException("Error occurred while revoking the access tokens in tenant " + tenantId, e);
    }
}
 
Example #22
Source File: TokenValidationHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
    * 
    * @param accessTokenDO
    * @return
    */
   private String getAuthzUser(AccessTokenDO accessTokenDO) {
User user = accessTokenDO.getAuthzUser();
String authzUser = UserCoreUtil.addDomainToName(user.getUserName(), user.getUserStoreDomain());
return UserCoreUtil.addTenantDomainToEntry(authzUser, user.getTenantDomain());
   }
 
Example #23
Source File: RefreshGrantHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    if(!super.validateGrant(tokReqMsgCtx)){
        return false;
    }

    OAuth2AccessTokenReqDTO tokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();

    String refreshToken = tokenReqDTO.getRefreshToken();

    RefreshTokenValidationDataDO validationDataDO = tokenMgtDAO.validateRefreshToken(
            tokenReqDTO.getClientId(), refreshToken);

    if (validationDataDO.getAccessToken() == null) {
        log.debug("Invalid Refresh Token provided for Client with " +
                "Client Id : " + tokenReqDTO.getClientId());
        return false;
    }

    if (validationDataDO.getRefreshTokenState() != null &&
            !OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(
                    validationDataDO.getRefreshTokenState()) &&
            !OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED.equals(
                    validationDataDO.getRefreshTokenState())) {
        if(log.isDebugEnabled()) {
            log.debug("Access Token is not in 'ACTIVE' or 'EXPIRED' state for Client with " +
                    "Client Id : " + tokenReqDTO.getClientId());
        }
        return false;
    }

    String userStoreDomain = null;
    if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) {
        try {
            userStoreDomain = OAuth2Util.getUserStoreDomainFromUserId(validationDataDO.getAuthorizedUser().toString());
        } catch (IdentityOAuth2Exception e) {
            String errorMsg = "Error occurred while getting user store domain for User ID : " + validationDataDO.getAuthorizedUser();
            log.error(errorMsg, e);
            throw new IdentityOAuth2Exception(errorMsg, e);
        }
    }

    AccessTokenDO accessTokenDO = tokenMgtDAO.retrieveLatestAccessToken(tokenReqDTO.getClientId(),
            validationDataDO.getAuthorizedUser(),
            userStoreDomain, OAuth2Util.buildScopeString(validationDataDO.getScope()), true);

    if (accessTokenDO == null){
        if(log.isDebugEnabled()){
            log.debug("Error while retrieving the latest refresh token");
        }
        return false;
    }else if(!refreshToken.equals(accessTokenDO.getRefreshToken())){
        if(log.isDebugEnabled()){
            log.debug("Refresh token is not the latest.");
        }
        return false;
    }

    if (log.isDebugEnabled()) {
        log.debug("Refresh token validation successful for " +
                "Client id : " + tokenReqDTO.getClientId() +
                ", Authorized User : " + validationDataDO.getAuthorizedUser() +
                ", Token Scope : " + OAuth2Util.buildScopeString(validationDataDO.getScope()));
    }

    tokReqMsgCtx.setAuthorizedUser(validationDataDO.getAuthorizedUser());
    tokReqMsgCtx.setScope(validationDataDO.getScope());
    // Store the old access token as a OAuthTokenReqMessageContext property, this is already
    // a preprocessed token.
    tokReqMsgCtx.addProperty(PREV_ACCESS_TOKEN, validationDataDO);
    return true;
}
 
Example #24
Source File: AccessContextTokenDO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public AccessTokenDO getExistingAccessTokenDO() {
    return existingAccessTokenDO;
}
 
Example #25
Source File: AccessContextTokenDO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public AccessTokenDO getNewAccessTokenDO() {
    return newAccessTokenDO;
}
 
Example #26
Source File: OAuth2ScopeValidator.java    From carbon-identity with Apache License 2.0 2 votes vote down vote up
/**
 * Method to validate the scopes associated with the access token against the resource that is being accessed.
 *
 * @param accessTokenDO - The access token data object
 * @param resource      - The resource that is being accessed.
 * @return - true if scope is valid, false otherwise
 * @throws IdentityOAuth2Exception
 */
public abstract boolean validateScope(AccessTokenDO accessTokenDO, String resource) throws IdentityOAuth2Exception;