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;
}
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;
}
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);
}
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);
}
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;
}
Aggregations