org.wso2.carbon.identity.oauth.IdentityOAuthAdminException Java Examples

The following examples show how to use org.wso2.carbon.identity.oauth.IdentityOAuthAdminException. 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: RegistrationServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve the existing application of given name
 *
 * @param applicationName application name
 * @param saasApp         value of IsSaasApp attribute of application.
 * @return existing Application
 */
private OAuthApplicationInfo getExistingApp(String applicationName, boolean saasApp) {

    OAuthApplicationInfo appToReturn = null;
    OAuthAdminService oAuthAdminService = new OAuthAdminService();
    try {
        OAuthConsumerAppDTO consumerAppDTO = oAuthAdminService.
                getOAuthApplicationDataByAppName(applicationName);
        Map<String, String> valueMap = new HashMap<String, String>();
        valueMap.put(OAUTH_CLIENT_GRANT, consumerAppDTO.getGrantTypes());

        appToReturn = this.fromAppDTOToApplicationInfo(consumerAppDTO.getOauthConsumerKey(),
                consumerAppDTO.getApplicationName(), consumerAppDTO.getCallbackUrl(),
                consumerAppDTO.getOauthConsumerSecret(), saasApp, null, valueMap);

    } catch (IdentityOAuthAdminException e) {
        log.error("error occurred while trying to get OAuth Application data", e);
    }
    return appToReturn;
}
 
Example #2
Source File: OidcScopeManagementService.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
/**
 * Handle error cases.
 *
 * @param e       Exception.
 * @param message Error message.
 * @return API error.
 */
private APIError handleException(IdentityOAuthAdminException e, String message) {

    ErrorResponse.Builder builder = new ErrorResponse.Builder().withCode(e.getErrorCode())
            .withMessage(message).withDescription(e.getMessage());
    ErrorResponse errorResponse = builder.build(LOG, e, message);
    Response.Status status;
    if (OidcScopeConstants.ErrorMessage.INVALID_REQUEST.getCode().equals(e.getErrorCode())) {
        status = Response.Status.BAD_REQUEST;
    } else if (OidcScopeConstants.ErrorMessage.ERROR_CONFLICT_REQUEST.getCode().equals(e.getErrorCode())) {
        status = Response.Status.CONFLICT;
    } else if (OidcScopeConstants.ErrorMessage.SCOPE_NOT_FOUND.getCode().equals(e.getErrorCode())) {
        status = Response.Status.NOT_FOUND;
    } else {
        status = Response.Status.INTERNAL_SERVER_ERROR;
    }
    return new APIError(status, errorResponse);
}
 
Example #3
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private String getCallbackURLOfReqToken(String oauthToken) throws IdentityOAuthAdminException {
    String callbackURL = null;
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;

    try {
        prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_CALLBACK_URL_OF_REQ_TOKEN);
        prepStmt.setString(1, oauthToken);
        resultSet = prepStmt.executeQuery();

        if (resultSet.next()) {
            callbackURL = resultSet.getString(1);
        }
        connection.commit();
    } catch (SQLException e) {
        throw new IdentityOAuthAdminException("Error when reading the callback url for OAuth Token : " +
                oauthToken, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }

    return callbackURL;
}
 
Example #4
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private String getCallbackURLOfApp(String consumerKey) throws IdentityOAuthAdminException {
    String callbackURL = null;
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;

    try {
        prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_REGISTERED_CALLBACK_URL);
        prepStmt.setString(1, consumerKey);
        resultSet = prepStmt.executeQuery();

        if (resultSet.next()) {
            callbackURL = resultSet.getString(1);
        }
        connection.commit();
    } catch (SQLException e) {
        throw new IdentityOAuthAdminException("Error when reading the callback url for consumer key : " +
                consumerKey, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }

    return callbackURL;
}
 
Example #5
Source File: OAuthAppDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void removeConsumerApplication(String consumerKey) throws IdentityOAuthAdminException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;

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

        prepStmt.execute();
        connection.commit();

    } catch (SQLException e) {;
        throw new IdentityOAuthAdminException("Error when executing the SQL : " + SQLQueries.OAuthAppDAOSQLQueries.REMOVE_APPLICATION, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
}
 
Example #6
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the username corresponding to a given client id and consumer secret
 *
 * @param clientId     Client Id/Key
 * @param clientSecret Consumer secret
 * @return Username if successful, empty string otherwise
 * @throws IdentityOAuthAdminException Error when reading consumer secret from the persistence store
 */
public String getAuthenticatedUsername(String clientId, String clientSecret) throws IdentityOAuthAdminException {
    String username = "";
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;

    try {
        prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_USERNAME_FOR_KEY_AND_SECRET);
        prepStmt.setString(1, clientId);
        prepStmt.setString(2, clientSecret);
        resultSet = prepStmt.executeQuery();

        if (resultSet.next()) {
            username = resultSet.getString(1);
        } else {
            log.debug("Invalid client id : " + clientId + ", and consumer secret : " + clientSecret);
        }
        connection.commit();
    } catch (SQLException e) {
        log.error("Error when executing the SQL : " + SQLQueries.OAuthConsumerDAOSQLQueries.GET_USERNAME_FOR_KEY_AND_SECRET);
        log.error(e.getMessage(), e);
        throw new IdentityOAuthAdminException("Error while reading username for client id : " + clientId +
                ", and consumer secret : " + clientSecret);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }

    return username;

}
 
Example #7
Source File: RegistrationServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Method to create a OAuth App with client credentials
 *
 * @param appName    application name
 * @param grantTypes grant types
 * @param userName   username of the application
 * @return created Oauth App
 */
private OAuthConsumerAppDTO createOAuthApp(String appName, OAuthApplicationInfo applicationInfo,
        String grantTypes, String userName) {
    OAuthConsumerAppDTO createdApp = null;
    OAuthAdminService oauthAdminService = new OAuthAdminService();
    OAuthConsumerAppDTO oauthConsumerAppDTO = new OAuthConsumerAppDTO();
    oauthConsumerAppDTO.setApplicationName(appName);
    if (StringUtils.isNotBlank(applicationInfo.getCallBackURL())) {
        oauthConsumerAppDTO.setCallbackUrl(applicationInfo.getCallBackURL());
    }
    oauthConsumerAppDTO.setUsername(userName);
    oauthConsumerAppDTO.setOAuthVersion(OAuthConstants.OAuthVersions.VERSION_2);
    oauthConsumerAppDTO.setGrantTypes(grantTypes.trim());
    try {
        boolean isHashDisabled = OAuth2Util.isHashDisabled();
        if (isHashDisabled) {
            //Creating the Oauth app
            oauthAdminService.registerOAuthApplicationData(oauthConsumerAppDTO);

            //Retrieving the created OAuth application
            createdApp = oauthAdminService.getOAuthApplicationDataByAppName
                    (oauthConsumerAppDTO.getApplicationName());
        } else {
            createdApp = oauthAdminService.registerAndRetrieveOAuthApplicationData(oauthConsumerAppDTO);
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error occurred while creating the OAuth app", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Created OAuth App " + appName);
    }
    return createdApp;
}
 
Example #8
Source File: OAuthApplicationMgtListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void addClientSecret(ServiceProvider serviceProvider) throws IdentityApplicationManagementException {

        if (serviceProvider == null) {
            return ; // if service provider is not present no need to add this information
        }

        try {
            InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig();
            if (inboundAuthenticationConfig != null) {
                InboundAuthenticationRequestConfig[] inboundRequestConfigs = inboundAuthenticationConfig.
                        getInboundAuthenticationRequestConfigs();
                if (inboundRequestConfigs != null) {
                    for (InboundAuthenticationRequestConfig inboundRequestConfig : inboundRequestConfigs) {
                        if (inboundRequestConfig.getInboundAuthType().equals(OAUTH2)) {
                            Property[] props = inboundRequestConfig.getProperties();
                            Property property = new Property();
                            property.setName(OAUTH2_CONSUMER_SECRET);
                            property.setValue(getClientSecret(inboundRequestConfig.getInboundAuthKey()));
                            props = (Property[]) ArrayUtils.add(props, property);
                            inboundRequestConfig.setProperties(props);
                            continue;// we are interested only on oauth2 config. Only one will be present.
                        } else {
                            //ignore
                        }
                    }
                } else {
                    //ignore
                }
            } else {
                //nothing to do
            }
        } catch (IdentityOAuthAdminException e) {
            throw new IdentityApplicationManagementException("Injecting client secret failed.", e);
        }


        return;
    }
 
Example #9
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validating the access token. Should be equal in the scope where the original request token
 * been issued to.If this matches, the method returns the user who authorized the request token.
 *
 * @param consumerKey Consumer Key
 * @param oauthToken  Access Token
 * @param reqScope    Scope in the request
 * @return Authorized Username
 * @throws IdentityException Error when reading token information from persistence store or invalid token or invalid scope.
 */
public String validateAccessToken(String consumerKey, String oauthToken, String reqScope)
        throws IdentityException {

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;
    String scope = null;
    String authorizedUser = null;

    try {
        prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_ACCESS_TOKEN);
        prepStmt.setString(1, oauthToken);
        resultSet = prepStmt.executeQuery();

        if (resultSet.next()) {
            scope = resultSet.getString(1);
            authorizedUser = resultSet.getString(2);
        } else {
            throw IdentityException.error("Invalid access token : " + oauthToken);
        }
        connection.commit();
    } catch (SQLException e) {
        throw new IdentityOAuthAdminException("Error when reading the callback url for consumer key : " +
                consumerKey, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }

    if (reqScope != null && reqScope.equals(scope)) {
        return authorizedUser;
    } else {
        throw IdentityException.error("Scope of the access token doesn't match with the original scope");
    }
}
 
Example #10
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void issueAccessToken(String consumerKey, String accessToken, String accessTokenSecret,
                             String requestToken, String authorizedUser, String scope) throws IdentityOAuthAdminException {

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement removeReqTokStmt = null;
    PreparedStatement issueAccessTokStmt = null;

    try {
        removeReqTokStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.REMOVE_REQUEST_TOKEN);
        removeReqTokStmt.setString(1, requestToken);
        removeReqTokStmt.execute();

        issueAccessTokStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.ADD_ACCESS_TOKEN);
        issueAccessTokStmt.setString(1, accessToken);
        issueAccessTokStmt.setString(2, accessTokenSecret);
        issueAccessTokStmt.setString(3, consumerKey);
        issueAccessTokStmt.setString(4, scope);
        issueAccessTokStmt.setString(5, authorizedUser);
        issueAccessTokStmt.execute();

        connection.commit();

    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw new IdentityOAuthAdminException("Error when creating the request token for consumer : " + consumerKey);
    } finally {
        IdentityDatabaseUtil.closeStatement(issueAccessTokStmt);
        IdentityDatabaseUtil.closeAllConnections(connection, null, removeReqTokStmt);
    }

}
 
Example #11
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes the OAuth request token.
 *
 * @param oauthToken    Authorized OAuth token
 * @param userName      The name of the user who authorized the token.
 * @param oauthVerifier oauth_verifier - an unique identifier
 * @throws IdentityException
 */
public Parameters authorizeOAuthToken(String oauthToken, String userName, String oauthVerifier)
        throws IdentityException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;

    try {
        prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.AUTHORIZE_REQ_TOKEN);
        prepStmt.setString(1, Boolean.toString(true));
        prepStmt.setString(2, oauthVerifier);
        prepStmt.setString(3, userName);
        prepStmt.setString(4, oauthToken);

        prepStmt.execute();
        connection.commit();

    } catch (SQLException e) {
        throw new IdentityOAuthAdminException("Error when authorizing the request token : " + oauthToken);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }

    Parameters params = new Parameters();
    params.setOauthCallback(getCallbackURLOfReqToken(oauthToken));

    return params;

}
 
Example #12
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new OAuth token.
 *
 * @param consumerKey  Consumer Key
 * @param oauthToken   OAuth Token, a unique identifier
 * @param oauthSecret  OAuth Secret
 * @param userCallback Where the user should be redirected once the approval completed.
 * @param scope        Resource or the scope of the resource.
 * @throws IdentityOAuthAdminException Error when writing the OAuth Req. token to the persistence store
 */
public void createOAuthRequestToken(String consumerKey, String oauthToken, String oauthSecret,
                                    String userCallback, String scope) throws IdentityOAuthAdminException {
    final String OUT_OF_BAND = "oob";
    if (userCallback == null || OUT_OF_BAND.equals(userCallback)) {
        userCallback = getCallbackURLOfApp(consumerKey);
    }

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;

    try {
        prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.ADD_OAUTH_REQ_TOKEN);
        prepStmt.setString(1, oauthToken);
        prepStmt.setString(2, oauthSecret);
        prepStmt.setString(3, userCallback);
        prepStmt.setString(4, scope);
        prepStmt.setString(5, Boolean.toString(false));
        prepStmt.setString(6, consumerKey);

        prepStmt.execute();
        connection.commit();

    } catch (SQLException e) {
        log.error("Error when executing the SQL : " + SQLQueries.OAuthConsumerDAOSQLQueries.ADD_OAUTH_REQ_TOKEN);
        log.error(e.getMessage(), e);
        throw new IdentityOAuthAdminException("Error when creating the request token for consumer : " + consumerKey);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }

}
 
Example #13
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the token secret for the given access token
 *
 * @param token         OAuth token, this could be a request token(temporary token) or a access token
 * @param isAccessToken True, if it is as access token
 * @return Token Secret
 * @throws IdentityOAuthAdminException Error when accessing the token secret from the persistence store.
 */
public String getOAuthTokenSecret(String token, Boolean isAccessToken) throws IdentityException {

    String tokenSecret = null;
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;
    String sqlStmt;

    if (isAccessToken) {
        sqlStmt = SQLQueries.OAuthConsumerDAOSQLQueries.GET_ACCESS_TOKEN_SECRET;
    } else {
        sqlStmt = SQLQueries.OAuthConsumerDAOSQLQueries.GET_REQ_TOKEN_SECRET;
    }

    try {
        prepStmt = connection.prepareStatement(sqlStmt);
        prepStmt.setString(1, token);
        resultSet = prepStmt.executeQuery();
        connection.commit();

        if (resultSet.next()) {
            tokenSecret = resultSet.getString(1);
        } else {
            throw IdentityException.error("Invalid token : " + token);
        }
    } catch (SQLException e) {
        throw new IdentityOAuthAdminException("Error when reading the token secret for token : " +
                token, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }

    return tokenSecret;

}
 
Example #14
Source File: OidcScopeManagementService.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
/**
 * Add an OIDC scope.
 *
 * @param scopeObject Scope.
 * @return Return location URI of created scope.
 */
public String addScope(Scope scopeObject) {

    try {
        List<String> claimList = scopeObject.getClaims();
        String[] claimArray = claimList.toArray(new String[claimList.size()]);
        ScopeDTO scopeDTO = new ScopeDTO(scopeObject.getName(), scopeObject.getDisplayName(),
                scopeObject.getDescription(), claimArray);
        getOAuthAdminService().addScope(scopeDTO);
        return scopeDTO.getName();
    } catch (IdentityOAuthAdminException e) {
        throw handleException(e, "Server encountered an error while adding OIDC scope: " + scopeObject.getName());
    }
}
 
Example #15
Source File: OAuthAppDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private boolean isDuplicateApplication(String username, int tenantId, String userDomain, OAuthAppDO consumerAppDTO)
        throws IdentityOAuthAdminException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet rSet = null;

    boolean isDuplicateApp = false;
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(username, tenantId);

    try {
        String sql = SQLQueries.OAuthAppDAOSQLQueries.CHECK_EXISTING_APPLICATION;
        if (!isUsernameCaseSensitive) {
            sql = sql.replace("USERNAME", "LOWER(USERNAME)");
        }
        prepStmt = connection.prepareStatement(sql);
        if (isUsernameCaseSensitive) {
            prepStmt.setString(1, username);
        } else {
            prepStmt.setString(1, username.toLowerCase());
        }
        prepStmt.setInt(2, tenantId);
        prepStmt.setString(3, userDomain);
        prepStmt.setString(4, consumerAppDTO.getApplicationName());

        rSet = prepStmt.executeQuery();
        if (rSet.next()) {
            isDuplicateApp = true;
        }
        connection.commit();
    } catch (SQLException e) {
        throw new IdentityOAuthAdminException("Error when executing the SQL : " + SQLQueries.OAuthAppDAOSQLQueries.CHECK_EXISTING_APPLICATION, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rSet, prepStmt);
    }
    return isDuplicateApp;
}
 
Example #16
Source File: OAuthAppDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public String[] addOAuthConsumer(String username, int tenantId, String userDomain) throws IdentityOAuthAdminException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    String sqlStmt = null;
    String consumerKey;
    String consumerSecret = OAuthUtil.getRandomNumber();

    do {
        consumerKey = OAuthUtil.getRandomNumber();
    }
    while (isDuplicateConsumer(consumerKey));

    try {
        sqlStmt = SQLQueries.OAuthAppDAOSQLQueries.ADD_OAUTH_CONSUMER;
        prepStmt = connection.prepareStatement(sqlStmt);
        prepStmt.setString(1, consumerKey);
        prepStmt.setString(2, consumerSecret);
        prepStmt.setString(3, username);
        prepStmt.setInt(4, tenantId);
        prepStmt.setString(5, userDomain);
        // it is assumed that the OAuth version is 1.0a because this is required with OAuth 1.0a
        prepStmt.setString(6, OAuthConstants.OAuthVersions.VERSION_1A);
        prepStmt.execute();

        connection.commit();

    } catch (SQLException e) {
        throw new IdentityOAuthAdminException("Error when executing the SQL : " + sqlStmt, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
    return new String[]{consumerKey, consumerSecret};
}
 
Example #17
Source File: OAuthInboundFunctions.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
public static void revokeOAuthClient(String clientId) {

        try {
            ApplicationManagementServiceHolder.getInstance().getOAuthAdminService()
                    .updateConsumerAppState(clientId, OAuthConstants.OauthAppStates.APP_STATE_REVOKED);
        } catch (IdentityOAuthAdminException e) {
            throw buildServerError("Error while revoking oauth application.", e);
        }
    }
 
Example #18
Source File: OAuthInboundFunctions.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
public static OpenIDConnectConfiguration regenerateClientSecret(String clientId) {

        try {
            OAuthConsumerAppDTO oAuthConsumerAppDTO = ApplicationManagementServiceHolder.getInstance()
                    .getOAuthAdminService().updateAndRetrieveOauthSecretKey(clientId);
            return new OAuthConsumerAppToApiModel().apply(oAuthConsumerAppDTO);
        } catch (IdentityOAuthAdminException e) {
            throw buildServerError("Error while regenerating client secret of oauth application.", e);
        }
    }
 
Example #19
Source File: OAuthInboundFunctions.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
public static void deleteOAuthInbound(InboundAuthenticationRequestConfig inbound) {

        try {
            String consumerKey = inbound.getInboundAuthKey();
            ApplicationManagementServiceHolder.getInstance().getOAuthAdminService().removeOAuthApplicationData
                    (consumerKey);
        } catch (IdentityOAuthAdminException e) {
            throw buildServerError("Error while trying to rollback OAuth2/OpenIDConnect " +
                    "configuration." + e.getMessage(), e);
        }
    }
 
Example #20
Source File: OAuthInboundFunctions.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
public static OpenIDConnectConfiguration getOAuthConfiguration(InboundAuthenticationRequestConfig inboundAuth) {

        String clientId = inboundAuth.getInboundAuthKey();
        try {
            OAuthConsumerAppDTO oauthApp =
                    ApplicationManagementServiceHolder.getInstance().getOAuthAdminService().getOAuthApplicationData
                            (clientId);
            return new OAuthConsumerAppToApiModel().apply(oauthApp);

        } catch (IdentityOAuthAdminException e) {
            throw buildServerError("Error while retrieving oauth application for clientId: " + clientId, e);
        }
    }
 
Example #21
Source File: OAuthInboundFunctions.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
public static InboundAuthenticationRequestConfig createOAuthInbound(String appName, OpenIDConnectConfiguration
                                                                    oidcModel) {

    // Build a consumer apps object.
    OAuthConsumerAppDTO consumerApp = new ApiModelToOAuthConsumerApp().apply(appName, oidcModel);
    try {
        OAuthConsumerAppDTO createdOAuthApp = ApplicationManagementServiceHolder.getInstance()
                .getOAuthAdminService()
                .registerAndRetrieveOAuthApplicationData(consumerApp);

        return createInboundAuthRequestConfig(createdOAuthApp.getOauthConsumerKey());
    } catch (IdentityOAuthAdminException e) {
        throw handleOAuthException(e);
    }
}
 
Example #22
Source File: OAuthInboundFunctions.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
private static APIError handleOAuthException(IdentityOAuthAdminException e) {

        String message = "Error while Creating/Updating OAuth2/OpenIDConnect configuration. " + e.getMessage();
        if (e instanceof IdentityOAuthClientException) {
            return buildBadRequestError(message);
        }
        return buildServerError(message, e);
    }
 
Example #23
Source File: OAuthInboundFunctions.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
public static InboundAuthenticationRequestConfig putOAuthInbound(ServiceProvider application,
                                                                 OpenIDConnectConfiguration oidcConfigModel) {

    // First we identify whether this is a insert or update.
    try {
        String currentClientId = InboundFunctions.getInboundAuthKey(application, StandardInboundProtocols.OAUTH2);
        if (currentClientId != null) {
            // This is an update.
            OAuthConsumerAppDTO oauthApp = ApplicationManagementServiceHolder.getInstance().getOAuthAdminService
                    ().getOAuthApplicationData(currentClientId);

            if (!StringUtils.equals(oauthApp.getOauthConsumerKey(), oidcConfigModel.getClientId())) {
                throw buildBadRequestError("Invalid ClientID provided for update.");
            }

            if (!StringUtils.equals(oauthApp.getOauthConsumerSecret(), oidcConfigModel.getClientSecret())) {
                throw buildBadRequestError("Invalid ClientSecret provided for update.");
            }

            OAuthConsumerAppDTO appToUpdate = new ApiModelToOAuthConsumerApp().apply(application
                    .getApplicationName(), oidcConfigModel);
            ApplicationManagementServiceHolder.getInstance().getOAuthAdminService().updateConsumerApplication
                    (appToUpdate);

            String updatedClientId = appToUpdate.getOauthConsumerKey();
            return createInboundAuthRequestConfig(updatedClientId);
        } else {
            return createOAuthInbound(application.getApplicationName(), oidcConfigModel);
        }

    } catch (IdentityOAuthAdminException e) {
        throw handleOAuthException(e);
    }
}
 
Example #24
Source File: OidcScopeManagementService.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
/**
 * Update an existing scope.
 *
 * @param id                Scope name.
 * @param scopeUpdateObject Updated scope object.
 */
public void updateScope(String id, ScopeUpdateRequest scopeUpdateObject) {

    try {
        List<String> claimList = scopeUpdateObject.getClaims();
        String[] claimArray = claimList.toArray(new String[claimList.size()]);
        ScopeDTO scopeDTO = new ScopeDTO(id, scopeUpdateObject.getDisplayName(),
                scopeUpdateObject.getDescription(), claimArray);
        getOAuthAdminService().updateScope(scopeDTO);
    } catch (IdentityOAuthAdminException e) {
        throw handleException(e, "Server encountered an error while updating OIDC scope: " + id);
    }
}
 
Example #25
Source File: OidcScopeManagementService.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
/**
 * List all available OIDC scopes.
 *
 * @return List of scopes.
 */
public List<Scope> getScopes() {

    try {
        ScopeDTO[] scopes = getOAuthAdminService().getScopes();
        return buildScopeList(scopes);
    } catch (IdentityOAuthAdminException e) {
        throw handleException(e, "Server encountered an error while listing OIDC scopes.");
    }

}
 
Example #26
Source File: OidcScopeManagementService.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
/**
 * Get an OIDC scope.
 *
 * @param id Scope name.
 * @return Return scope details.
 */
public Scope getScope(String id) {

    try {
        ScopeDTO scopeDTO = getOAuthAdminService().getScope(id);
        return convertScopeDTOObjectToScope(scopeDTO);
    } catch (IdentityOAuthAdminException e) {
        throw handleException(e, "Server encountered an error while retrieving OIDC scope: " + id);
    }
}
 
Example #27
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 #28
Source File: OAuthApplicationMgtListener.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private String getClientSecret(String inboundAuthKey) throws IdentityOAuthAdminException {
    OAuthConsumerDAO dao = new OAuthConsumerDAO();
    return dao.getOAuthConsumerSecret(inboundAuthKey);
}
 
Example #29
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 #30
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;
}