use of org.wso2.carbon.apimgt.rest.api.util.MethodStats 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.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.
the class SubscriberRegistrationInterceptor method loadTenantRegistry.
@MethodStats
private void loadTenantRegistry() throws APIManagementException {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
APIUtil.loadTenantRegistry(tenantId);
APIUtil.loadTenantExternalStoreConfig(tenantDomain);
APIUtil.loadTenantWorkFlowExtensions(tenantDomain);
APIUtil.loadTenantSelfSignUpConfigurations(tenantDomain);
APIUtil.loadAndSyncTenantConf(tenantDomain);
} catch (RegistryException e) {
throw new APIManagementException("Error occured while loading registry for tenant '" + tenantDomain + "'");
}
}
use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.
the class SubscriberRegistrationInterceptor method handleMessage.
/**
* Handles the incoming message after post authentication. Only used in Store REST API, to register a newly
* signed up store user who hasn't logged in to Store for the first time either via REST API or Store UI.
* This method will register the user as a subscriber
* (register in AM_SUBSCRIBER table, add the default application for subscriber etc.).
*
* @param message cxf message
*/
@Override
@MethodStats
public void handleMessage(Message message) {
String username = RestApiCommonUtil.getLoggedInUsername();
// by-passes the interceptor if user is an annonymous user
if (username.equalsIgnoreCase(APIConstants.WSO2_ANONYMOUS_USER)) {
return;
}
// checking if the subscriber exists in the subscriber cache
Cache<String, Subscriber> subscriberCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.API_SUBSCRIBER_CACHE);
if (subscriberCache.get(username) != null) {
return;
}
// check the existence in the database
String groupId = RestApiUtil.getLoggedInUserGroupId();
String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
try {
// takes a consumer object using the user set in thread local carbon context
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
Subscriber subscriber = apiConsumer.getSubscriber(username);
if (subscriber == null) {
synchronized ((username + LOCK_POSTFIX).intern()) {
subscriber = apiConsumer.getSubscriber(username);
if (subscriber == null) {
message.getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
if (!hasSubscribeScope(message)) {
// permission. It should be allowed.
if (logger.isDebugEnabled()) {
logger.debug("User " + username + " does not have subscribe scope " + "(" + APIM_SUBSCRIBE_SCOPE + ")");
}
return;
}
if (!APIConstants.SUPER_TENANT_DOMAIN.equalsIgnoreCase(tenantDomain)) {
loadTenantRegistry();
}
apiConsumer.addSubscriber(username, groupId);
// The subscriber object added here is not a complete subscriber object. It will only contain
// username
subscriberCache.put(username, new Subscriber(username));
if (logger.isDebugEnabled()) {
logger.debug("Subscriber " + username + " added to AM_SUBSCRIBER database");
}
}
}
} else {
subscriberCache.put(username, subscriber);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Unable to add the subscriber " + username, e, logger);
}
}
use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.
the class BasicAuthenticationInterceptor method handleMessage.
/**
* This method handles the incoming message by checking if an anonymous api is being called or invalid
* authorization headers are present in the request. If not, authenticate the request.
*
* @param inMessage cxf Message
*/
@Override
@MethodStats
public void handleMessage(Message inMessage) {
// by-passes the interceptor if user calls an anonymous api
if (RestApiUtil.checkIfAnonymousAPI(inMessage)) {
return;
}
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
inMessage.put(RestApiConstants.TENANT_DOMAIN, tenantDomain);
// Extract and check if "Authorization: Basic" is present in the request. If not, by-passes the interceptor.
// If yes, set the request_authentication_scheme property in the message as basic_auth and execute the basic
// authentication flow.
AuthorizationPolicy policy = inMessage.get(AuthorizationPolicy.class);
if (policy != null) {
inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, RestApiConstants.BASIC_AUTHENTICATION);
// Extract user credentials from the auth header and validate.
String username = StringUtils.trim(policy.getUserName());
String password = StringUtils.trim(policy.getPassword());
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
String errorMessage = StringUtils.isEmpty(username) ? "username cannot be null/empty." : "password cannot be null/empty.";
log.error("Basic Authentication failed: " + errorMessage);
throw new AuthenticationException("Unauthenticated request");
} else if (!authenticate(inMessage, username, password)) {
throw new AuthenticationException("Unauthenticated request");
}
log.debug("User logged into web app using Basic Authentication");
}
}
use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.
the class TokenMergeInterceptor method handleMessage.
@MethodStats
public void handleMessage(Message message) throws Fault {
// If Authorization headers are present anonymous URI check will be skipped
String accessToken = RestApiUtil.extractOAuthAccessTokenFromMessage(message, RestApiConstants.REGEX_BEARER_PATTERN, RestApiConstants.AUTH_HEADER_NAME);
if (accessToken == null) {
return;
}
ArrayList tokenCookie = (ArrayList) ((TreeMap) (message.get(Message.PROTOCOL_HEADERS))).get(RestApiConstants.COOKIE_HEADER_NAME);
if (tokenCookie == null) {
return;
}
String cookie = tokenCookie.get(0).toString();
if (cookie == null) {
return;
}
cookie = cookie.trim();
String[] cookies = cookie.split(";");
String tokenFromCookie = Arrays.stream(cookies).filter(name -> name.contains(RestApiConstants.AUTH_COOKIE_NAME)).findFirst().orElse("");
String[] tokenParts = tokenFromCookie.split("=");
if (tokenParts.length == 2) {
// Append the token section from cookie to token part from Auth header
accessToken += tokenParts[1];
}
TreeMap headers = (TreeMap) message.get(Message.PROTOCOL_HEADERS);
ArrayList authorizationHeader = new ArrayList<>();
authorizationHeader.add(0, String.format("Bearer %s", accessToken));
headers.put(RestApiConstants.AUTH_HEADER_NAME, authorizationHeader);
message.put(Message.PROTOCOL_HEADERS, headers);
}
Aggregations