Search in sources :

Example 26 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testSetAccessTokenData.

@Test
public void testSetAccessTokenData() throws Exception {
    // Happy Path
    APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
    EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
    Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
    APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
    APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
    Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
    // // AccessTokenInfo object
    AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
    accessTokenInfo.setIdToken("eyJ4NXQiOiJObUptT0dVeE16WmxZak0yWkRSaE5UWmxZVEExWXpkaFpUUmlPV0UwTldJMk0ySm1PVGMxWkEiLCJraWQiOiJkMGVjNTE0YTMyYjZmODhjMGFiZDEyYTI4NDA2OTliZGQzZGViYTlkIiwiYWxnIjoiUlMyNTYifQ.eyJhdF9oYXNoIjoiWGg3bFZpSDZDS2pZLXRIT09JaWN5QSIsInN1YiI6ImFkbWluIiwiYXVkIjpbInR6NlJGQnhzdV93Z0RCd3FyUThvVmo3d25FTWEiXSwiYXpwIjoidHo2UkZCeHN1X3dnREJ3cXJROG9Wajd3bkVNYSIsImF1dGhfdGltZSI6MTUwMTczMzQ1NiwiaXNzIjoiaHR0cHM6XC9cL2xvY2FsaG9zdDo5NDQzXC9vYXV0aDJcL3Rva2VuIiwiZXhwIjoxNTAxNzM3MDU3LCJpYXQiOjE1MDE3MzM0NTd9.XXX-XXX");
    accessTokenInfo.setValidityPeriod(-2L);
    accessTokenInfo.setScopes("apim:subscribe openid");
    // // Expected AuthResponseBean object
    AuthResponseBean expectedAuthResponseBean = new AuthResponseBean();
    expectedAuthResponseBean.setTokenValid(true);
    expectedAuthResponseBean.setAuthUser("admin");
    expectedAuthResponseBean.setScopes(accessTokenInfo.getScopes());
    expectedAuthResponseBean.setType(AuthenticatorConstants.BEARER_PREFIX);
    expectedAuthResponseBean.setValidityPeriod(accessTokenInfo.getValidityPeriod());
    expectedAuthResponseBean.setIdToken(accessTokenInfo.getIdToken());
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    // // Actual response
    AuthResponseBean authResponseBean = authenticatorService.getResponseBeanFromTokenInfo(accessTokenInfo);
    Assert.assertTrue(EqualsBuilder.reflectionEquals(expectedAuthResponseBean, authResponseBean));
    // Happy Path - When id token is null
    // // AccessTokenInfo object with null id token
    AccessTokenInfo invalidTokenInfo = new AccessTokenInfo();
    invalidTokenInfo.setValidityPeriod(-2L);
    invalidTokenInfo.setScopes("apim:subscribe openid");
    // // Expected AuthResponseBean object when id token is null
    AuthResponseBean expectedResponseBean = new AuthResponseBean();
    expectedResponseBean.setTokenValid(true);
    expectedResponseBean.setScopes(invalidTokenInfo.getScopes());
    expectedResponseBean.setType(AuthenticatorConstants.BEARER_PREFIX);
    expectedResponseBean.setValidityPeriod(invalidTokenInfo.getValidityPeriod());
    expectedResponseBean.setIdToken(invalidTokenInfo.getIdToken());
    expectedResponseBean.setAuthUser("admin");
    // // Actual response when id token is null
    AuthResponseBean responseBean = authenticatorService.getResponseBeanFromTokenInfo(invalidTokenInfo);
    Assert.assertTrue(EqualsBuilder.reflectionEquals(expectedResponseBean, responseBean));
    // Error Path - When parsing JWT fails and throws KeyManagementException
    // // AccessTokenInfo object with invalid ID token format
    AccessTokenInfo invalidAccessTokenInfo = new AccessTokenInfo();
    invalidAccessTokenInfo.setIdToken("xxx-invalid-id-token-xxx");
    invalidAccessTokenInfo.setValidityPeriod(-2L);
    invalidAccessTokenInfo.setScopes("apim:subscribe openid");
    try {
        AuthResponseBean errorResponseBean = authenticatorService.getResponseBeanFromTokenInfo(invalidAccessTokenInfo);
    } catch (KeyManagementException e) {
        Assert.assertEquals(900986, e.getErrorHandler().getErrorCode());
    }
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) AuthResponseBean(org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean) Test(org.junit.Test)

Example 27 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo in project carbon-apimgt by wso2.

the class AuthenticatorService method getResponseBeanFromTokenInfo.

/**
 * This method sets access token data.
 *
 * @param accessTokenInfo Information of the access token
 * @return AuthResponseBean - An object with access token data
 * @throws KeyManagementException When parsing JWT fails
 */
public AuthResponseBean getResponseBeanFromTokenInfo(AccessTokenInfo accessTokenInfo) throws KeyManagementException {
    String authUser = null;
    if (accessTokenInfo.getIdToken() != null) {
        authUser = getUsernameFromJWT(accessTokenInfo.getIdToken());
    }
    if (authUser == null) {
        authUser = AuthenticatorConstants.ADMIN_USER;
    }
    AuthResponseBean responseBean = new AuthResponseBean();
    responseBean.setTokenValid(true);
    responseBean.setAuthUser(authUser);
    responseBean.setScopes(accessTokenInfo.getScopes());
    responseBean.setType(AuthenticatorConstants.BEARER_PREFIX);
    responseBean.setValidityPeriod(accessTokenInfo.getValidityPeriod());
    responseBean.setIdToken(accessTokenInfo.getIdToken());
    return responseBean;
}
Also used : AuthResponseBean(org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean)

Example 28 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo in project product-iots by wso2.

the class DeviceTypeServiceImpl method createDownloadFile.

private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) throws DeviceManagementException, JWTClientException, APIManagerException, UserStoreException {
    // create new device id
    String deviceId = shortUUID();
    if (apiApplicationKey == null) {
        String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName();
        applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
        APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
        String[] tags = { DeviceTypeConstants.DEVICE_TYPE };
        apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true, "3600");
    }
    JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
    String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
    AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
    // create token
    String accessToken = accessTokenInfo.getAccessToken();
    String refreshToken = accessTokenInfo.getRefreshToken();
    boolean status = register(deviceId, deviceName);
    if (!status) {
        String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
        throw new DeviceManagementException(msg);
    }
    ZipUtil ziputil = new ZipUtil();
    ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId, deviceName, accessToken, refreshToken, apiApplicationKey.toString());
    return zipFile;
}
Also used : AccessTokenInfo(org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) APIManagementProviderService(org.wso2.carbon.apimgt.application.extension.APIManagementProviderService) JWTClient(org.wso2.carbon.identity.jwt.client.extension.JWTClient) ZipUtil(org.wso2.iot.sampledevice.api.util.ZipUtil) ZipArchive(org.wso2.iot.sampledevice.api.util.ZipArchive)

Example 29 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo in project carbon-apimgt by wso2.

the class AccessTokenGenerator method generateNewAccessToken.

private AccessTokenInfo generateNewAccessToken(String[] scopes) {
    try {
        String tokenEndpoint;
        int serverPort;
        URL oauthURL;
        if (StringUtils.isNotEmpty(this.tokenEndpoint)) {
            tokenEndpoint = this.tokenEndpoint;
            oauthURL = new URL(tokenEndpoint);
            serverPort = oauthURL.getPort();
        } else {
            oauthURL = new URL(oauthUrl);
            serverPort = oauthURL.getPort();
            tokenEndpoint = oauthUrl.concat("/token");
        }
        String serverProtocol = oauthURL.getProtocol();
        HttpPost request = new HttpPost(tokenEndpoint);
        HttpClient httpClient = APIUtil.getHttpClient(serverPort, serverProtocol);
        byte[] credentials = org.apache.commons.codec.binary.Base64.encodeBase64((consumerKey + ":" + consumerSecret).getBytes(StandardCharsets.UTF_8));
        request.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
        request.setHeader(APIConstants.CONTENT_TYPE_HEADER, APIConstants.CONTENT_TYPE_APPLICATION_FORM);
        List<BasicNameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair(APIConstants.TOKEN_GRANT_TYPE_KEY, APIConstants.GRANT_TYPE_VALUE));
        if (scopes != null && scopes.length > 0) {
            urlParameters.add(new BasicNameValuePair(APIConstants.OAUTH_RESPONSE_TOKEN_SCOPE, String.join(" ", scopes)));
        }
        request.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse httpResponse = httpClient.execute(request);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String payload = EntityUtils.toString(httpResponse.getEntity());
            JSONObject response = new JSONObject(payload);
            String accessToken = (String) response.get(APIConstants.OAUTH_RESPONSE_ACCESSTOKEN);
            int validityPeriod = (Integer) response.get(APIConstants.OAUTH_RESPONSE_EXPIRY_TIME) * 1000;
            long expiryTime = System.currentTimeMillis() + validityPeriod;
            if (log.isDebugEnabled()) {
                log.debug("Successfully received an access token which expires in " + expiryTime);
            }
            AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
            accessTokenInfo.setAccessToken(accessToken);
            accessTokenInfo.setIssuedTime(System.currentTimeMillis());
            accessTokenInfo.setValidityPeriod(validityPeriod);
            return accessTokenInfo;
        } else {
            log.error("Error occurred when generating a new Access token. Server responded with " + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        log.error("Error occurred when generating a new Access token", e);
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URL(java.net.URL) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) JSONObject(org.json.JSONObject) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 30 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo in project carbon-apimgt by wso2.

the class APIConsumerImplTest method testMapExistingOAuthClient.

@Test
public void testMapExistingOAuthClient() throws APIManagementException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(apiMgtDAO);
    apiConsumer.tenantDomain = "carbon.super";
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    OAuthAppRequest oAuthAppRequest = new OAuthAppRequest();
    oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo);
    BDDMockito.when(ApplicationUtils.createOauthAppRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(oAuthAppRequest);
    Mockito.when(apiMgtDAO.isKeyMappingExistsForConsumerKeyOrApplication(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true, false);
    Mockito.when(keyManager.mapOAuthApplication((OAuthAppRequest) Mockito.any())).thenReturn(oAuthApplicationInfo);
    Mockito.doNothing().when(apiMgtDAO).createApplicationKeyTypeMappingForManualClients(Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    KeyManagerConfigurationDTO keyManagerConfigurationsDto = new KeyManagerConfigurationDTO();
    keyManagerConfigurationsDto.setUuid(UUID.randomUUID().toString());
    keyManagerConfigurationsDto.setEnabled(true);
    Mockito.when(apiMgtDAO.isKeyManagerConfigurationExistByName("default", "carbon.super")).thenReturn(true);
    Mockito.when(apiMgtDAO.getKeyManagerConfigurationByName("carbon.super", "default")).thenReturn(keyManagerConfigurationsDto);
    AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
    AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
    KeyManagerConfiguration keyManagerConfiguration = new KeyManagerConfiguration();
    Mockito.when(keyManager.getKeyManagerConfiguration()).thenReturn(keyManagerConfiguration);
    BDDMockito.when(ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplicationInfo, null)).thenReturn(accessTokenRequest);
    Mockito.when(keyManager.getNewApplicationAccessToken(accessTokenRequest)).thenReturn(accessTokenInfo);
    try {
        apiConsumer.mapExistingOAuthClient("", "admin", "1", "app1", "refresh", "DEFAULT", "Resident Key Manager", "carbon.super");
        Assert.fail("Exception is not thrown when client id is already mapped to an application");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Key Mappings already exists for application"));
    }
    Assert.assertEquals(8, apiConsumer.mapExistingOAuthClient("", "admin", "1", "app1", "PRODUCTION", "DEFAULT", "Resident Key Manager", "carbon.super").size());
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) KeyManagerConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)18 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)12 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)12 Response (feign.Response)9 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)8 Gson (com.google.gson.Gson)7 Test (org.junit.Test)7 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)7 OAuth2TokenInfo (org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)7 AccessTokenRequest (org.wso2.carbon.apimgt.core.models.AccessTokenRequest)7 HashMap (java.util.HashMap)6 Test (org.testng.annotations.Test)6 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)6 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)6 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)6 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)6 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)5