org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException Java Examples

The following examples show how to use org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @throws OAuthSystemException
 */
public void putUserRPToStore(AuthenticatedUser user, String appName, boolean trustedAlways, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDO repDO = new OpenIDUserRPDO();
    repDO.setDefaultProfileName(DEFAULT_PROFILE_NAME);
    repDO.setRpUrl(appName);
    repDO.setUserName(user.getAuthenticatedSubjectIdentifier());
    repDO.setTrustedAlways(trustedAlways);
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    dao.createOrUpdate(repDO, tenantId);
}
 
Example #2
Source File: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @return
 * @throws OAuthSystemException
 */
public synchronized boolean hasUserApproved(AuthenticatedUser user, String appName, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    OpenIDUserRPDO rpDO;
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

    rpDO = dao.getOpenIDUserRP(user.getAuthenticatedSubjectIdentifier(), appName, tenantId);
    if (rpDO != null && rpDO.isTrustedAlways()) {
        return true;
    }

    return false;
}
 
Example #3
Source File: OAuthAdminService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Get OAuth application data by the consumer key.
 *
 * @param consumerKey Consumer Key
 * @return <code>OAuthConsumerAppDTO</code> with application information
 * @throws Exception Error when reading application information from persistence store.
 */
public OAuthConsumerAppDTO getOAuthApplicationData(String consumerKey) throws IdentityOAuthAdminException {
    OAuthConsumerAppDTO dto = new OAuthConsumerAppDTO();
    OAuthAppDAO dao = new OAuthAppDAO();
    try {
        OAuthAppDO app = dao.getAppInformation(consumerKey);
        if (app != null) {
            dto.setApplicationName(app.getApplicationName());
            dto.setCallbackUrl(app.getCallbackUrl());
            dto.setOauthConsumerKey(app.getOauthConsumerKey());
            dto.setOauthConsumerSecret(app.getOauthConsumerSecret());
            dto.setOAuthVersion(app.getOauthVersion());
            dto.setGrantTypes(app.getGrantTypes());
        }
        return dto;
    } catch (InvalidOAuthClientException | IdentityOAuth2Exception e) {
        throw new IdentityOAuthAdminException("Error while retrieving the app information using consumer key", e);
    }

}
 
Example #4
Source File: OAuthAdminService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Get OAuth application data by the application name.
 *
 * @param appName OAuth application name
 * @return <code>OAuthConsumerAppDTO</code> with application information
 * @throws Exception Error when reading application information from persistence store.
 */
public OAuthConsumerAppDTO getOAuthApplicationDataByAppName(String appName) throws IdentityOAuthAdminException {
    OAuthConsumerAppDTO dto = new OAuthConsumerAppDTO();
    OAuthAppDAO dao = new OAuthAppDAO();
    try {
        OAuthAppDO app = dao.getAppInformationByAppName(appName);
        if (app != null) {
            dto.setApplicationName(app.getApplicationName());
            dto.setCallbackUrl(app.getCallbackUrl());
            dto.setOauthConsumerKey(app.getOauthConsumerKey());
            dto.setOauthConsumerSecret(app.getOauthConsumerSecret());
            dto.setOAuthVersion(app.getOauthVersion());
            dto.setGrantTypes(app.getGrantTypes());
        }
        return dto;
    }catch (InvalidOAuthClientException | IdentityOAuth2Exception e){
        throw new IdentityOAuthAdminException("Error while retrieving the app information by app name", e);
    }
}
 
Example #5
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private void validateConsumerKey(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception {

        String consumerKey = (String) claimsSet.getClaim(CONSUMER_KEY);
        if (StringUtils.isNotBlank(consumerKey)) {
            try {
                OAuth2Util.getAppInformationByClientId(consumerKey);
            } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
                throw new IdentityOAuth2Exception("Invalid consumerKey. Cannot find a registered app for consumerKey: "
                        + consumerKey);
            }
        } else {
            throw new IdentityOAuth2Exception("Mandatory claim 'consumerKey' is missing in the signedJWT.");
        }
    }
 
Example #6
Source File: AccessTokenIssuer.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get Oauth application information
 *
 * @param tokenReqDTO
 * @return Oauth app information
 * @throws IdentityOAuth2Exception
 * @throws InvalidOAuthClientException
 */
private OAuthAppDO getAppInformation(OAuth2AccessTokenReqDTO tokenReqDTO) throws IdentityOAuth2Exception, InvalidOAuthClientException {
    OAuthAppDO oAuthAppDO = appInfoCache.getValueFromCache(tokenReqDTO.getClientId());
    if (oAuthAppDO != null) {
        return oAuthAppDO;
    } else {
        oAuthAppDO = new OAuthAppDAO().getAppInformation(tokenReqDTO.getClientId());
        appInfoCache.addToCache(tokenReqDTO.getClientId(), oAuthAppDO);
        return oAuthAppDO;
    }
}
 
Example #7
Source File: AbstractAuthorizationGrantHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    OAuth2AccessTokenReqDTO tokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
    String grantType = tokenReqDTO.getGrantType();

    // Load application data from the cache
    AppInfoCache appInfoCache = AppInfoCache.getInstance();
    OAuthAppDO oAuthAppDO = appInfoCache.getValueFromCache(tokenReqDTO.getClientId());
    if (oAuthAppDO == null) {
        try {
            oAuthAppDO = new OAuthAppDAO().getAppInformation(tokenReqDTO.getClientId());
            appInfoCache.addToCache(tokenReqDTO.getClientId(), oAuthAppDO);
        } catch (InvalidOAuthClientException e) {
            throw new IdentityOAuth2Exception(e.getMessage(), e);
        }
    }
    // If the application has defined a limited set of grant types, then check the grant
    if (oAuthAppDO.getGrantTypes() != null && !oAuthAppDO.getGrantTypes().contains(grantType)) {
        if (log.isDebugEnabled()) {
            //Do not change this log format as these logs use by external applications
            log.debug("Unsupported Grant Type : " + grantType + " for client id : " + tokenReqDTO.getClientId());
        }
        return false;
    }
    return true;
}
 
Example #8
Source File: AuthorizationHandlerManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private OAuthAppDO getAppInformation(OAuth2AuthorizeReqDTO authzReqDTO) throws IdentityOAuth2Exception,
        InvalidOAuthClientException {
    OAuthAppDO oAuthAppDO = appInfoCache.getValueFromCache(authzReqDTO.getConsumerKey());
    if (oAuthAppDO != null) {
        return oAuthAppDO;
    } else {
        oAuthAppDO = new OAuthAppDAO().getAppInformation(authzReqDTO.getConsumerKey());
        appInfoCache.addToCache(authzReqDTO.getConsumerKey(), oAuthAppDO);
        return oAuthAppDO;
    }
}
 
Example #9
Source File: OAuthAppDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public OAuthAppDO getAppInformation(String consumerKey) throws InvalidOAuthClientException, IdentityOAuth2Exception {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet rSet = null;
    OAuthAppDO oauthApp = null;

    try {
        prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.GET_APP_INFO);
        prepStmt.setString(1, persistenceProcessor.getProcessedClientId(consumerKey));

        rSet = prepStmt.executeQuery();
        List<OAuthAppDO> oauthApps = new ArrayList<>();
        /**
         * We need to determine whether the result set has more than 1 row. Meaning, we found an application for
         * the given consumer key. There can be situations where a user passed a key which doesn't yet have an
         * associated application. We need to barf with a meaningful error message for this case
         */
        boolean rSetHasRows = false;
        while (rSet.next()) {
            // There is at least one application associated with a given key
            rSetHasRows = true;
            if (rSet.getString(4) != null && rSet.getString(4).length() > 0) {
                oauthApp = new OAuthAppDO();
                oauthApp.setOauthConsumerKey(consumerKey);
                oauthApp.setOauthConsumerSecret(persistenceProcessor.getPreprocessedClientSecret(rSet.getString(1)));
                AuthenticatedUser authenticatedUser = new AuthenticatedUser();
                authenticatedUser.setUserName(rSet.getString(2));
                oauthApp.setApplicationName(rSet.getString(3));
                oauthApp.setOauthVersion(rSet.getString(4));
                oauthApp.setCallbackUrl(rSet.getString(5));
                authenticatedUser.setTenantDomain(IdentityTenantUtil.getTenantDomain(rSet.getInt(6)));
                authenticatedUser.setUserStoreDomain(rSet.getString(7));
                oauthApp.setUser(authenticatedUser);
                oauthApp.setGrantTypes(rSet.getString(8));
                oauthApp.setId(rSet.getInt(9));
                oauthApps.add(oauthApp);
            }
        }
        if (!rSetHasRows) {
            /**
             * We come here because user submitted a key that doesn't have any associated application with it.
             * We're throwing an error here because we cannot continue without this info. Otherwise it'll throw
             * a null values not supported error when it tries to cache this info
             */

            throw new InvalidOAuthClientException("Cannot find an application associated with the given consumer key : " + consumerKey);
        }
        connection.commit();
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error while retrieving the app information", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rSet, prepStmt);
    }
    return oauthApp;
}
 
Example #10
Source File: OAuthAppDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public OAuthAppDO getAppInformationByAppName(String appName) throws InvalidOAuthClientException, IdentityOAuth2Exception {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet rSet = null;
    OAuthAppDO oauthApp = null;

    try {
        int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.GET_APP_INFO_BY_APP_NAME);
        prepStmt.setString(1, appName);
        prepStmt.setInt(2, tenantID);

        rSet = prepStmt.executeQuery();
        List<OAuthAppDO> oauthApps = new ArrayList<>();
        oauthApp = new OAuthAppDO();
        oauthApp.setApplicationName(appName);
        AuthenticatedUser user = new AuthenticatedUser();
        user.setTenantDomain(IdentityTenantUtil.getTenantDomain(tenantID));
        /**
         * We need to determine whether the result set has more than 1 row. Meaning, we found an application for
         * the given consumer key. There can be situations where a user passed a key which doesn't yet have an
         * associated application. We need to barf with a meaningful error message for this case
         */
        boolean rSetHasRows = false;
        while (rSet.next()) {
            // There is at least one application associated with a given key
            rSetHasRows = true;
            if (rSet.getString(4) != null && rSet.getString(4).length() > 0) {
                oauthApp.setOauthConsumerSecret(persistenceProcessor.getPreprocessedClientSecret(rSet.getString(1)));
                user.setUserName(rSet.getString(2));
                user.setUserStoreDomain(rSet.getString(3));
                oauthApp.setUser(user);
                oauthApp.setOauthConsumerKey(persistenceProcessor.getPreprocessedClientId(rSet.getString(4)));
                oauthApp.setOauthVersion(rSet.getString(5));
                oauthApp.setCallbackUrl(rSet.getString(6));
                oauthApp.setGrantTypes(rSet.getString(7));
                oauthApp.setId(rSet.getInt(8));
                oauthApps.add(oauthApp);
            }
        }
        if (!rSetHasRows) {
            /**
             * We come here because user submitted a key that doesn't have any associated application with it.
             * We're throwing an error here because we cannot continue without this info. Otherwise it'll throw
             * a null values not supported error when it tries to cache this info
             */
            String message = "Cannot find an application associated with the given consumer key : " + appName;
            if(log.isDebugEnabled()) {
                log.debug(message);
            }
            throw new InvalidOAuthClientException(message);
        }
        connection.commit();
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error while retrieving the app information", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rSet, prepStmt);
    }
    return oauthApp;
}
 
Example #11
Source File: AuthorizationHandlerManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public OAuth2AuthorizeRespDTO handleAuthorization(OAuth2AuthorizeReqDTO authzReqDTO)
           throws IdentityOAuth2Exception, IdentityOAuthAdminException, InvalidOAuthClientException {

       String responseType = authzReqDTO.getResponseType();
       OAuth2AuthorizeRespDTO authorizeRespDTO = new OAuth2AuthorizeRespDTO();

       if (!responseHandlers.containsKey(responseType)) {
           log.warn("Unsupported Response Type : " + responseType +
                   " provided  for user : " + authzReqDTO.getUser());
           handleErrorRequest(authorizeRespDTO, OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE,
                   "Unsupported Response Type!");
           authorizeRespDTO.setCallbackURI(authzReqDTO.getCallbackUrl());
           return authorizeRespDTO;
       }

       ResponseTypeHandler authzHandler = responseHandlers.get(responseType);
       OAuthAuthzReqMessageContext authzReqMsgCtx = new OAuthAuthzReqMessageContext(authzReqDTO);

       // loading the stored application data
       OAuthAppDO oAuthAppDO = getAppInformation(authzReqDTO);

       authzReqMsgCtx.addProperty("OAuthAppDO", oAuthAppDO);

       boolean accessDelegationAuthzStatus = authzHandler.validateAccessDelegation(authzReqMsgCtx);
       if(authzReqMsgCtx.getProperty("ErrorCode") != null){
           authorizeRespDTO.setErrorCode((String)authzReqMsgCtx.getProperty("ErrorCode"));
           authorizeRespDTO.setErrorMsg((String)authzReqMsgCtx.getProperty("ErrorMsg"));
           authorizeRespDTO.setCallbackURI(authzReqDTO.getCallbackUrl());
           return authorizeRespDTO;
       } else if (!accessDelegationAuthzStatus) {
           log.warn("User : " + authzReqDTO.getUser() +
                   " doesn't have necessary rights to grant access to the resource(s) " +
                   OAuth2Util.buildScopeString(authzReqDTO.getScopes()));
           handleErrorRequest(authorizeRespDTO, OAuthError.CodeResponse.UNAUTHORIZED_CLIENT,
                   "Authorization Failure!");
           authorizeRespDTO.setCallbackURI(authzReqDTO.getCallbackUrl());
           return authorizeRespDTO;
       }

       boolean scopeValidationStatus = authzHandler.validateScope(authzReqMsgCtx);
       if (!scopeValidationStatus) {
           log.warn("Scope validation failed for user : "
                   + authzReqDTO.getUser() + ", for the scope : "
                   + OAuth2Util.buildScopeString(authzReqDTO.getScopes()));
           handleErrorRequest(authorizeRespDTO,
                   OAuthError.CodeResponse.INVALID_SCOPE, "Invalid Scope!");
           authorizeRespDTO.setCallbackURI(authzReqDTO.getCallbackUrl());
           return authorizeRespDTO;
       } else {
           // We are here because the call-back handler has approved the scope.
           // If call-back handler set the approved scope - then we respect that. If not we take
           // the approved scope as the provided scope.
           if (authzReqMsgCtx.getApprovedScope() == null
                   || authzReqMsgCtx.getApprovedScope().length == 0) {
               authzReqMsgCtx
                       .setApprovedScope(authzReqMsgCtx.getAuthorizationReqDTO().getScopes());
           }
       }

try {
    // set the authorization request context to be used by downstream handlers. This is introduced as a fix for
    // IDENTITY-4111
    OAuth2Util.setAuthzRequestContext(authzReqMsgCtx);
    authorizeRespDTO = authzHandler.issue(authzReqMsgCtx);
} finally {
    // clears authorization request context
    OAuth2Util.clearAuthzRequestContext();
}

       return authorizeRespDTO;
   }
 
Example #12
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the OAuth Consumer
 *
 * @param clientId             Consumer Key/Id
 * @param clientSecretProvided Consumer Secret issued during the time of registration
 * @return true, if the authentication is successful, false otherwise.
 * @throws IdentityOAuthAdminException Error when looking up the credentials from the database
 */
public static boolean authenticateClient(String clientId, String clientSecretProvided)
        throws IdentityOAuthAdminException, IdentityOAuth2Exception, InvalidOAuthClientException {

    boolean cacheHit = false;
    String clientSecret = null;

    // Check the cache first.
    if (cacheEnabled) {
        CacheEntry cacheResult = cache.getValueFromCache(new OAuthCacheKey(clientId));
        if (cacheResult != null && cacheResult instanceof ClientCredentialDO) {
            ClientCredentialDO clientCredentialDO = (ClientCredentialDO) cacheResult;
            clientSecret = clientCredentialDO.getClientSecret();
            cacheHit = true;
            if (log.isDebugEnabled()) {
                log.debug("Client credentials were available in the cache for client id : " +
                        clientId);
            }
        }
    }

    // Cache miss
    if (clientSecret == null) {
        OAuthConsumerDAO oAuthConsumerDAO = new OAuthConsumerDAO();
        clientSecret = oAuthConsumerDAO.getOAuthConsumerSecret(clientId);
        if (log.isDebugEnabled()) {
            log.debug("Client credentials were fetched from the database.");
        }
    }

    if (clientSecret == null) {
        if (log.isDebugEnabled()) {
            log.debug("Provided Client ID : " + clientId + "is not valid.");
        }
        return false;
    }

    if (!clientSecret.equals(clientSecretProvided)) {

        if (log.isDebugEnabled()) {
            log.debug("Provided the Client ID : " + clientId +
                    " and Client Secret do not match with the issued credentials.");
        }

        return false;
    }

    if (log.isDebugEnabled()) {
        log.debug("Successfully authenticated the client with client id : " + clientId);
    }

    if (cacheEnabled && !cacheHit) {

        cache.addToCache(new OAuthCacheKey(clientId), new ClientCredentialDO(clientSecret));
        if (log.isDebugEnabled()) {
            log.debug("Client credentials were added to the cache for client id : " + clientId);
        }
    }

    return true;
}
 
Example #13
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the OAuth consumer and return the username of user which own the provided client id and client
 * secret.
 *
 * @param clientId             Consumer Key/Id
 * @param clientSecretProvided Consumer Secret issued during the time of registration
 * @return Username of the user which own client id and client secret if authentication is
 * successful. Empty string otherwise.
 * @throws IdentityOAuthAdminException Error when looking up the credentials from the database
 */
public static String getAuthenticatedUsername(String clientId, String clientSecretProvided)
        throws IdentityOAuthAdminException, IdentityOAuth2Exception, InvalidOAuthClientException {

    boolean cacheHit = false;
    String username = null;
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(username);

    if (OAuth2Util.authenticateClient(clientId, clientSecretProvided)) {
        // check cache
        if (cacheEnabled) {
            CacheEntry cacheResult = cache.getValueFromCache(new OAuthCacheKey(clientId + ":" + username));
            if (cacheResult != null && cacheResult instanceof ClientCredentialDO) {
                // Ugh. This is fugly. Have to have a generic way of caching a key:value pair
                username = ((ClientCredentialDO) cacheResult).getClientSecret();
                cacheHit = true;
                if (log.isDebugEnabled()) {
                    log.debug("Username was available in the cache : " +
                            username);
                }
            }
        }

        if (username == null) {
            // Cache miss
            OAuthConsumerDAO oAuthConsumerDAO = new OAuthConsumerDAO();
            username = oAuthConsumerDAO.getAuthenticatedUsername(clientId, clientSecretProvided);
            if (log.isDebugEnabled()) {
                log.debug("Username fetch from the database");
            }
        }

        if (username != null && cacheEnabled && !cacheHit) {
            /**
             * Using the same ClientCredentialDO to host username. Semantically wrong since ClientCredentialDo
             * accept a client secret and we're storing a username in the secret variable. Do we have to make our
             * own cache key and cache entry class every time we need to put something to it? Ideal solution is
             * to have a generalized way of caching a key:value pair
             */
            if (isUsernameCaseSensitive) {
                cache.addToCache(new OAuthCacheKey(clientId + ":" + username), new ClientCredentialDO(username));
            } else {
                cache.addToCache(new OAuthCacheKey(clientId + ":" + username.toLowerCase()),
                        new ClientCredentialDO(username));
            }
            if (log.isDebugEnabled()) {
                log.debug("Caching username : " + username);
            }

        }
    }
    return username;
}