Search in sources :

Example 51 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class ApplicationThrottleController method createThrottleContext.

private static ThrottleContext createThrottleContext(MessageContext synCtx, ThrottleDataHolder dataHolder, String applicationId, String policyKeyApplication) {
    // Object entryValue = synCtx.getEntry(APPLICATION_THROTTLE_POLICY_KEY);
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
    AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
    // extract the subscriber username from the auth Context
    String subscriber = authContext.getSubscriber();
    // get the tenant Domain from the subscriber
    String tenantDomain = MultitenantUtils.getTenantDomain(subscriber);
    int tenantId;
    // get the tenant domain id from the tenant domain name
    try {
        tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        handleException("Unable to Find the tenant ID using tenant: " + tenantDomain, e);
        return null;
    }
    Object entryValue = lookup(policyKeyApplication, tenantId);
    if (entryValue == null || !(entryValue instanceof OMElement)) {
        handleException("Unable to load throttling policy using key: " + policyKeyApplication);
    }
    try {
        Throttle throttle = ThrottleFactory.createMediatorThrottle(PolicyEngine.getPolicy((OMElement) entryValue));
        ThrottleContext context = throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
        dataHolder.addThrottleContext(applicationId, context);
        return context;
    } catch (ThrottleException e) {
        handleException("Error processing the throttling policy", e);
    }
    return null;
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) RealmService(org.wso2.carbon.user.core.service.RealmService) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Throttle(org.apache.synapse.commons.throttle.core.Throttle)

Example 52 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class ThrottleHandler method isSubscriptionLevelSpike.

/**
 * This method will check if coming request is hitting subscription level spikes.
 *
 * @param synCtx      synapse message context which contains message data
 * @param throttleKey subscription level throttle key.
 * @return true if message is throttled else false
 */
public boolean isSubscriptionLevelSpike(MessageContext synCtx, String throttleKey) {
    ThrottleContext subscriptionLevelSpikeArrestThrottleContext = throttle.getThrottleContext(throttleKey);
    try {
        AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
        if (subscriptionLevelSpikeArrestThrottleContext != null && authContext.getKeyType() != null) {
            org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
            ConfigurationContext cc = axis2MC.getConfigurationContext();
            subscriptionLevelSpikeArrestThrottleContext.setConfigurationContext(cc);
            subscriptionLevelSpikeArrestThrottleContext.setThrottleId(id + APIThrottleConstants.SUBSCRIPTION_BURST_LIMIT);
            AccessInformation info = getAccessInformation(subscriptionLevelSpikeArrestThrottleContext, throttleKey, throttleKey);
            if (log.isDebugEnabled()) {
                log.debug("Throttle by subscription level burst limit " + throttleKey);
                log.debug("Allowed = " + (info != null ? info.isAccessAllowed() : "false"));
            }
            if (info != null && !info.isAccessAllowed()) {
                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.SUBSCRIPTON_BURST_LIMIT_EXCEEDED);
                log.debug("Subscription level burst control limit exceeded for key " + throttleKey);
                return true;
            }
        }
    } catch (ThrottleException e) {
        log.warn("Exception occurred while performing role " + "based throttling", e);
        synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.HARD_LIMIT_EXCEEDED);
        return false;
    }
    return false;
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) AccessInformation(org.apache.synapse.commons.throttle.core.AccessInformation) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 53 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class MutualSSLAuthenticator method setAuthContext.

/**
 * To set the authentication context in current message context.
 *
 * @param messageContext Relevant message context.
 * @param x509Certificate  SSL certificate.
 * @throws APISecurityException API Security Exception.
 */
private void setAuthContext(MessageContext messageContext, X509Certificate x509Certificate) throws APISecurityException {
    String subjectDN = x509Certificate.getSubjectDN().getName();
    String uniqueIdentifier = (x509Certificate.getSerialNumber() + "_" + x509Certificate.getIssuerDN()).replaceAll(",", "#").replaceAll("\"", "'").trim();
    String tier = certificates.get(uniqueIdentifier);
    if (StringUtils.isEmpty(tier)) {
        if (log.isDebugEnabled()) {
            log.debug("The client certificate presented is available in gateway, however it was not added against " + "the API " + getAPIIdentifier(messageContext));
        }
        if (isMandatory) {
            log.error("Mutual SSL authentication failure. API is not associated with the certificate");
        }
        throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
    }
    AuthenticationContext authContext = new AuthenticationContext();
    authContext.setAuthenticated(true);
    authContext.setUsername(subjectDN);
    try {
        LdapName ldapDN = new LdapName(subjectDN);
        for (Rdn rdn : ldapDN.getRdns()) {
            if (APIConstants.CERTIFICATE_COMMON_NAME.equalsIgnoreCase(rdn.getType())) {
                authContext.setUsername((String) rdn.getValue());
            }
        }
    } catch (InvalidNameException e) {
        log.warn("Cannot get the CN name from certificate:" + e.getMessage() + ". Please make sure the " + "certificate to include a proper common name that follows naming convention.");
        authContext.setUsername(subjectDN);
    }
    authContext.setApiTier(apiLevelPolicy);
    APIIdentifier apiIdentifier = getAPIIdentifier(messageContext);
    authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
    authContext.setStopOnQuotaReach(true);
    authContext.setApiKey(uniqueIdentifier + "_" + apiIdentifier.toString());
    authContext.setTier(tier);
    /* For the mutual SSL based authenticated request, the resource level throttling is not considered, hence
        assigning the unlimited tier for that. */
    List<VerbInfoDTO> verbInfoList = new ArrayList<>(1);
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setThrottling(APIConstants.UNLIMITED_TIER);
    verbInfoList.add(verbInfoDTO);
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
    if (log.isDebugEnabled()) {
        log.debug("Auth context for the API " + getAPIIdentifier(messageContext) + ": Username[" + authContext.getUsername() + "APIKey[(" + authContext.getApiKey() + "] Tier[" + authContext.getTier() + "]");
    }
    APISecurityUtils.setAuthenticationContext(messageContext, authContext, null);
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) InvalidNameException(javax.naming.InvalidNameException) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) ArrayList(java.util.ArrayList) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Rdn(javax.naming.ldap.Rdn) LdapName(javax.naming.ldap.LdapName)

Example 54 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class JWTValidator method authenticateForGraphQLSubscription.

/**
 * Authenticate for GraphQL subscriptions API requests. This method validates the token signature, expire time and
 * subscription. The token request scopes are added to the AuthenticationContxt to validate later.
 *
 * @param signedJWTInfo SignedJWTInfo
 * @param apiContext    API context
 * @param apiVersion    API version
 * @return AuthenticationContext
 * @throws APISecurityException if an error occurs
 */
public AuthenticationContext authenticateForGraphQLSubscription(SignedJWTInfo signedJWTInfo, String apiContext, String apiVersion) throws APISecurityException {
    String tokenSignature = signedJWTInfo.getSignedJWT().getSignature().toString();
    JWTClaimsSet jwtClaimsSet = signedJWTInfo.getJwtClaimsSet();
    String jti = jwtClaimsSet.getJWTID();
    JWTValidationInfo jwtValidationInfo = validateTokenForWS(signedJWTInfo, tokenSignature, jti);
    if (jwtValidationInfo != null && jwtValidationInfo.isValid()) {
        APIKeyValidationInfoDTO apiKeyValidationInfoDTO = validateSubscriptionsForWS(jwtValidationInfo, apiContext, apiVersion);
        if (apiKeyValidationInfoDTO.isAuthorized()) {
            if (log.isDebugEnabled()) {
                log.debug("JWT authentication successful. user: " + apiKeyValidationInfoDTO.getEndUserName());
            }
            String endUserToken = generateBackendJWTForWS(jwtValidationInfo, apiKeyValidationInfoDTO, apiContext, apiVersion, tokenSignature);
            return generateAuthenticationContextForWS(jti, jwtValidationInfo, apiKeyValidationInfoDTO, endUserToken, apiVersion);
        } else {
            String message = "User is NOT authorized to access the Resource. API Subscription validation failed.";
            log.error(message);
            throw new APISecurityException(apiKeyValidationInfoDTO.getValidationStatus(), message);
        }
    } else if (!jwtValidationInfo.isValid()) {
        throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
    }
    throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)

Example 55 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class JWTValidator method generateAuthenticationContextForWS.

/**
 * Generate Authentication Context for WS API requests.
 *
 * @param jti                     JTI
 * @param jwtValidationInfo       JWTValidationInfo
 * @param apiKeyValidationInfoDTO APIKeyValidationInfoDTO
 * @param endUserToken            Enduser token
 * @param apiVersion              API Version
 * @return AuthenticationContext
 */
private AuthenticationContext generateAuthenticationContextForWS(String jti, JWTValidationInfo jwtValidationInfo, APIKeyValidationInfoDTO apiKeyValidationInfoDTO, String endUserToken, String apiVersion) {
    AuthenticationContext context = GatewayUtils.generateAuthenticationContext(jti, jwtValidationInfo, apiKeyValidationInfoDTO, endUserToken, true);
    context.setApiVersion(apiVersion);
    return context;
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)

Aggregations

AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)96 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)69 Test (org.junit.Test)69 MessageContext (org.apache.synapse.MessageContext)56 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)49 ArrayList (java.util.ArrayList)31 ConditionGroupDTO (org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)31 TreeMap (java.util.TreeMap)22 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)22 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)21 HashMap (java.util.HashMap)19 Cache (javax.cache.Cache)18 Test (org.testng.annotations.Test)18 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)18 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)17 SignedJWT (com.nimbusds.jwt.SignedJWT)16 ConditionDTO (org.wso2.carbon.apimgt.api.dto.ConditionDTO)16 ThrottleDataHolder (org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder)16 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)15 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)14