Search in sources :

Example 1 with AuthzCodeDO

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

the class TokenResponseTypeHandler method deactivateCurrentAuthorizationCode.

private void deactivateCurrentAuthorizationCode(String authorizationCode, String tokenId) throws IdentityOAuth2Exception {
    if (authorizationCode != null) {
        AuthzCodeDO authzCodeDO = new AuthzCodeDO();
        authzCodeDO.setAuthorizationCode(authorizationCode);
        authzCodeDO.setOauthTokenId(tokenId);
        OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().deactivateAuthorizationCode(authzCodeDO);
    }
}
Also used : AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)

Example 2 with AuthzCodeDO

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

the class ResponseTypeHandlerUtil method deactivateCurrentAuthorizationCode.

private static void deactivateCurrentAuthorizationCode(String authorizationCode, String tokenId) throws IdentityOAuth2Exception {
    if (authorizationCode != null) {
        AuthzCodeDO authzCodeDO = new AuthzCodeDO();
        authzCodeDO.setAuthorizationCode(authorizationCode);
        authzCodeDO.setOauthTokenId(tokenId);
        OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().deactivateAuthorizationCode(authzCodeDO);
    }
}
Also used : AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)

Example 3 with AuthzCodeDO

use of org.wso2.carbon.identity.oauth2.model.AuthzCodeDO 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)

Example 4 with AuthzCodeDO

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

the class ResponseTypeHandlerUtil method generateAuthorizationCode.

public static AuthzCodeDO generateAuthorizationCode(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled) throws IdentityOAuth2Exception {
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String consumerKey = authorizationReqDTO.getConsumerKey();
    try {
        OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey);
        return generateAuthorizationCode(oauthAuthzMsgCtx, cacheEnabled, oauthTokenIssuer);
    } catch (InvalidOAuthClientException e) {
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-authz-code", null);
        throw new IdentityOAuth2Exception("Error while retrieving oauth issuer for the app with clientId: " + consumerKey, e);
    }
}
Also used : OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 5 with AuthzCodeDO

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

the class AuthorizationCodeDAOImpl method validateAuthorizationCode.

@Override
public AuthorizationCodeValidationResult validateAuthorizationCode(String consumerKey, String authorizationKey) throws IdentityOAuth2Exception {
    if (log.isDebugEnabled()) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.AUTHORIZATION_CODE)) {
            log.debug("Validating authorization code(hashed): " + DigestUtils.sha256Hex(authorizationKey) + " for client: " + consumerKey);
        } else {
            log.debug("Validating authorization code for client: " + consumerKey);
        }
    }
    Connection connection = IdentityDatabaseUtil.getDBConnection(false);
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;
    AuthorizationCodeValidationResult result = null;
    try {
        AuthenticatedUser user = null;
        String codeState = null;
        String authorizedUser = null;
        String userstoreDomain = null;
        String scopeString = null;
        String callbackUrl = null;
        String tenantDomain = null;
        String codeId = null;
        String subjectIdentifier = null;
        String pkceCodeChallenge = null;
        String pkceCodeChallengeMethod = null;
        Timestamp issuedTime = null;
        long validityPeriod = 0;
        int tenantId;
        String sql;
        if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
            sql = SQLQueries.VALIDATE_AUTHZ_CODE_WITH_PKCE_IDP_NAME;
        } else {
            sql = SQLQueries.VALIDATE_AUTHZ_CODE_WITH_PKCE;
        }
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setString(1, getPersistenceProcessor().getProcessedClientId(consumerKey));
        // use hash value for search
        prepStmt.setString(2, getHashingPersistenceProcessor().getProcessedAuthzCode(authorizationKey));
        resultSet = prepStmt.executeQuery();
        if (resultSet.next()) {
            codeState = resultSet.getString(8);
            authorizedUser = resultSet.getString(1);
            userstoreDomain = resultSet.getString(2);
            tenantId = resultSet.getInt(3);
            tenantDomain = OAuth2Util.getTenantDomain(tenantId);
            scopeString = resultSet.getString(4);
            callbackUrl = resultSet.getString(5);
            issuedTime = resultSet.getTimestamp(6, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
            validityPeriod = resultSet.getLong(7);
            codeId = resultSet.getString(11);
            subjectIdentifier = resultSet.getString(12);
            pkceCodeChallenge = resultSet.getString(13);
            pkceCodeChallengeMethod = resultSet.getString(14);
            String authenticatedIDP = null;
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                authenticatedIDP = resultSet.getString(15);
            }
            user = OAuth2Util.createAuthenticatedUser(authorizedUser, userstoreDomain, tenantDomain, authenticatedIDP);
            ServiceProvider serviceProvider;
            try {
                serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService().getServiceProviderByClientId(consumerKey, OAuthConstants.Scope.OAUTH2, tenantDomain);
            } catch (IdentityApplicationManagementException e) {
                throw new IdentityOAuth2Exception("Error occurred while retrieving OAuth2 application data " + "for client id " + consumerKey, e);
            }
            user.setAuthenticatedSubjectIdentifier(subjectIdentifier, serviceProvider);
            String tokenId = resultSet.getString(9);
            String tokenBindingReference = NONE;
            if (StringUtils.isNotBlank(tokenId)) {
                tokenBindingReference = getTokenBindingReference(connection, tokenId, tenantId);
            }
            // for on demand scope migration.
            if (StringUtils.isBlank(scopeString)) {
                List<String> scopes = getAuthorizationCodeScopes(connection, codeId, tenantId);
                scopeString = OAuth2Util.buildScopeString(scopes.toArray(new String[0]));
            }
            AuthzCodeDO codeDo = createAuthzCodeDo(consumerKey, authorizationKey, user, codeState, scopeString, callbackUrl, codeId, pkceCodeChallenge, pkceCodeChallengeMethod, issuedTime, validityPeriod, tokenBindingReference);
            result = new AuthorizationCodeValidationResult(codeDo, tokenId);
        }
        return result;
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error when validating an authorization code", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }
}
Also used : SQLException(java.sql.SQLException) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) Timestamp(java.sql.Timestamp) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ResultSet(java.sql.ResultSet) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)

Aggregations

AuthzCodeDO (org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)38 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)18 Test (org.testng.annotations.Test)11 Connection (java.sql.Connection)8 PreparedStatement (java.sql.PreparedStatement)8 SQLException (java.sql.SQLException)8 Timestamp (java.sql.Timestamp)8 Matchers.anyString (org.mockito.Matchers.anyString)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)8 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)8 ArrayList (java.util.ArrayList)7 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)6 ResultSet (java.sql.ResultSet)5 HashMap (java.util.HashMap)5 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)5 HashSet (java.util.HashSet)4 OAuthTokenReqMessageContext (org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext)4 Map (java.util.Map)3 DataProvider (org.testng.annotations.DataProvider)3