use of org.wso2.carbon.user.api.UserStoreException 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.user.api.UserStoreException in project carbon-apimgt by wso2.
the class ImportUtils method importSubscriptions.
/**
* Import and add subscriptions of a particular application for the available APIs and API products
*
* @param subscribedAPIs Subscribed APIs
* @param userId Username of the subscriber
* @param application Application
* @param update Whether to update the application or not
* @param apiConsumer API Consumer
* @param organization Organization
* @return a list of APIIdentifiers of the skipped subscriptions
* @throws APIManagementException if an error occurs while importing and adding subscriptions
* @throws UserStoreException if an error occurs while checking whether the tenant domain exists
*/
public static List<APIIdentifier> importSubscriptions(Set<ExportedSubscribedAPI> subscribedAPIs, String userId, Application application, Boolean update, APIConsumer apiConsumer, String organization) throws APIManagementException, UserStoreException {
List<APIIdentifier> skippedAPIList = new ArrayList<>();
for (ExportedSubscribedAPI subscribedAPI : subscribedAPIs) {
APIIdentifier apiIdentifier = subscribedAPI.getApiId();
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
if (!StringUtils.isEmpty(tenantDomain) && APIUtil.isTenantAvailable(tenantDomain)) {
String name = apiIdentifier.getApiName();
String version = apiIdentifier.getVersion();
// Creating a solr compatible search query, here we will execute a search query without wildcard *s
StringBuilder searchQuery = new StringBuilder();
String[] searchCriteria = { name, "version:" + version };
for (int i = 0; i < searchCriteria.length; i++) {
if (i == 0) {
searchQuery = new StringBuilder(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
} else {
searchQuery.append(APIConstants.SEARCH_AND_TAG).append(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
}
}
Map matchedAPIs;
matchedAPIs = apiConsumer.searchPaginatedAPIs(searchQuery.toString(), tenantDomain, 0, Integer.MAX_VALUE, false);
Set<Object> apiSet = (Set<Object>) matchedAPIs.get("apis");
if (apiSet != null && !apiSet.isEmpty()) {
Object type = apiSet.iterator().next();
ApiTypeWrapper apiTypeWrapper = null;
String apiOrApiProductUuid;
// Check whether the object is ApiProduct
if (isApiProduct(type)) {
APIProduct apiProduct = (APIProduct) apiSet.iterator().next();
apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(apiProduct.getId(), organization);
} else {
API api = (API) apiSet.iterator().next();
apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(api.getId(), organization);
}
apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiOrApiProductUuid, organization);
// Tier of the imported subscription
String targetTier = subscribedAPI.getThrottlingPolicy();
// Checking whether the target tier is available
if (isTierAvailable(targetTier, apiTypeWrapper) && apiTypeWrapper.getStatus() != null && APIConstants.PUBLISHED.equals(apiTypeWrapper.getStatus())) {
apiTypeWrapper.setTier(targetTier);
// It will throw an error if subscriber already exists
if (update == null || !update) {
apiConsumer.addSubscription(apiTypeWrapper, userId, application);
} else if (!apiConsumer.isSubscribedToApp(subscribedAPI.getApiId(), userId, application.getId())) {
// on update skip subscriptions that already exists
apiConsumer.addSubscription(apiTypeWrapper, userId, application);
}
} else {
log.error("Failed to import Subscription as API/API Product " + name + "-" + version + " as one or more tiers may be unavailable or the API/API Product may not have been published ");
skippedAPIList.add(subscribedAPI.getApiId());
}
} else {
log.error("Failed to import Subscription as API " + name + "-" + version + " is not available");
skippedAPIList.add(subscribedAPI.getApiId());
}
} else {
log.error("Failed to import Subscription as Tenant domain: " + tenantDomain + " is not available");
skippedAPIList.add(subscribedAPI.getApiId());
}
}
return skippedAPIList;
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class RegistrationServiceImpl method isUserSuperAdmin.
private boolean isUserSuperAdmin(String username) {
try {
RealmConfiguration realmConfig = new RealmConfigXMLProcessor().buildRealmConfigurationFromFile();
String adminUserName = realmConfig.getAdminUserName();
return adminUserName.equalsIgnoreCase(username);
} catch (UserStoreException e) {
log.error("Error while retrieving super admin username", e);
return false;
}
}
use of org.wso2.carbon.user.api.UserStoreException 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;
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.
the class UserSubstitutionService method getSubstitute.
/**
* Return the substitute info for the given user in path parameter
* @param user
* @return SubstituteInfoResponse
* @throws URISyntaxException
*/
@GET
@Path("/{user}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getSubstitute(@PathParam("user") String user) throws UserStoreException {
if (!subsFeatureEnabled) {
return Response.status(405).build();
}
user = getTenantAwareUser(user);
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String loggedInUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (!loggedInUser.equals(user) && !isUserAuthorizedForSubstitute(loggedInUser)) {
throw new BPMNForbiddenException("Not allowed to view others substitution details. No sufficient permission");
}
SubstitutesDataModel model = UserSubstitutionUtils.getSubstituteOfUser(user, tenantId);
if (model != null) {
SubstituteInfoResponse response = new SubstituteInfoResponse();
response.setSubstitute(model.getSubstitute());
response.setAssignee(model.getUser());
response.setEnabled(model.isEnabled());
response.setStartTime(model.getSubstitutionStart());
response.setEndTime(model.getSubstitutionEnd());
return Response.ok(response).build();
} else {
return Response.status(404).build();
}
}
Aggregations