Search in sources :

Example 11 with KeyManagementException

use of org.wso2.carbon.apimgt.core.exception.KeyManagementException in project carbon-apimgt by wso2.

the class AuthenticatorService method createDCRApplication.

/**
 * This method creates a DCR application.
 *
 * @param clientName  Name of the application to be created
 * @param callBackURL Call back URL of the application
 * @param grantTypes  List of grant types of the application
 * @return OAUthApplicationInfo - An object with DCR Application information
 * @throws APIManagementException When creating DCR application fails
 */
private OAuthApplicationInfo createDCRApplication(String clientName, String callBackURL, List<String> grantTypes) throws APIManagementException {
    OAuthApplicationInfo oAuthApplicationInfo;
    try {
        // Here the keyType:"Application" will be passed as a default value
        // for the oAuthAppRequest constructor argument.
        // This value is not related to DCR application creation.
        OAuthAppRequest oAuthAppRequest = new OAuthAppRequest(clientName, callBackURL, AuthenticatorConstants.APPLICATION_KEY_TYPE, grantTypes);
        if (systemApplicationDao.isConsumerKeyExistForApplication(clientName)) {
            String consumerKey = systemApplicationDao.getConsumerKeyForApplication(clientName);
            oAuthApplicationInfo = getKeyManager().retrieveApplication(consumerKey);
        } else {
            oAuthApplicationInfo = getKeyManager().createApplication(oAuthAppRequest);
            if (oAuthApplicationInfo != null) {
                systemApplicationDao.addApplicationKey(clientName, oAuthApplicationInfo.getClientId());
            }
        }
    } catch (KeyManagementException | APIMgtDAOException e) {
        String errorMsg = "Error while creating the keys for OAuth application : " + clientName;
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
    return oAuthApplicationInfo;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.core.models.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 12 with KeyManagementException

use of org.wso2.carbon.apimgt.core.exception.KeyManagementException in project carbon-apimgt by wso2.

the class AuthenticatorService method getUsernameFromJWT.

private String getUsernameFromJWT(String jwt) throws KeyManagementException {
    if (jwt != null && jwt.contains(".")) {
        String[] jwtParts = jwt.split("\\.");
        JWTTokenPayload jwtHeader = new Gson().fromJson(new String(Base64.getDecoder().decode(jwtParts[1]), StandardCharsets.UTF_8), JWTTokenPayload.class);
        // Removing "@carbon.super" part explicitly (until IS side is fixed to drop it)
        String username = jwtHeader.getSub();
        username = username.replace("@carbon.super", "");
        return username;
    } else {
        log.error("JWT Parsing failed. Invalid JWT: " + jwt);
        throw new KeyManagementException("JWT Parsing failed. Invalid JWT.", ExceptionCodes.JWT_PARSING_FAILED);
    }
}
Also used : Gson(com.google.gson.Gson) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 13 with KeyManagementException

use of org.wso2.carbon.apimgt.core.exception.KeyManagementException in project carbon-apimgt by wso2.

the class AuthenticatorService method getTokens.

/**
 * This method returns the access tokens for a given application.
 *
 * @param appName           Name of the application which needs to get tokens
 * @param grantType         Grant type of the application
 * @param userName          User name of the user
 * @param password          Password of the user
 * @param refreshToken      Refresh token
 * @param validityPeriod    Validity period of tokens
 * @param authorizationCode Authorization Code
 * @return AccessTokenInfo - An object with the generated access token information
 * @throws APIManagementException When receiving access tokens fails
 */
public AccessTokenInfo getTokens(String appName, String grantType, String userName, String password, String refreshToken, long validityPeriod, String authorizationCode, String assertion, IdentityProvider identityProvider) throws APIManagementException {
    AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
    AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
    MultiEnvironmentOverview multiEnvironmentOverviewConfigs = apimConfigurationService.getEnvironmentConfigurations().getMultiEnvironmentOverview();
    boolean isMultiEnvironmentOverviewEnabled = multiEnvironmentOverviewConfigs.isEnabled();
    // Get scopes of the application
    String scopes = getApplicationScopes(appName);
    log.debug("Set scopes for {} application using swagger definition.", appName);
    // TODO: Get Consumer Key & Secret without creating a new app, from the IS side
    Map<String, String> consumerKeySecretMap = getConsumerKeySecret(appName);
    log.debug("Received consumer key & secret for {} application.", appName);
    try {
        if (KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE.equals(grantType)) {
            // Access token for authorization code grant type
            APIMAppConfigurations appConfigs = apimAppConfigurationService.getApimAppConfigurations();
            String callBackURL = appConfigs.getApimBaseUrl() + AuthenticatorConstants.AUTHORIZATION_CODE_CALLBACK_URL + appName;
            if (authorizationCode != null) {
                // Get Access & Refresh Tokens
                accessTokenRequest.setClientId(consumerKeySecretMap.get("CONSUMER_KEY"));
                accessTokenRequest.setClientSecret(consumerKeySecretMap.get("CONSUMER_SECRET"));
                accessTokenRequest.setGrantType(grantType);
                accessTokenRequest.setAuthorizationCode(authorizationCode);
                accessTokenRequest.setScopes(scopes);
                accessTokenRequest.setValidityPeriod(validityPeriod);
                accessTokenRequest.setCallbackURI(callBackURL);
                accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
            } else {
                String errorMsg = "No Authorization Code available.";
                log.error(errorMsg, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
                throw new APIManagementException(errorMsg, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
            }
        } else if (KeyManagerConstants.PASSWORD_GRANT_TYPE.equals(grantType)) {
            // Access token for password code grant type
            accessTokenRequest = AuthUtil.createAccessTokenRequest(userName, password, grantType, refreshToken, null, validityPeriod, scopes, consumerKeySecretMap.get("CONSUMER_KEY"), consumerKeySecretMap.get("CONSUMER_SECRET"));
            accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
        } else if (KeyManagerConstants.REFRESH_GRANT_TYPE.equals(grantType)) {
            accessTokenRequest = AuthUtil.createAccessTokenRequest(userName, password, grantType, refreshToken, null, validityPeriod, scopes, consumerKeySecretMap.get("CONSUMER_KEY"), consumerKeySecretMap.get("CONSUMER_SECRET"));
            accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
        } else if (isMultiEnvironmentOverviewEnabled) {
            // JWT or Custom grant type
            accessTokenRequest.setClientId(consumerKeySecretMap.get("CONSUMER_KEY"));
            accessTokenRequest.setClientSecret(consumerKeySecretMap.get("CONSUMER_SECRET"));
            accessTokenRequest.setAssertion(assertion);
            // Pass grant type to extend a custom grant instead of JWT grant in the future
            accessTokenRequest.setGrantType(KeyManagerConstants.JWT_GRANT_TYPE);
            accessTokenRequest.setScopes(scopes);
            accessTokenRequest.setValidityPeriod(validityPeriod);
            accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
            String usernameFromJWT = getUsernameFromJWT(accessTokenInfo.getIdToken());
            try {
                identityProvider.getIdOfUser(usernameFromJWT);
            } catch (IdentityProviderException e) {
                String errorMsg = "User " + usernameFromJWT + " does not exists in this environment.";
                throw new APIManagementException(errorMsg, e, ExceptionCodes.USER_NOT_AUTHENTICATED);
            }
        }
    } catch (KeyManagementException e) {
        String errorMsg = "Error while receiving tokens for OAuth application : " + appName;
        log.error(errorMsg, e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
    }
    log.debug("Received access token for {} application.", appName);
    return accessTokenInfo;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 14 with KeyManagementException

use of org.wso2.carbon.apimgt.core.exception.KeyManagementException in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testRevokeToken.

// TODO:Enable after revoke endpoint implementation done in key manager.
@Test(enabled = false)
public void testRevokeToken() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.RevokeServiceStub revokeStub = Mockito.mock(OAuth2ServiceStubs.RevokeServiceStub.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200
    Response revokeTokenResponse = Response.builder().status(200).headers(new HashMap<>()).build();
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    final String revokeToken = "xxx-revoke-token-xxx";
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(revokeTokenResponse);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - response is null
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(null);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Error occurred while revoking current access token. " + "Response is null"));
    }
    // error case - token response non-200
    final int errorCode = 500;
    Response errorResponse = Response.builder().status(errorCode).headers(new HashMap<>()).body("backend error occurred", Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(errorResponse);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Token revocation failed. HTTP error code: " + errorCode));
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) HashMap(java.util.HashMap) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Test(org.testng.annotations.Test)

Example 15 with KeyManagementException

use of org.wso2.carbon.apimgt.core.exception.KeyManagementException in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testDeleteApplication.

@Test
public void testDeleteApplication() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    final String consumerKey = "xxx-xxx-xxx-xxx";
    // happy path - 204
    Response okResponse = Response.builder().status(204).headers(new HashMap<>()).build();
    Mockito.when(dcrmServiceStub.deleteApplication(consumerKey)).thenReturn(okResponse);
    try {
        kmImpl.deleteApplication(consumerKey);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - empty consumer key
    try {
        kmImpl.deleteApplication("");
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to delete OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - empty consumer null
    try {
        kmImpl.deleteApplication(null);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to delete OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - non-204
    String errorMsg = "unknown error occurred";
    Response errorResponse = Response.builder().status(500).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.deleteApplication(consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.deleteApplication(consumerKey);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while deleting DCR application."));
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) HashMap(java.util.HashMap) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Test(org.testng.annotations.Test)

Aggregations

KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)24 Response (feign.Response)16 Test (org.testng.annotations.Test)13 HashMap (java.util.HashMap)11 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)11 Gson (com.google.gson.Gson)10 ScopeInfo (org.wso2.carbon.apimgt.core.auth.dto.ScopeInfo)9 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)7 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)7 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)7 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)6 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)6 Scope (org.wso2.carbon.apimgt.core.models.Scope)6 DCRClientInfo (org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo)5 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)5 GsonDecoder (feign.gson.GsonDecoder)4 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 AccessTokenRequest (org.wso2.carbon.apimgt.core.models.AccessTokenRequest)3 DCRError (org.wso2.carbon.apimgt.core.auth.dto.DCRError)2