use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class APIMgtCacheInvalidationListener method handleCacheInvalidationMessage.
private void handleCacheInvalidationMessage(Map map) {
String cacheManagerName = (String) map.get("cacheManagerName");
String cacheName = (String) map.get("cacheName");
String cacheKey = (String) map.get("cacheKey");
String tenantDomain = (String) map.get("tenantDomain");
int tenantId = (Integer) map.get("tenantId");
String clusterDomain = (String) map.get("clusterDomain");
String nodeId = (String) map.get("nodeId");
if (!DataHolder.getNodeId().equals(nodeId) && cacheInvalidationConfiguration.getDomain().equals(clusterDomain)) {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setTenantId(tenantId);
carbonContext.setTenantDomain(tenantDomain);
CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(cacheManagerName);
Cache<Object, Object> cache = cacheManager.getCache(cacheName);
Object cacheKeyObject = constructCacheKeyObject(cacheKey);
if (cache instanceof CacheImpl) {
if (CLEAR_ALL_PREFIX.equals(cacheKeyObject)) {
((CacheImpl) cache).removeAllLocal();
} else {
((CacheImpl) cache).removeLocal(cacheKeyObject);
}
}
} catch (ClassNotFoundException e) {
log.error("Error while removing cache Object", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class OAuthJwtAuthenticatorImpl method handleScopeValidation.
/**
* Handle scope validation
*
* @param accessToken JWT token
* @param signedJWTInfo : Signed token info
* @param message : cxf Message
*/
private boolean handleScopeValidation(Message message, SignedJWTInfo signedJWTInfo, String accessToken) throws APIManagementException, ParseException {
String maskedToken = message.get(RestApiConstants.MASKED_TOKEN).toString();
OAuthTokenInfo oauthTokenInfo = new OAuthTokenInfo();
oauthTokenInfo.setAccessToken(accessToken);
oauthTokenInfo.setEndUserName(signedJWTInfo.getJwtClaimsSet().getSubject());
String scopeClaim = signedJWTInfo.getJwtClaimsSet().getStringClaim(JwtTokenConstants.SCOPE);
if (scopeClaim != null) {
String orgId = RestApiUtil.resolveOrganization(message);
String[] scopes = scopeClaim.split(JwtTokenConstants.SCOPE_DELIMITER);
scopes = java.util.Arrays.stream(scopes).filter(s -> s.contains(orgId)).map(s -> s.replace(APIConstants.URN_CHOREO + orgId + ":", "")).toArray(size -> new String[size]);
oauthTokenInfo.setScopes(scopes);
if (validateScopes(message, oauthTokenInfo)) {
// Add the user scopes list extracted from token to the cxf message
message.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, oauthTokenInfo.getScopes());
// If scope validation successful then set tenant name and user name to current context
String tenantDomain = MultitenantUtils.getTenantDomain(oauthTokenInfo.getEndUserName());
int tenantId;
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
try {
String username = oauthTokenInfo.getEndUserName();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// when the username is an email in supertenant, it has at least 2 occurrences of '@'
long count = username.chars().filter(ch -> ch == '@').count();
// in the case of email, there will be more than one '@'
boolean isEmailUsernameEnabled = Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("EnableEmailUserName"));
if (isEmailUsernameEnabled || (username.endsWith(SUPER_TENANT_SUFFIX) && count <= 1)) {
username = MultitenantUtils.getTenantAwareUsername(username);
}
}
if (log.isDebugEnabled()) {
log.debug("username = " + username + "masked token " + maskedToken);
}
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
carbonContext.setTenantDomain(tenantDomain);
carbonContext.setTenantId(tenantId);
carbonContext.setUsername(username);
message.put(RestApiConstants.SUB_ORGANIZATION, orgId);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(tenantDomain);
}
return true;
} catch (UserStoreException e) {
log.error("Error while retrieving tenant id for tenant domain: " + tenantDomain, e);
}
log.debug("Scope validation success for the token " + maskedToken);
return true;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class PreAuthenticationInterceptor method handleMessage.
@Override
@MethodStats
public void handleMessage(Message message) throws Fault {
String path = (String) message.get(Message.PATH_INFO);
if (path.contains(APIConstants.RestApiConstants.REST_API_OLD_VERSION)) {
path = path.replace("/" + APIConstants.RestApiConstants.REST_API_OLD_VERSION, "");
}
String httpMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
Dictionary<URITemplate, List<String>> allowedResourcePathsMap;
// If Authorization headers are present anonymous URI check will be skipped
ArrayList authHeaders = (ArrayList) ((TreeMap) (message.get(Message.PROTOCOL_HEADERS))).get(RestApiConstants.AUTH_HEADER_NAME);
if (authHeaders != null)
return;
// Check if the accessing URI is allowed and then authorization is skipped
try {
allowedResourcePathsMap = RestApiUtil.getAllowedURIsToMethodsMap();
Enumeration<URITemplate> uriTemplateSet = allowedResourcePathsMap.keys();
ArrayList requestedTenantDomain = (ArrayList) ((TreeMap) (message.get(Message.PROTOCOL_HEADERS))).get(RestApiConstants.HEADER_X_WSO2_TENANT);
String tenantDomain = null;
if (requestedTenantDomain != null) {
tenantDomain = RestApiUtil.getRequestedTenantDomain(requestedTenantDomain.get(0).toString());
}
if (StringUtils.isEmpty(tenantDomain)) {
tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
}
while (uriTemplateSet.hasMoreElements()) {
URITemplate uriTemplate = uriTemplateSet.nextElement();
if (uriTemplate.matches(path, new HashMap<String, String>())) {
List<String> allowedVerbs = allowedResourcePathsMap.get(uriTemplate);
if (allowedVerbs.contains(httpMethod)) {
if (StringUtils.startsWith((String) message.get(Message.BASE_PATH), "/" + RestApiConstants.REST_API_DEVELOPER_PORTAL_CONTEXT)) {
// Authentication will be skipped for /swagger.yaml, /settings, /tenants resources of
// the devportal REST API
boolean doSkipAuthentication = StringUtils.equals(path, "/" + RestApiConstants.REST_API_DEVELOPER_PORTAL_CONTEXT + RestApiConstants.RESOURCE_PATH_SWAGGER) || StringUtils.equals(path, "/" + RestApiConstants.REST_API_DEVELOPER_PORTAL_CONTEXT + RestApiConstants.REST_API_DEVELOPER_PORTAL_RESOURCE_PATH_SETTINGS) || StringUtils.equals(path, "/" + RestApiConstants.REST_API_DEVELOPER_PORTAL_CONTEXT + RestApiConstants.REST_API_DEVELOPER_PORTAL_RESOURCE_PATH_TENANTS);
if (!doSkipAuthentication) {
message.put(RestApiConstants.AUTHENTICATION_REQUIRED, !RestApiUtil.isDevPortalAnonymousEnabled(tenantDomain));
} else {
message.put(RestApiConstants.AUTHENTICATION_REQUIRED, false);
}
} else {
message.put(RestApiConstants.AUTHENTICATION_REQUIRED, false);
}
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
return;
}
}
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Unable to retrieve/process allowed URIs for REST API", e, logger);
}
}
use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class OAuthOpaqueAuthenticatorImpl method authenticate.
/**
* @param message cxf message to be authenticated
* @return true if authentication was successful else false
* @throws APIManagementException when error in authentication process
*/
@Override
public boolean authenticate(Message message) throws APIManagementException {
boolean retrievedFromInvalidTokenCache = false;
boolean retrievedFromTokenCache = false;
String accessToken = RestApiUtil.extractOAuthAccessTokenFromMessage(message, RestApiConstants.REGEX_BEARER_PATTERN, RestApiConstants.AUTH_HEADER_NAME);
OAuthTokenInfo tokenInfo = null;
RESTAPICacheConfiguration cacheConfiguration = APIUtil.getRESTAPICacheConfig();
// validate the token from cache if it is enabled
if (cacheConfiguration.isTokenCacheEnabled()) {
tokenInfo = (OAuthTokenInfo) getRESTAPITokenCache().get(accessToken);
if (tokenInfo != null) {
if (isAccessTokenExpired(tokenInfo)) {
tokenInfo.setTokenValid(false);
// remove the token from token cache and put the token into invalid token cache
// when the access token is expired
getRESTAPIInvalidTokenCache().put(accessToken, tokenInfo);
getRESTAPITokenCache().remove(accessToken);
log.error(RestApiConstants.ERROR_TOKEN_EXPIRED);
return false;
} else {
retrievedFromTokenCache = true;
}
} else {
// if the token doesn't exist in the valid token cache, then check it in the invalid token cache
tokenInfo = (OAuthTokenInfo) getRESTAPIInvalidTokenCache().get(accessToken);
if (tokenInfo != null) {
retrievedFromInvalidTokenCache = true;
}
}
}
// if the tokenInfo is null, then only retrieve the token information from the database
try {
if (tokenInfo == null) {
tokenInfo = getTokenMetaData(accessToken);
}
} catch (APIManagementException e) {
log.error("Error while retrieving token information for token: " + accessToken, e);
}
// if we got valid access token we will proceed with next
if (tokenInfo != null && tokenInfo.isTokenValid()) {
if (cacheConfiguration.isTokenCacheEnabled() && !retrievedFromTokenCache) {
// put the token info into token cache
getRESTAPITokenCache().put(accessToken, tokenInfo);
}
// If access token is valid then we will perform scope check for given resource.
if (validateScopes(message, tokenInfo)) {
// Add the user scopes list extracted from token to the cxf message
message.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, tokenInfo.getScopes());
// If scope validation successful then set tenant name and user name to current context
String tenantDomain = MultitenantUtils.getTenantDomain(tokenInfo.getEndUserName());
int tenantId;
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
try {
String username = tokenInfo.getEndUserName();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// when the username is an email in supertenant, it has at least 2 occurrences of '@'
long count = username.chars().filter(ch -> ch == '@').count();
// in the case of email, there will be more than one '@'
boolean isEmailUsernameEnabled = Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("EnableEmailUserName"));
if (isEmailUsernameEnabled || (username.endsWith(SUPER_TENANT_SUFFIX) && count <= 1)) {
username = MultitenantUtils.getTenantAwareUsername(username);
}
}
if (log.isDebugEnabled()) {
log.debug("username = " + username);
}
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
carbonContext.setTenantDomain(tenantDomain);
carbonContext.setTenantId(tenantId);
carbonContext.setUsername(username);
message.put(RestApiConstants.SUB_ORGANIZATION, tenantDomain);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(tenantDomain);
}
return true;
} catch (UserStoreException e) {
log.error("Error while retrieving tenant id for tenant domain: " + tenantDomain, e);
}
} else {
log.error(RestApiConstants.ERROR_SCOPE_VALIDATION_FAILED);
}
} else {
log.error(RestApiConstants.ERROR_TOKEN_INVALID);
if (cacheConfiguration.isTokenCacheEnabled() && !retrievedFromInvalidTokenCache) {
getRESTAPIInvalidTokenCache().put(accessToken, tokenInfo);
}
}
return false;
}
use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class JWTUtil method handleScopeValidation.
/**
* Handle scope validation
*
* @param accessToken JWT token
* @param signedJWTInfo : Signed token info
* @param message : inbound message context
*/
public static boolean handleScopeValidation(HashMap<String, Object> message, SignedJWTInfo signedJWTInfo, String accessToken) throws APIManagementException, ParseException {
String maskedToken = message.get(RestApiConstants.MASKED_TOKEN).toString();
OAuthTokenInfo oauthTokenInfo = new OAuthTokenInfo();
oauthTokenInfo.setAccessToken(accessToken);
oauthTokenInfo.setEndUserName(signedJWTInfo.getJwtClaimsSet().getSubject());
String scopeClaim = signedJWTInfo.getJwtClaimsSet().getStringClaim(APIConstants.JwtTokenConstants.SCOPE);
if (scopeClaim != null) {
String orgId = (String) message.get(RestApiConstants.ORG_ID);
String[] scopes = scopeClaim.split(APIConstants.JwtTokenConstants.SCOPE_DELIMITER);
scopes = java.util.Arrays.stream(scopes).filter(s -> s.contains(orgId)).map(s -> s.replace(APIConstants.URN_CHOREO + orgId + ":", "")).toArray(size -> new String[size]);
oauthTokenInfo.setScopes(scopes);
if (validateScopes(message, oauthTokenInfo)) {
// Add the user scopes list extracted from token to the cxf message
message.put(RestApiConstants.USER_REST_API_SCOPES, oauthTokenInfo.getScopes());
// If scope validation successful then set tenant name and user name to current context
String tenantDomain = MultitenantUtils.getTenantDomain(oauthTokenInfo.getEndUserName());
int tenantId;
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
try {
String username = oauthTokenInfo.getEndUserName();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// when the username is an email in supertenant, it has at least 2 occurrences of '@'
long count = username.chars().filter(ch -> ch == '@').count();
// in the case of email, there will be more than one '@'
boolean isEmailUsernameEnabled = Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("EnableEmailUserName"));
if (isEmailUsernameEnabled || (username.endsWith(SUPER_TENANT_SUFFIX) && count <= 1)) {
username = MultitenantUtils.getTenantAwareUsername(username);
}
}
if (log.isDebugEnabled()) {
log.debug("username = " + username + "masked token " + maskedToken);
}
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
carbonContext.setTenantDomain(tenantDomain);
carbonContext.setTenantId(tenantId);
carbonContext.setUsername(username);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(tenantDomain);
}
return true;
} catch (UserStoreException e) {
log.error("Error while retrieving tenant id for tenant domain: " + tenantDomain, e);
}
log.debug("Scope validation success for the token " + maskedToken);
return true;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
Aggregations