Search in sources :

Example 31 with AccessTokenInfo

use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.

the class AbstractAPIManager method getApplicationKeys.

/**
 * Returns the key associated with given application id.
 *
 * @param applicationId Id of the Application.
 * @return APIKey The key of the application.
 * @throws APIManagementException
 */
protected Set<APIKey> getApplicationKeys(int applicationId, String xWso2Tenant) throws APIManagementException {
    Set<APIKey> apiKeyList = apiMgtDAO.getKeyMappingsFromApplicationId(applicationId);
    if (StringUtils.isNotEmpty(xWso2Tenant)) {
        int tenantId = APIUtil.getInternalOrganizationId(xWso2Tenant);
        // To handle choreo scenario. due to keymanagers are not per organization atm. using ST
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            xWso2Tenant = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
    }
    Set<APIKey> resultantApiKeyList = new HashSet<>();
    for (APIKey apiKey : apiKeyList) {
        String keyManagerName = apiKey.getKeyManager();
        String consumerKey = apiKey.getConsumerKey();
        String tenantDomain = this.tenantDomain;
        if (StringUtils.isNotEmpty(xWso2Tenant)) {
            tenantDomain = xWso2Tenant;
        }
        KeyManagerConfigurationDTO keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        if (keyManagerConfigurationDTO == null) {
            keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
            if (keyManagerConfigurationDTO != null) {
                keyManagerName = keyManagerConfigurationDTO.getName();
            } else {
                log.error("Key Manager: " + keyManagerName + " not found in database.");
                continue;
            }
        }
        if (tenantDomain != null && !tenantDomain.equalsIgnoreCase(keyManagerConfigurationDTO.getOrganization())) {
            continue;
        }
        KeyManager keyManager = null;
        if (keyManagerConfigurationDTO.isEnabled()) {
            keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
        } else {
            continue;
        }
        apiKey.setKeyManager(keyManagerConfigurationDTO.getName());
        if (StringUtils.isNotEmpty(consumerKey)) {
            if (keyManager != null) {
                if (APIConstants.OAuthAppMode.MAPPED.name().equalsIgnoreCase(apiKey.getCreateMode()) && !isOauthAppValidation()) {
                    resultantApiKeyList.add(apiKey);
                } else {
                    OAuthApplicationInfo oAuthApplicationInfo = null;
                    try {
                        oAuthApplicationInfo = keyManager.retrieveApplication(consumerKey);
                    } catch (APIManagementException e) {
                        log.error("Error while retrieving Application Information", e);
                        continue;
                    }
                    if (StringUtils.isNotEmpty(apiKey.getAppMetaData())) {
                        OAuthApplicationInfo storedOAuthApplicationInfo = new Gson().fromJson(apiKey.getAppMetaData(), OAuthApplicationInfo.class);
                        if (oAuthApplicationInfo == null) {
                            oAuthApplicationInfo = storedOAuthApplicationInfo;
                        } else {
                            if (StringUtils.isEmpty(oAuthApplicationInfo.getCallBackURL())) {
                                oAuthApplicationInfo.setCallBackURL(storedOAuthApplicationInfo.getCallBackURL());
                            }
                            if ("null".equalsIgnoreCase(oAuthApplicationInfo.getCallBackURL())) {
                                oAuthApplicationInfo.setCallBackURL("");
                            }
                            if (oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) == null && storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) != null) {
                                if (storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) instanceof String) {
                                    oAuthApplicationInfo.addParameter(APIConstants.JSON_GRANT_TYPES, ((String) storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES)).replace(",", " "));
                                } else {
                                    oAuthApplicationInfo.addParameter(APIConstants.JSON_GRANT_TYPES, storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
                                }
                            }
                            if (StringUtils.isEmpty(oAuthApplicationInfo.getClientSecret()) && StringUtils.isNotEmpty(storedOAuthApplicationInfo.getClientSecret())) {
                                oAuthApplicationInfo.setClientSecret(storedOAuthApplicationInfo.getClientSecret());
                            }
                        }
                    }
                    AccessTokenInfo tokenInfo = keyManager.getAccessTokenByConsumerKey(consumerKey);
                    if (oAuthApplicationInfo != null) {
                        apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
                        apiKey.setCallbackUrl(oAuthApplicationInfo.getCallBackURL());
                        apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
                        if (oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES) != null) {
                            apiKey.setAdditionalProperties(oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES));
                        }
                    }
                    if (tokenInfo != null) {
                        apiKey.setAccessToken(tokenInfo.getAccessToken());
                        apiKey.setValidityPeriod(tokenInfo.getValidityPeriod());
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Access token does not exist for Consumer Key: " + consumerKey);
                        }
                    }
                    resultantApiKeyList.add(apiKey);
                }
            } else {
                log.error("Key Manager " + keyManagerName + " not initialized in tenant " + tenantDomain);
            }
        } else {
            resultantApiKeyList.add(apiKey);
        }
    }
    return resultantApiKeyList;
}
Also used : APIKey(org.wso2.carbon.apimgt.api.model.APIKey) KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Gson(com.google.gson.Gson) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 32 with AccessTokenInfo

use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.

the class AMDefaultKeyManagerImplTest method testTokenUnlimitedExpirationTime.

@Test
public void testTokenUnlimitedExpirationTime() throws KeyManagerClientException, APIManagementException {
    String accessToken = "155ddde3-68db-35b1-82dc-1247616b2da9";
    IntrospectInfo response = new IntrospectInfo();
    response.setActive(true);
    response.setExpiry(Long.MAX_VALUE);
    response.setIat(new Date().getTime());
    Mockito.when(introspectionClient.introspect(accessToken)).thenReturn(response);
    AccessTokenInfo info = keyManager.getTokenMetaData(accessToken);
    Assert.assertEquals(Long.MAX_VALUE, info.getValidityPeriod());
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) IntrospectInfo(org.wso2.carbon.apimgt.impl.kmclient.model.IntrospectInfo) Date(java.util.Date) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 33 with AccessTokenInfo

use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.

the class DefaultKeyValidationHandler method validateToken.

@Override
public boolean validateToken(TokenValidationContext validationContext) throws APIKeyMgtException {
    // If validationInfoDTO is taken from cache, validity of the cached infoDTO is checked with each request.
    if (validationContext.isCacheHit()) {
        APIKeyValidationInfoDTO infoDTO = validationContext.getValidationInfoDTO();
        // TODO: This should only happen in GW
        boolean tokenExpired = APIUtil.isAccessTokenExpired(infoDTO);
        if (tokenExpired) {
            infoDTO.setAuthorized(false);
            infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
            log.debug("Token " + validationContext.getAccessToken() + " expired.");
            return false;
        } else {
            return true;
        }
    }
    if (StringUtils.isEmpty(validationContext.getAccessToken())) {
        APIKeyValidationInfoDTO infoDTO = validationContext.getValidationInfoDTO();
        infoDTO.setAuthorized(false);
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
        log.debug("Token Not available");
        return false;
    }
    try {
        AccessTokenInfo tokenInfo = getAccessTokenInfo(validationContext);
        if (tokenInfo == null) {
            return false;
        }
        // Setting TokenInfo in validationContext. Methods down in the chain can use TokenInfo.
        validationContext.setTokenInfo(tokenInfo);
        // TODO: Eliminate use of APIKeyValidationInfoDTO if possible
        APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
        validationContext.setValidationInfoDTO(apiKeyValidationInfoDTO);
        if (!tokenInfo.isTokenValid()) {
            apiKeyValidationInfoDTO.setAuthorized(false);
            if (tokenInfo.getErrorcode() > 0) {
                apiKeyValidationInfoDTO.setValidationStatus(tokenInfo.getErrorcode());
            } else {
                apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_GENERAL_ERROR);
            }
            return false;
        }
        apiKeyValidationInfoDTO.setKeyManager(tokenInfo.getKeyManager());
        apiKeyValidationInfoDTO.setAuthorized(tokenInfo.isTokenValid());
        apiKeyValidationInfoDTO.setEndUserName(tokenInfo.getEndUserName());
        apiKeyValidationInfoDTO.setConsumerKey(tokenInfo.getConsumerKey());
        apiKeyValidationInfoDTO.setIssuedTime(tokenInfo.getIssuedTime());
        apiKeyValidationInfoDTO.setValidityPeriod(tokenInfo.getValidityPeriod());
        if (tokenInfo.getScopes() != null) {
            Set<String> scopeSet = new HashSet<String>(Arrays.asList(tokenInfo.getScopes()));
            apiKeyValidationInfoDTO.setScopes(scopeSet);
        }
        return tokenInfo.isTokenValid();
    } catch (APIManagementException e) {
        log.error("Error while obtaining Token Metadata from Authorization Server", e);
        throw new APIKeyMgtException("Error while obtaining Token Metadata from Authorization Server");
    }
}
Also used : APIKeyMgtException(org.wso2.carbon.apimgt.keymgt.APIKeyMgtException) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) HashSet(java.util.HashSet)

Example 34 with AccessTokenInfo

use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsApplicationIdKeysKeyTypeGenerateTokenPost.

@Override
public Response applicationsApplicationIdKeysKeyTypeGenerateTokenPost(String applicationId, String keyType, ApplicationTokenGenerateRequestDTO body, String ifMatch, MessageContext messageContext) {
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyType(applicationId, keyType);
                if (appKey != null) {
                    String jsonInput = null;
                    String grantType;
                    if (ApplicationTokenGenerateRequestDTO.GrantTypeEnum.TOKEN_EXCHANGE.equals(body.getGrantType())) {
                        grantType = APIConstants.OAuthConstants.TOKEN_EXCHANGE;
                    } else {
                        grantType = APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS;
                    }
                    try {
                        // verify that the provided jsonInput is a valid json
                        if (body.getAdditionalProperties() != null && !body.getAdditionalProperties().toString().isEmpty()) {
                            jsonInput = validateAdditionalParameters(grantType, body);
                        }
                    } catch (JsonProcessingException | ParseException | ClassCastException e) {
                        RestApiUtil.handleBadRequest("Error while generating " + keyType + " token for " + "application " + applicationId + ". Invalid jsonInput '" + body.getAdditionalProperties() + "' provided.", log);
                    }
                    if (StringUtils.isNotEmpty(body.getConsumerSecret())) {
                        appKey.setConsumerSecret(body.getConsumerSecret());
                    }
                    String[] scopes = body.getScopes().toArray(new String[0]);
                    AccessTokenInfo response = apiConsumer.renewAccessToken(body.getRevokeToken(), appKey.getConsumerKey(), appKey.getConsumerSecret(), body.getValidityPeriod().toString(), scopes, jsonInput, APIConstants.KeyManager.DEFAULT_KEY_MANAGER, grantType);
                    ApplicationTokenDTO appToken = new ApplicationTokenDTO();
                    appToken.setAccessToken(response.getAccessToken());
                    appToken.setTokenScopes(Arrays.asList(response.getScopes()));
                    appToken.setValidityTime(response.getValidityPeriod());
                    return Response.ok().entity(appToken).build();
                } else {
                    RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_CONSUMER_KEY, keyType, log);
                }
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while generating " + keyType + " token for application " + applicationId, e, log);
    }
    return null;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ParseException(org.json.simple.parser.ParseException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 35 with AccessTokenInfo

use of org.wso2.carbon.identity.jwt.client.extension.dto.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)

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