Search in sources :

Example 1 with AccessTokenRequest

use of org.wso2.carbon.apimgt.core.models.AccessTokenRequest in project carbon-apimgt by wso2.

the class DefaultKeyManagerImpl method getNewAccessToken.

@Override
public AccessTokenInfo getNewAccessToken(AccessTokenRequest tokenRequest) throws KeyManagementException {
    if (tokenRequest == null) {
        throw new KeyManagementException("No information available to generate Token. AccessTokenRequest is null", ExceptionCodes.INVALID_TOKEN_REQUEST);
    }
    // Call the /revoke only if there's a token to be revoked.
    if (!StringUtils.isEmpty(tokenRequest.getTokenToRevoke())) {
        this.revokeAccessToken(tokenRequest.getTokenToRevoke(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
    }
    // When validity time set to a negative value, a token is considered never to expire.
    if (tokenRequest.getValidityPeriod() == -1L) {
        // Setting a different negative value if the set value is -1 (-1 will be ignored by TokenValidator)
        tokenRequest.setValidityPeriod(-2L);
    }
    Response response;
    try {
        if (KeyManagerConstants.CLIENT_CREDENTIALS_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generateClientCredentialsGrantAccessToken(tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else if (KeyManagerConstants.PASSWORD_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generatePasswordGrantAccessToken(tokenRequest.getResourceOwnerUsername(), tokenRequest.getResourceOwnerPassword(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else if (KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generateAuthCodeGrantAccessToken(tokenRequest.getAuthorizationCode(), tokenRequest.getCallbackURI(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else if (KeyManagerConstants.REFRESH_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generateRefreshGrantAccessToken(tokenRequest.getRefreshToken(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else if (KeyManagerConstants.JWT_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generateJWTGrantAccessToken(tokenRequest.getAssertion(), KeyManagerConstants.JWT_GRANT_TYPE, tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else {
            throw new KeyManagementException("Invalid access token request. Unsupported grant type: " + tokenRequest.getGrantType(), ExceptionCodes.INVALID_TOKEN_REQUEST);
        }
    } catch (APIManagementException ex) {
        throw new KeyManagementException("Token generation request failed. Error: " + ex.getMessage(), ex, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
    }
    if (response == null) {
        throw new KeyManagementException("Error occurred while generating an access token. " + "Response is null", ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
    }
    if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        // 200 - Success
        log.debug("A new access token is successfully generated.");
        try {
            OAuth2TokenInfo oAuth2TokenInfo = (OAuth2TokenInfo) new GsonDecoder().decode(response, OAuth2TokenInfo.class);
            AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
            accessTokenInfo.setAccessToken(oAuth2TokenInfo.getAccessToken());
            accessTokenInfo.setScopes(oAuth2TokenInfo.getScope());
            accessTokenInfo.setRefreshToken(oAuth2TokenInfo.getRefreshToken());
            accessTokenInfo.setIdToken(oAuth2TokenInfo.getIdToken());
            accessTokenInfo.setValidityPeriod(oAuth2TokenInfo.getExpiresIn());
            return accessTokenInfo;
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing token response", e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
        }
    } else {
        // Error case
        throw new KeyManagementException("Token generation request failed. HTTP error code: " + response.status() + " Error Response Body: " + response.body().toString(), ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
    }
}
Also used : OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) Response(feign.Response) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) OAuth2TokenInfo(org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)

Example 2 with AccessTokenRequest

use of org.wso2.carbon.apimgt.core.models.AccessTokenRequest 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 3 with AccessTokenRequest

use of org.wso2.carbon.apimgt.core.models.AccessTokenRequest in project carbon-apimgt by wso2.

the class AuthUtil method createAccessTokenRequest.

/**
 * This method is used to generate access token request to login for uuf apps.
 *
 * @param username username for generate token
 * @param password password for generate token
 * @param grantType grantType requested
 * @param refreshToken refreshToken if present
 * @param accessToken accessToken to revoke
 * @param validityPeriod validityPeriod for token
 * @param scopes requested scopes
 * @param clientId clientId of app
 * @param clientSecret clientSecret of app
 * @return AccessTokenRequest object
 */
public static AccessTokenRequest createAccessTokenRequest(String username, String password, String grantType, String refreshToken, String accessToken, long validityPeriod, String scopes, String clientId, String clientSecret) {
    AccessTokenRequest tokenRequest = new AccessTokenRequest();
    tokenRequest.setClientId(clientId);
    tokenRequest.setClientSecret(clientSecret);
    tokenRequest.setGrantType(grantType);
    tokenRequest.setRefreshToken(refreshToken);
    tokenRequest.setResourceOwnerUsername(username);
    tokenRequest.setResourceOwnerPassword(password);
    tokenRequest.setScopes(scopes);
    tokenRequest.setValidityPeriod(validityPeriod);
    tokenRequest.setTokenToRevoke(accessToken);
    return tokenRequest;
}
Also used : AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest)

Example 4 with AccessTokenRequest

use of org.wso2.carbon.apimgt.core.models.AccessTokenRequest in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByClientCredentialsGrant.

@Test
public void testGetNewAccessTokenByClientCredentialsGrant() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.TokenServiceStub tokenStub = Mockito.mock(OAuth2ServiceStubs.TokenServiceStub.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200 - client credentials grant type
    // //request to key manager
    AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.CLIENT_CREDENTIALS_GRANT_TYPE, null, null, null, -2L, null, null, null, null);
    // //mocked response from /token service
    OAuth2TokenInfo oAuth2TokenInfo = createTokenServiceResponse(tokenRequest);
    // //expected response from key manager
    AccessTokenInfo accessTokenInfo = createExpectedKeyManagerResponse(oAuth2TokenInfo);
    Response newTokenResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(oAuth2TokenInfo), Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generateClientCredentialsGrantAccessToken(tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(newTokenResponse);
    try {
        AccessTokenInfo newToken = kmImpl.getNewAccessToken(tokenRequest);
        Assert.assertEquals(newToken, accessTokenInfo);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) Gson(com.google.gson.Gson) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) OAuth2TokenInfo(org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo) Test(org.testng.annotations.Test)

Example 5 with AccessTokenRequest

use of org.wso2.carbon.apimgt.core.models.AccessTokenRequest in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method createTokenServiceResponse.

private OAuth2TokenInfo createTokenServiceResponse(AccessTokenRequest tokenRequestForPasswordGrant) {
    OAuth2TokenInfo oAuth2TokenInfo = new OAuth2TokenInfo();
    oAuth2TokenInfo.setAccessToken("xxx-new-token-xxx");
    oAuth2TokenInfo.setRefreshToken("xxx-new-refresh-xxx");
    oAuth2TokenInfo.setIdToken("wdewedwedwedwedwedwedvcdvflkdnjlkjbkjhbvskjhbcdkjsabcdkjsavdcsacdascdsadcasdca");
    oAuth2TokenInfo.setTokenType("Bearer");
    oAuth2TokenInfo.setExpiresIn(tokenRequestForPasswordGrant.getValidityPeriod());
    oAuth2TokenInfo.setScope(tokenRequestForPasswordGrant.getScopes());
    return oAuth2TokenInfo;
}
Also used : OAuth2TokenInfo(org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)

Aggregations

AccessTokenRequest (org.wso2.carbon.apimgt.core.models.AccessTokenRequest)11 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)9 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)8 Response (feign.Response)7 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)7 OAuth2TokenInfo (org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)7 Test (org.testng.annotations.Test)6 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)6 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)6 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)6 Gson (com.google.gson.Gson)5 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)2 GsonDecoder (feign.gson.GsonDecoder)1 IOException (java.io.IOException)1 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)1 IdentityProviderException (org.wso2.carbon.apimgt.core.exception.IdentityProviderException)1 ApplicationToken (org.wso2.carbon.apimgt.core.models.ApplicationToken)1 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)1