Search in sources :

Example 96 with ServiceProvider

use of org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider in project identity-inbound-auth-oauth by wso2-extensions.

the class AccessTokenDAOImpl method getLatestAccessTokenByState.

private AccessTokenDO getLatestAccessTokenByState(Connection connection, String consumerKey, AuthenticatedUser authzUser, String userStoreDomain, String scope, boolean active) throws IdentityOAuth2Exception, SQLException {
    if (log.isDebugEnabled()) {
        log.debug("Retrieving latest " + (active ? " active" : " non active") + " access token for user: " + authzUser.getLoggableUserId() + " client: " + consumerKey + " scope: " + scope);
    }
    String tenantDomain = authzUser.getTenantDomain();
    int tenantId = OAuth2Util.getTenantId(tenantDomain);
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreCaseSensitive(authzUser.getUserStoreDomain(), tenantId);
    String tenantAwareUsernameWithNoUserDomain = authzUser.getUserName();
    String userDomain = OAuth2Util.getUserStoreDomain(authzUser);
    String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(authzUser);
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;
    try {
        String sql;
        String driverName = connection.getMetaData().getDriverName();
        if (active) {
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                if (driverName.contains("MySQL") || driverName.contains("MariaDB") || driverName.contains("H2")) {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_MYSQL;
                } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_DB2SQL;
                } else if (driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_MSSQL;
                } else if (driverName.contains("PostgreSQL")) {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_POSTGRESQL;
                } else if (driverName.contains("Informix")) {
                    // Driver name = "IBM Informix JDBC Driver for IBM Informix Dynamic Server"
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_INFORMIX;
                } else {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_ORACLE;
                }
            } else {
                if (driverName.contains("MySQL") || driverName.contains("MariaDB") || driverName.contains("H2")) {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL;
                } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL;
                } else if (driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL;
                } else if (driverName.contains("PostgreSQL")) {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL;
                } else if (driverName.contains("Informix")) {
                    // Driver name = "IBM Informix JDBC Driver for IBM Informix Dynamic Server"
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX;
                } else {
                    sql = SQLQueries.RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE;
                }
            }
        } else {
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                if (driverName.contains("MySQL") || driverName.contains("MariaDB") || driverName.contains("H2")) {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_MYSQL;
                } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_DB2SQL;
                } else if (driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_MSSQL;
                } else if (driverName.contains("PostgreSQL")) {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_POSTGRESQL;
                } else if (driverName.contains("Informix")) {
                    // Driver name = "IBM Informix JDBC Driver for IBM Informix Dynamic Server"
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_INFORMIX;
                } else {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_IDP_NAME_ORACLE;
                }
            } else {
                if (driverName.contains("MySQL") || driverName.contains("MariaDB") || driverName.contains("H2")) {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL;
                } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL;
                } else if (driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL;
                } else if (driverName.contains("PostgreSQL")) {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL;
                } else if (driverName.contains("Informix")) {
                    // Driver name = "IBM Informix JDBC Driver for IBM Informix Dynamic Server"
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX;
                } else {
                    sql = SQLQueries.RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE;
                }
            }
        }
        sql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userDomain);
        if (!isUsernameCaseSensitive) {
            sql = sql.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        String hashedScope = OAuth2Util.hashScopes(scope);
        if (hashedScope == null) {
            sql = sql.replace("TOKEN_SCOPE_HASH=?", "TOKEN_SCOPE_HASH IS NULL");
        }
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setString(1, getPersistenceProcessor().getProcessedClientId(consumerKey));
        if (isUsernameCaseSensitive) {
            prepStmt.setString(2, tenantAwareUsernameWithNoUserDomain);
        } else {
            prepStmt.setString(2, tenantAwareUsernameWithNoUserDomain.toLowerCase());
        }
        prepStmt.setInt(3, tenantId);
        prepStmt.setString(4, userDomain);
        if (hashedScope != null) {
            prepStmt.setString(5, hashedScope);
        }
        if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
            prepStmt.setString(6, authenticatedIDP);
        }
        resultSet = prepStmt.executeQuery();
        AccessTokenDO accessTokenDO = null;
        if (resultSet.next()) {
            String accessToken = getPersistenceProcessor().getPreprocessedAccessTokenIdentifier(resultSet.getString(1));
            String refreshToken = null;
            if (resultSet.getString(2) != null) {
                refreshToken = getPersistenceProcessor().getPreprocessedRefreshToken(resultSet.getString(2));
            }
            long issuedTime = resultSet.getTimestamp(3, Calendar.getInstance(TimeZone.getTimeZone("UTC"))).getTime();
            long refreshTokenIssuedTime = resultSet.getTimestamp(4, Calendar.getInstance(TimeZone.getTimeZone("UTC"))).getTime();
            long validityPeriodInMillis = resultSet.getLong(5);
            long refreshTokenValidityPeriodInMillis = resultSet.getLong(6);
            String userType = resultSet.getString(7);
            String tokenId = resultSet.getString(8);
            String subjectIdentifier = resultSet.getString(9);
            // data loss at dividing the validity period but can be neglected
            AuthenticatedUser user = OAuth2Util.createAuthenticatedUser(tenantAwareUsernameWithNoUserDomain, userDomain, 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);
            accessTokenDO = new AccessTokenDO(consumerKey, user, OAuth2Util.buildScopeArray(scope), new Timestamp(issuedTime), new Timestamp(refreshTokenIssuedTime), validityPeriodInMillis, refreshTokenValidityPeriodInMillis, userType);
            accessTokenDO.setAccessToken(accessToken);
            accessTokenDO.setRefreshToken(refreshToken);
            accessTokenDO.setTokenId(tokenId);
        }
        return accessTokenDO;
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        String errorMsg = "Error occurred while trying to retrieve latest 'ACTIVE' " + "access token for Client ID : " + consumerKey + ", User ID : " + authzUser + " and  Scope : " + scope;
        if (!active) {
            errorMsg = errorMsg.replace("ACTIVE", "NON ACTIVE");
        }
        throw new IdentityOAuth2Exception(errorMsg, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(null, resultSet, prepStmt);
    }
}
Also used : SQLException(java.sql.SQLException) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) PreparedStatement(java.sql.PreparedStatement) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) Timestamp(java.sql.Timestamp) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ResultSet(java.sql.ResultSet)

Example 97 with ServiceProvider

use of org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider in project identity-inbound-auth-oauth by wso2-extensions.

the class AccessTokenDAOImpl method getAccessToken.

@Override
public AccessTokenDO getAccessToken(String accessTokenIdentifier, boolean includeExpired) throws IdentityOAuth2Exception {
    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
        log.debug("Retrieving information of access token(hashed): " + DigestUtils.sha256Hex(accessTokenIdentifier));
    }
    AccessTokenDO dataDO = null;
    Connection connection = IdentityDatabaseUtil.getDBConnection(false);
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;
    try {
        String sql;
        if (includeExpired) {
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                sql = SQLQueries.RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN_IDP_NAME;
            } else {
                sql = SQLQueries.RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN;
            }
        } else {
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                sql = SQLQueries.RETRIEVE_ACTIVE_ACCESS_TOKEN_IDP_NAME;
            } else {
                sql = SQLQueries.RETRIEVE_ACTIVE_ACCESS_TOKEN;
            }
        }
        sql = OAuth2Util.getTokenPartitionedSqlByToken(sql, accessTokenIdentifier);
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setString(1, getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenIdentifier));
        resultSet = prepStmt.executeQuery();
        int iterateId = 0;
        List<String> scopes = new ArrayList<>();
        while (resultSet.next()) {
            if (iterateId == 0) {
                String consumerKey = getPersistenceProcessor().getPreprocessedClientId(resultSet.getString(1));
                String authorizedUser = resultSet.getString(2);
                int tenantId = resultSet.getInt(3);
                String tenantDomain = OAuth2Util.getTenantDomain(tenantId);
                String userDomain = resultSet.getString(4);
                String[] scope = OAuth2Util.buildScopeArray(resultSet.getString(5));
                Timestamp issuedTime = resultSet.getTimestamp(6, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
                Timestamp refreshTokenIssuedTime = resultSet.getTimestamp(7, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
                long validityPeriodInMillis = resultSet.getLong(8);
                long refreshTokenValidityPeriodMillis = resultSet.getLong(9);
                String tokenType = resultSet.getString(10);
                String refreshToken = resultSet.getString(11);
                String tokenId = resultSet.getString(12);
                String grantType = resultSet.getString(13);
                String subjectIdentifier = resultSet.getString(14);
                String authenticatedIDP = null;
                String tokenBindingReference = resultSet.getString(15);
                if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                    authenticatedIDP = resultSet.getString(16);
                }
                AuthenticatedUser user = OAuth2Util.createAuthenticatedUser(authorizedUser, userDomain, 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);
                dataDO = new AccessTokenDO(consumerKey, user, scope, issuedTime, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodMillis, tokenType);
                dataDO.setAccessToken(accessTokenIdentifier);
                dataDO.setRefreshToken(refreshToken);
                dataDO.setTokenId(tokenId);
                dataDO.setGrantType(grantType);
                dataDO.setTenantID(tenantId);
                if (StringUtils.isNotBlank(tokenBindingReference) && !NONE.equals(tokenBindingReference)) {
                    setTokenBindingToAccessTokenDO(dataDO, connection, tokenId);
                }
            } else {
                scopes.add(resultSet.getString(5));
            }
            iterateId++;
        }
        if (scopes.size() > 0 && dataDO != null) {
            dataDO.setScope((String[]) ArrayUtils.addAll(dataDO.getScope(), scopes.toArray(new String[scopes.size()])));
        }
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error when retrieving Access Token" + e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }
    return dataDO;
}
Also used : SQLException(java.sql.SQLException) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ResultSet(java.sql.ResultSet)

Example 98 with ServiceProvider

use of org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider in project identity-inbound-auth-oauth by wso2-extensions.

the class AccessTokenDAOImpl method getAccessTokens.

@Override
public Set<AccessTokenDO> getAccessTokens(String consumerKey, AuthenticatedUser userName, String userStoreDomain, boolean includeExpired) throws IdentityOAuth2Exception {
    if (log.isDebugEnabled()) {
        log.debug("Retrieving access tokens for client: " + consumerKey + " user: " + userName.toString());
    }
    String tenantDomain = userName.getTenantDomain();
    String tenantAwareUsernameWithNoUserDomain = userName.getUserName();
    String userDomain = OAuth2Util.getUserStoreDomain(userName);
    int tenantId = OAuth2Util.getTenantId(tenantDomain);
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreCaseSensitive(userName.getUserStoreDomain(), tenantId);
    userStoreDomain = OAuth2Util.getSanitizedUserStoreDomain(userStoreDomain);
    String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(userName);
    Connection connection = IdentityDatabaseUtil.getDBConnection(false);
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;
    Map<String, AccessTokenDO> accessTokenDOMap = new HashMap<>();
    try {
        String sql;
        if (includeExpired) {
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                sql = SQLQueries.RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN_BY_CLIENT_ID_USER_IDP_NAME;
            } else {
                sql = SQLQueries.RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN_BY_CLIENT_ID_USER;
            }
        } else {
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                sql = SQLQueries.RETRIEVE_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_IDP_NAME;
            } else {
                sql = SQLQueries.RETRIEVE_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER;
            }
        }
        sql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userStoreDomain);
        if (!isUsernameCaseSensitive) {
            sql = sql.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setString(1, getPersistenceProcessor().getProcessedClientId(consumerKey));
        if (isUsernameCaseSensitive) {
            prepStmt.setString(2, tenantAwareUsernameWithNoUserDomain);
        } else {
            prepStmt.setString(2, tenantAwareUsernameWithNoUserDomain.toLowerCase());
        }
        prepStmt.setInt(3, tenantId);
        prepStmt.setString(4, userDomain);
        if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
            prepStmt.setString(5, authenticatedIDP);
        }
        resultSet = prepStmt.executeQuery();
        while (resultSet.next()) {
            String accessToken = getPersistenceProcessor().getPreprocessedAccessTokenIdentifier(resultSet.getString(1));
            if (accessTokenDOMap.get(accessToken) == null) {
                String refreshToken = getPersistenceProcessor().getPreprocessedRefreshToken(resultSet.getString(2));
                Timestamp issuedTime = resultSet.getTimestamp(3, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
                Timestamp refreshTokenIssuedTime = resultSet.getTimestamp(4, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
                long validityPeriodInMillis = resultSet.getLong(5);
                long refreshTokenValidityPeriodMillis = resultSet.getLong(6);
                String tokenType = resultSet.getString(7);
                String[] scope = OAuth2Util.buildScopeArray(resultSet.getString(8));
                String tokenId = resultSet.getString(9);
                String subjectIdentifier = resultSet.getString(10);
                String tokenBindingReference = resultSet.getString(11);
                AuthenticatedUser user = OAuth2Util.createAuthenticatedUser(tenantAwareUsernameWithNoUserDomain, userDomain, 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);
                AccessTokenDO dataDO = new AccessTokenDO(consumerKey, user, scope, issuedTime, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodMillis, tokenType);
                dataDO.setAccessToken(accessToken);
                dataDO.setRefreshToken(refreshToken);
                dataDO.setTokenId(tokenId);
                if (StringUtils.isNotBlank(tokenBindingReference) && !NONE.equals(tokenBindingReference)) {
                    setTokenBindingToAccessTokenDO(dataDO, connection, tokenId);
                }
                accessTokenDOMap.put(accessToken, dataDO);
            } else {
                String scope = resultSet.getString(8).trim();
                AccessTokenDO accessTokenDO = accessTokenDOMap.get(accessToken);
                accessTokenDO.setScope((String[]) ArrayUtils.add(accessTokenDO.getScope(), scope));
            }
        }
    } catch (SQLException e) {
        String errorMsg = "Error occurred while retrieving 'ACTIVE' access tokens for " + "Client ID : " + consumerKey + " and User ID : " + userName;
        if (includeExpired) {
            errorMsg = errorMsg.replace("ACTIVE", "ACTIVE or EXPIRED");
        }
        throw new IdentityOAuth2Exception(errorMsg, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }
    return new HashSet<>(accessTokenDOMap.values());
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ResultSet(java.sql.ResultSet) HashSet(java.util.HashSet)

Example 99 with ServiceProvider

use of org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider 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)

Example 100 with ServiceProvider

use of org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider in project identity-inbound-auth-oauth by wso2-extensions.

the class ClaimUtil method getServiceProvider.

private static ServiceProvider getServiceProvider(String clientId, String spTenantDomain) throws IdentityApplicationManagementException, UserInfoEndpointException {
    ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService();
    String spName = applicationMgtService.getServiceProviderNameByClientId(clientId, INBOUND_AUTH2_TYPE, spTenantDomain);
    ServiceProvider serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(spName, spTenantDomain);
    if (serviceProvider == null) {
        throw new UserInfoEndpointException("Cannot retrieve service provider: " + spName + " in " + "tenantDomain: " + spTenantDomain);
    }
    return serviceProvider;
}
Also used : UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService)

Aggregations

ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)222 Test (org.testng.annotations.Test)120 ServiceProvider (org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider)96 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)85 ArrayList (java.util.ArrayList)65 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)58 HashMap (java.util.HashMap)50 InboundAuthenticationRequestConfig (org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig)49 ApplicationManagementService (org.wso2.carbon.identity.application.mgt.ApplicationManagementService)40 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)35 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)33 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)29 InboundAuthenticationRequestConfig (org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig)26 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)25 IdentityException (org.wso2.carbon.identity.base.IdentityException)23 Property (org.wso2.carbon.identity.application.common.model.xsd.Property)21 LocalAndOutboundAuthenticationConfig (org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig)20 InboundAuthenticationConfig (org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationConfig)20 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)20 Matchers.anyString (org.mockito.Matchers.anyString)19