Search in sources :

Example 1 with OauthTokenIssuer

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

the class UserInfoResponseBaseTest method mockObjectsRelatedToTokenValidation.

protected void mockObjectsRelatedToTokenValidation() throws Exception {
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(OAuthServerConfiguration.getInstance().getOAuthTokenGenerator()).thenReturn(oAuthIssuer);
    when(OAuthServerConfiguration.getInstance().getSignatureAlgorithm()).thenReturn("SHA256withRSA");
    when(OAuth2Util.getAccessTokenIdentifier(any())).thenCallRealMethod();
    when(OAuth2Util.findAccessToken(anyString(), anyBoolean())).thenCallRealMethod();
    when(OAuth2Util.class, "getAccessTokenDOFromMatchingTokenIssuer", anyString(), anyMap(), anyBoolean()).thenCallRealMethod();
    AccessTokenDO accessTokenDO = new AccessTokenDO();
    accessTokenDO.setAccessToken(accessToken);
    when(OAuth2Util.getAccessTokenDOFromTokenIdentifier(anyString(), anyBoolean())).thenReturn(accessTokenDO);
    Map<String, OauthTokenIssuer> oauthTokenIssuerMap = new HashMap<>();
    oauthTokenIssuerMap.put(DEFAULT_TOKEN_TYPE, new OauthTokenIssuerImpl());
    oauthTokenIssuerMap.put(JWT_TOKEN_TYPE, new JWTTokenIssuer());
    when(OAuthServerConfiguration.getInstance().getOauthTokenIssuerMap()).thenReturn(oauthTokenIssuerMap);
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) JWTTokenIssuer(org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer) HashMap(java.util.HashMap) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) OauthTokenIssuerImpl(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuerImpl) Matchers.anyString(org.mockito.Matchers.anyString)

Example 2 with OauthTokenIssuer

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

the class AccessTokenDAOImpl method insertAccessToken.

private void insertAccessToken(String accessToken, String consumerKey, AccessTokenDO accessTokenDO, Connection connection, String userStoreDomain, int retryAttemptCounter) throws IdentityOAuth2Exception {
    if (!isPersistenceEnabled()) {
        return;
    }
    if (accessTokenDO == null) {
        throw new IdentityOAuth2Exception("Access token data object should be available for further execution.");
    }
    if (accessTokenDO.getAuthzUser() == null) {
        throw new IdentityOAuth2Exception("Authorized user should be available for further execution.");
    }
    String accessTokenHash = accessToken;
    try {
        OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey);
        // check for persist alias for the token type
        if (oauthTokenIssuer.usePersistedAccessTokenAlias()) {
            accessTokenHash = oauthTokenIssuer.getAccessTokenHash(accessToken);
        }
    } catch (OAuthSystemException e) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Error while getting access token hash for token(hashed): " + DigestUtils.sha256Hex(accessTokenHash));
        }
        throw new IdentityOAuth2Exception("Error while getting access token hash.", e);
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Error while retrieving oauth issuer for the app with clientId: " + consumerKey, e);
    }
    if (log.isDebugEnabled()) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Persisting access token(hashed): " + DigestUtils.sha256Hex(accessTokenHash) + " for " + "client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().getLoggableUserId() + " scope: " + Arrays.toString(accessTokenDO.getScope()));
        } else {
            log.debug("Persisting access token for client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().getLoggableUserId() + " scope: " + Arrays.toString(accessTokenDO.getScope()));
        }
    }
    userStoreDomain = OAuth2Util.getSanitizedUserStoreDomain(userStoreDomain);
    String userDomain = OAuth2Util.getUserStoreDomain(accessTokenDO.getAuthzUser());
    String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(accessTokenDO.getAuthzUser());
    PreparedStatement insertTokenPrepStmt = null;
    PreparedStatement addScopePrepStmt = null;
    if (log.isDebugEnabled()) {
        String username;
        if (isFederatedUser(accessTokenDO)) {
            username = accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier();
        } else {
            username = accessTokenDO.getAuthzUser().toFullQualifiedUsername();
        }
        log.debug("Userstore domain for user: " + username + " is " + userDomain);
    }
    String sql;
    if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
        sql = SQLQueries.INSERT_OAUTH2_ACCESS_TOKEN_WITH_IDP_NAME;
    } else {
        sql = SQLQueries.INSERT_OAUTH2_ACCESS_TOKEN;
    }
    sql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userDomain);
    String sqlAddScopes = OAuth2Util.getTokenPartitionedSqlByUserStore(SQLQueries.INSERT_OAUTH2_TOKEN_SCOPE, userDomain);
    try {
        insertTokenPrepStmt = connection.prepareStatement(sql);
        insertTokenPrepStmt.setString(1, getPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenHash));
        if (accessTokenDO.getRefreshToken() != null) {
            insertTokenPrepStmt.setString(2, getPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken()));
        } else {
            insertTokenPrepStmt.setString(2, accessTokenDO.getRefreshToken());
        }
        insertTokenPrepStmt.setString(3, accessTokenDO.getAuthzUser().getUserName());
        int tenantId = OAuth2Util.getTenantId(accessTokenDO.getAuthzUser().getTenantDomain());
        insertTokenPrepStmt.setInt(4, tenantId);
        insertTokenPrepStmt.setString(5, OAuth2Util.getSanitizedUserStoreDomain(userDomain));
        insertTokenPrepStmt.setTimestamp(6, accessTokenDO.getIssuedTime(), Calendar.getInstance(TimeZone.getTimeZone(UTC)));
        insertTokenPrepStmt.setTimestamp(7, accessTokenDO.getRefreshTokenIssuedTime(), Calendar.getInstance(TimeZone.getTimeZone(UTC)));
        insertTokenPrepStmt.setLong(8, accessTokenDO.getValidityPeriodInMillis());
        insertTokenPrepStmt.setLong(9, accessTokenDO.getRefreshTokenValidityPeriodInMillis());
        insertTokenPrepStmt.setString(10, OAuth2Util.hashScopes(accessTokenDO.getScope()));
        insertTokenPrepStmt.setString(11, accessTokenDO.getTokenState());
        insertTokenPrepStmt.setString(12, accessTokenDO.getTokenType());
        insertTokenPrepStmt.setString(13, accessTokenDO.getTokenId());
        insertTokenPrepStmt.setString(14, accessTokenDO.getGrantType());
        insertTokenPrepStmt.setString(15, accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier());
        insertTokenPrepStmt.setString(16, getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenHash));
        if (accessTokenDO.getRefreshToken() != null) {
            insertTokenPrepStmt.setString(17, getHashingPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken()));
        } else {
            insertTokenPrepStmt.setString(17, accessTokenDO.getRefreshToken());
        }
        boolean tokenBindingAvailable = isTokenBindingAvailable(accessTokenDO.getTokenBinding());
        if (tokenBindingAvailable) {
            insertTokenPrepStmt.setString(18, accessTokenDO.getTokenBinding().getBindingReference());
        } else {
            insertTokenPrepStmt.setString(18, NONE);
        }
        insertTokenPrepStmt.setString(19, getPersistenceProcessor().getProcessedClientId(consumerKey));
        if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
            insertTokenPrepStmt.setString(20, authenticatedIDP);
            insertTokenPrepStmt.setInt(21, tenantId);
        }
        insertTokenPrepStmt.execute();
        String accessTokenId = accessTokenDO.getTokenId();
        addScopePrepStmt = connection.prepareStatement(sqlAddScopes);
        if (accessTokenDO.getScope() != null && accessTokenDO.getScope().length > 0) {
            for (String scope : accessTokenDO.getScope()) {
                addScopePrepStmt.setString(1, accessTokenId);
                addScopePrepStmt.setString(2, scope);
                addScopePrepStmt.setInt(3, tenantId);
                addScopePrepStmt.addBatch();
            }
        }
        addScopePrepStmt.executeBatch();
        if (tokenBindingAvailable) {
            if (log.isDebugEnabled()) {
                log.debug("Storing token binding information" + " accessTokenId: " + accessTokenId + " bindingType: " + accessTokenDO.getTokenBinding().getBindingType() + " bindingRef: " + accessTokenDO.getTokenBinding().getBindingReference());
            }
            try (PreparedStatement preparedStatement = connection.prepareStatement(STORE_TOKEN_BINDING)) {
                preparedStatement.setString(1, accessTokenId);
                preparedStatement.setString(2, accessTokenDO.getTokenBinding().getBindingType());
                preparedStatement.setString(3, accessTokenDO.getTokenBinding().getBindingReference());
                preparedStatement.setString(4, accessTokenDO.getTokenBinding().getBindingValue());
                preparedStatement.setInt(5, tenantId);
                preparedStatement.execute();
            }
        }
        if (retryAttemptCounter > 0) {
            log.info("Successfully recovered 'CON_APP_KEY' constraint violation with the attempt : " + retryAttemptCounter);
        }
    } catch (SQLIntegrityConstraintViolationException e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        if (retryAttemptCounter >= getTokenPersistRetryCount()) {
            log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - " + getTokenPersistRetryCount());
            String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : " + accessTokenDO.getAuthzUser() + " and scope : " + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists";
            throw new IdentityOAuth2Exception(errorMsg, e);
        }
        recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter + 1);
    } catch (DataTruncation e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        throw new IdentityOAuth2Exception("Invalid request", e);
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        // SQLIntegrityConstraintViolationException
        if (StringUtils.containsIgnoreCase(e.getMessage(), "CON_APP_KEY")) {
            if (retryAttemptCounter >= getTokenPersistRetryCount()) {
                log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - " + getTokenPersistRetryCount());
                String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : " + accessTokenDO.getAuthzUser() + " and scope : " + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists";
                throw new IdentityOAuth2Exception(errorMsg, e);
            }
            recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter + 1);
        } else {
            throw new IdentityOAuth2Exception("Error when storing the access token for consumer key : " + consumerKey, e);
        }
    } catch (Exception e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        // SQLIntegrityConstraintViolationException or SQLException.
        if (StringUtils.containsIgnoreCase(e.getMessage(), "CON_APP_KEY") || (e.getCause() != null && StringUtils.containsIgnoreCase(e.getCause().getMessage(), "CON_APP_KEY")) || (e.getCause() != null && e.getCause().getCause() != null && StringUtils.containsIgnoreCase(e.getCause().getCause().getMessage(), "CON_APP_KEY"))) {
            if (retryAttemptCounter >= getTokenPersistRetryCount()) {
                log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - " + getTokenPersistRetryCount());
                String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : " + accessTokenDO.getAuthzUser() + " and scope : " + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists";
                throw new IdentityOAuth2Exception(errorMsg, e);
            }
            recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter + 1);
        } else {
            throw new IdentityOAuth2Exception("Error when storing the access token for consumer key : " + consumerKey, e);
        }
    } finally {
        IdentityDatabaseUtil.closeStatement(addScopePrepStmt);
        IdentityDatabaseUtil.closeStatement(insertTokenPrepStmt);
    }
}
Also used : OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SQLException(java.sql.SQLException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) PreparedStatement(java.sql.PreparedStatement) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) DataAccessException(org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) SQLException(java.sql.SQLException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) DataTruncation(java.sql.DataTruncation)

Example 3 with OauthTokenIssuer

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

the class AccessTokenDAOImpl method recoverFromConAppKeyConstraintViolation.

private void recoverFromConAppKeyConstraintViolation(String accessToken, String consumerKey, AccessTokenDO accessTokenDO, Connection connection, String userStoreDomain, int retryAttemptCounter) throws IdentityOAuth2Exception {
    try {
        connection.setAutoCommit(false);
        log.warn("Retry attempt to recover 'CON_APP_KEY' constraint violation : " + retryAttemptCounter);
        AccessTokenDO latestNonActiveToken = getLatestAccessTokenByState(connection, consumerKey, accessTokenDO.getAuthzUser(), userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), false);
        AccessTokenDO latestActiveToken = getLatestAccessTokenByState(connection, consumerKey, accessTokenDO.getAuthzUser(), userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), true);
        OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey);
        if (latestActiveToken != null) {
            OAuthTokenReqMessageContext tokReqMsgCtx = OAuth2Util.getTokenRequestContext();
            // For JWT tokens, always issue a new token expiring the existing token.
            if (oauthTokenIssuer.renewAccessTokenPerRequest(tokReqMsgCtx)) {
                updateAccessTokenState(connection, latestActiveToken.getTokenId(), OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED, UUID.randomUUID().toString(), userStoreDomain, latestActiveToken.getGrantType());
                // Update token issued time make this token as latest token & try to store it again.
                accessTokenDO.setIssuedTime(new Timestamp(new Date().getTime()));
                insertAccessToken(accessTokenDO.getAccessToken(), consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter);
            } else if (OAuth2Util.getAccessTokenExpireMillis(latestActiveToken) != 0 && (latestNonActiveToken == null || latestActiveToken.getIssuedTime().after(latestNonActiveToken.getIssuedTime()))) {
                // If there is an active token in the database, it is not expired and it is the last issued
                // token, use the existing token. In here we can use existing token since we have a
                // synchronised communication.
                accessTokenDO.setTokenId(latestActiveToken.getTokenId());
                accessTokenDO.setAccessToken(latestActiveToken.getAccessToken());
                accessTokenDO.setRefreshToken(latestActiveToken.getRefreshToken());
                accessTokenDO.setIssuedTime(latestActiveToken.getIssuedTime());
                accessTokenDO.setRefreshTokenIssuedTime(latestActiveToken.getRefreshTokenIssuedTime());
                accessTokenDO.setValidityPeriodInMillis(latestActiveToken.getValidityPeriodInMillis());
                accessTokenDO.setRefreshTokenValidityPeriodInMillis(latestActiveToken.getRefreshTokenValidityPeriodInMillis());
                accessTokenDO.setTokenType(latestActiveToken.getTokenType());
                log.info("Successfully recovered 'CON_APP_KEY' constraint violation with the attempt : " + retryAttemptCounter);
            } else if (!(OAuth2Util.getAccessTokenExpireMillis(latestActiveToken) == 0)) {
                // If the last active token in the database is expired, update the token status in the database.
                updateAccessTokenState(connection, latestActiveToken.getTokenId(), OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED, UUID.randomUUID().toString(), userStoreDomain, latestActiveToken.getGrantType());
                // Update token issued time make this token as latest token & try to store it again.
                accessTokenDO.setIssuedTime(new Timestamp(new Date().getTime()));
                insertAccessToken(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter);
            } else {
                // Inactivate latest active token.
                updateAccessTokenState(connection, latestActiveToken.getTokenId(), OAuthConstants.TokenStates.TOKEN_STATE_INACTIVE, UUID.randomUUID().toString(), userStoreDomain, latestActiveToken.getGrantType());
                // Update token issued time make this token as latest token & try to store it again.
                accessTokenDO.setIssuedTime(new Timestamp(new Date().getTime()));
                insertAccessToken(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter);
            }
        } else {
            // In this case another process already updated the latest active token to inactive.
            // Update token issued time make this token as latest token & try to store it again.
            accessTokenDO.setIssuedTime(new Timestamp(new Date().getTime()));
            insertAccessToken(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter);
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException e1) {
            throw new IdentityOAuth2Exception("An rolling back transactions error occurred while trying to " + "recover 'CON_APP_KEY' constraint violation. ", e1);
        }
        String errorMsg = "SQL error occurred while trying to recover 'CON_APP_KEY' constraint violation.";
        throw new IdentityOAuth2Exception(errorMsg, e);
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Error while retrieving oauth issuer for the app with clientId: " + consumerKey + ".", e);
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SQLException(java.sql.SQLException) OAuthTokenReqMessageContext(org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext) Timestamp(java.sql.Timestamp) Date(java.util.Date) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 4 with OauthTokenIssuer

use of org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer 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 5 with OauthTokenIssuer

use of org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer 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

OauthTokenIssuer (org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer)18 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)15 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)14 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)9 HashMap (java.util.HashMap)7 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)7 OAuth2AuthorizeReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO)6 Timestamp (java.sql.Timestamp)5 Date (java.util.Date)5 UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)5 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)5 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)4 OauthTokenIssuerImpl (org.wso2.carbon.identity.oauth2.token.OauthTokenIssuerImpl)4 JWTTokenIssuer (org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer)3 SQLException (java.sql.SQLException)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 Test (org.testng.annotations.Test)2 TokenIssuerDO (org.wso2.carbon.identity.oauth2.model.TokenIssuerDO)2 OAuthTokenReqMessageContext (org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext)2