Search in sources :

Example 1 with RefreshTokenValidationDataDO

use of org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2Service method invokePostRevocationListeners.

private void invokePostRevocationListeners(OAuthRevocationRequestDTO revokeRequestDTO, OAuthRevocationResponseDTO revokeResponseDTO, AccessTokenDO accessTokenDO, RefreshTokenValidationDataDO refreshTokenDO) {
    OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy();
    if (oAuthEventInterceptorProxy != null && oAuthEventInterceptorProxy.isEnabled()) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            oAuthEventInterceptorProxy.onPostTokenRevocationByClient(revokeRequestDTO, revokeResponseDTO, accessTokenDO, refreshTokenDO, paramMap);
        } catch (IdentityOAuth2Exception e) {
            log.error("Error occurred when invoking post token revoke listener ", e);
        }
    }
}
Also used : HashMap(java.util.HashMap) OAuthEventInterceptor(org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor)

Example 2 with RefreshTokenValidationDataDO

use of org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO in project identity-inbound-auth-oauth by wso2-extensions.

the class TokenManagementDAOImpl method validateRefreshToken.

@Override
public RefreshTokenValidationDataDO validateRefreshToken(String consumerKey, String refreshToken) throws IdentityOAuth2Exception {
    if (log.isDebugEnabled()) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.REFRESH_TOKEN)) {
            log.debug("Validating refresh token(hashed): " + DigestUtils.sha256Hex(refreshToken) + " client: " + consumerKey);
        } else {
            log.debug("Validating refresh token for client: " + consumerKey);
        }
    }
    RefreshTokenValidationDataDO validationDataDO = new RefreshTokenValidationDataDO();
    Connection connection = IdentityDatabaseUtil.getDBConnection(false);
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;
    String sql;
    try {
        String driverName = connection.getMetaData().getDriverName();
        if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
            if (driverName.contains("MySQL") || driverName.contains("MariaDB") || driverName.contains("H2")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_IDP_NAME_MYSQL;
            } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_IDP_NAME_DB2SQL;
            } else if (driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_IDP_NAME_MSSQL;
            } else if (driverName.contains("PostgreSQL")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_IDP_NAME_POSTGRESQL;
            } else if (driverName.contains("INFORMIX")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_IDP_NAME_INFORMIX;
            } else {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_IDP_NAME_ORACLE;
            }
        } else {
            if (driverName.contains("MySQL") || driverName.contains("MariaDB") || driverName.contains("H2")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_MYSQL;
            } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_DB2SQL;
            } else if (driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_MSSQL;
            } else if (driverName.contains("PostgreSQL")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_POSTGRESQL;
            } else if (driverName.contains("INFORMIX")) {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_INFORMIX;
            } else {
                sql = SQLQueries.RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_ORACLE;
            }
        }
        sql = OAuth2Util.getTokenPartitionedSqlByToken(sql, refreshToken);
        if (refreshToken == null) {
            sql = sql.replace("REFRESH_TOKEN = ?", "REFRESH_TOKEN IS NULL");
        }
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setString(1, getPersistenceProcessor().getProcessedClientId(consumerKey));
        if (refreshToken != null) {
            prepStmt.setString(2, getHashingPersistenceProcessor().getProcessedRefreshToken(refreshToken));
        }
        resultSet = prepStmt.executeQuery();
        int iterateId = 0;
        List<String> scopes = new ArrayList<>();
        while (resultSet.next()) {
            if (iterateId == 0) {
                if (isHashDisabled) {
                    validationDataDO.setAccessToken(getPersistenceProcessor().getPreprocessedAccessTokenIdentifier(resultSet.getString(1)));
                } else {
                    validationDataDO.setAccessToken(resultSet.getString(1));
                }
                String userName = resultSet.getString(2);
                int tenantId = resultSet.getInt(3);
                String userDomain = resultSet.getString(4);
                String tenantDomain = OAuth2Util.getTenantDomain(tenantId);
                validationDataDO.setScope(OAuth2Util.buildScopeArray(resultSet.getString(5)));
                validationDataDO.setRefreshTokenState(resultSet.getString(6));
                validationDataDO.setIssuedTime(resultSet.getTimestamp(7, Calendar.getInstance(TimeZone.getTimeZone(UTC))));
                validationDataDO.setValidityPeriodInMillis(resultSet.getLong(8));
                validationDataDO.setTokenId(resultSet.getString(9));
                validationDataDO.setGrantType(resultSet.getString(10));
                String subjectIdentifier = resultSet.getString(11);
                validationDataDO.setTokenBindingReference(resultSet.getString(12));
                validationDataDO.setAccessTokenIssuedTime(resultSet.getTimestamp(13, Calendar.getInstance(TimeZone.getTimeZone(UTC))));
                validationDataDO.setAccessTokenValidityInMillis(resultSet.getLong(14));
                String authenticatedIDP = null;
                if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                    authenticatedIDP = resultSet.getString(15);
                }
                AuthenticatedUser user = OAuth2Util.createAuthenticatedUser(userName, userDomain, tenantDomain, authenticatedIDP);
                user.setAuthenticatedSubjectIdentifier(subjectIdentifier);
                validationDataDO.setAuthorizedUser(user);
            } else {
                scopes.add(resultSet.getString(5));
            }
            iterateId++;
        }
        if (scopes.size() > 0 && validationDataDO != null) {
            validationDataDO.setScope((String[]) ArrayUtils.addAll(validationDataDO.getScope(), scopes.toArray(new String[scopes.size()])));
        }
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error when validating a refresh token", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }
    return validationDataDO;
}
Also used : RefreshTokenValidationDataDO(org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 3 with RefreshTokenValidationDataDO

use of org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO in project identity-inbound-auth-oauth by wso2-extensions.

the class RefreshGrantHandler method persistNewToken.

private void persistNewToken(OAuthTokenReqMessageContext tokReqMsgCtx, AccessTokenDO accessTokenBean, String clientId) throws IdentityOAuth2Exception {
    String userStoreDomain = getUserStoreDomain(tokReqMsgCtx.getAuthorizedUser());
    RefreshTokenValidationDataDO oldAccessToken = (RefreshTokenValidationDataDO) tokReqMsgCtx.getProperty(PREV_ACCESS_TOKEN);
    if (log.isDebugEnabled()) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Previous access token (hashed): " + DigestUtils.sha256Hex(oldAccessToken.getAccessToken()));
        }
    }
    // set the previous access token state to "INACTIVE" and store new access token in single db connection
    OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().invalidateAndCreateNewAccessToken(oldAccessToken.getTokenId(), OAuthConstants.TokenStates.TOKEN_STATE_INACTIVE, clientId, UUID.randomUUID().toString(), accessTokenBean, userStoreDomain, oldAccessToken.getGrantType());
    updateCacheIfEnabled(tokReqMsgCtx, accessTokenBean, clientId, oldAccessToken);
}
Also used : RefreshTokenValidationDataDO(org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO)

Example 4 with RefreshTokenValidationDataDO

use of org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO in project identity-inbound-auth-oauth by wso2-extensions.

the class RefreshGrantHandler method issue.

@Override
public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    OAuth2AccessTokenReqDTO tokenReq = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
    // An active or expired token will be returned. Since we do the validation for active or expired token in
    // validateGrant() no need to do it here again also no need to read it from DB again. Simply get it from
    // context property.
    RefreshTokenValidationDataDO validationBean = (RefreshTokenValidationDataDO) tokReqMsgCtx.getProperty(PREV_ACCESS_TOKEN);
    if (isRefreshTokenExpired(validationBean)) {
        return handleError(OAuth2ErrorCodes.INVALID_GRANT, "Refresh token is expired.", tokenReq);
    }
    AccessTokenDO accessTokenBean = createAccessTokenBean(tokReqMsgCtx, tokenReq, validationBean);
    persistNewToken(tokReqMsgCtx, accessTokenBean, tokenReq.getClientId());
    if (log.isDebugEnabled()) {
        log.debug("Persisted an access token for the refresh token, " + "Client ID : " + tokenReq.getClientId() + ", Authorized user : " + tokReqMsgCtx.getAuthorizedUser() + ", Timestamp : " + accessTokenBean.getIssuedTime() + ", Validity period (s) : " + accessTokenBean.getValidityPeriod() + ", Scope : " + OAuth2Util.buildScopeString(tokReqMsgCtx.getScope()) + ", Token State : " + OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE + " and User Type : " + getTokenType());
    }
    setTokenDataToMessageContext(tokReqMsgCtx, accessTokenBean);
    addUserAttributesToCache(accessTokenBean, tokReqMsgCtx);
    return buildTokenResponse(tokReqMsgCtx, accessTokenBean);
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) RefreshTokenValidationDataDO(org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)

Example 5 with RefreshTokenValidationDataDO

use of org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO in project identity-inbound-auth-oauth by wso2-extensions.

the class RefreshGrantHandler method validateTokenBindingReference.

private void validateTokenBindingReference(OAuth2AccessTokenReqDTO tokenReqDTO, RefreshTokenValidationDataDO validationDataDO) throws IdentityOAuth2Exception {
    if (StringUtils.isBlank(validationDataDO.getTokenBindingReference()) || NONE.equals(validationDataDO.getTokenBindingReference())) {
        return;
    }
    OAuthAppDO oAuthAppDO;
    try {
        oAuthAppDO = OAuth2Util.getAppInformationByClientId(tokenReqDTO.getClientId());
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Failed load the application with client id: " + tokenReqDTO.getClientId());
    }
    if (StringUtils.isBlank(oAuthAppDO.getTokenBindingType())) {
        return;
    }
    Optional<TokenBinder> tokenBinderOptional = OAuth2ServiceComponentHolder.getInstance().getTokenBinder(oAuthAppDO.getTokenBindingType());
    if (!tokenBinderOptional.isPresent()) {
        throw new IdentityOAuth2Exception("Token binder for the binding type: " + oAuthAppDO.getTokenBindingType() + " is not registered.");
    }
    TokenBinder tokenBinder = tokenBinderOptional.get();
    if ((oAuthAppDO.isTokenBindingValidationEnabled()) && !tokenBinder.isValidTokenBinding(tokenReqDTO, validationDataDO.getTokenBindingReference())) {
        throw new IdentityOAuth2Exception("Invalid token binding value is present in the request.");
    }
}
Also used : OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) TokenBinder(org.wso2.carbon.identity.oauth2.token.bindings.TokenBinder)

Aggregations

RefreshTokenValidationDataDO (org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO)10 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)4 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)4 HashMap (java.util.HashMap)3 Test (org.testng.annotations.Test)3 AuthorizationGrantCacheEntry (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry)3 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)3 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)2 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)2 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)2 AuthorizationGrantCacheKey (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey)2 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)2 OAuthEventInterceptor (org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor)2 OAuthClientAuthnContext (org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext)2 OAuthTokenReqMessageContext (org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1