use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIUtil method createRole.
/**
* Creates a role with a given set of permissions for the specified tenant
*
* @param roleName role name
* @param permissions a set of permissions to be associated with the role
* @param tenantId id of the tenant
* @throws APIManagementException
*/
public static void createRole(String roleName, Permission[] permissions, int tenantId) throws APIManagementException {
try {
RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
UserRealm realm;
org.wso2.carbon.user.api.UserRealm tenantRealm;
UserStoreManager manager;
if (tenantId < 0) {
realm = realmService.getBootstrapRealm();
manager = realm.getUserStoreManager();
} else {
tenantRealm = realmService.getTenantUserRealm(tenantId);
manager = tenantRealm.getUserStoreManager();
}
if (!manager.isExistingRole(roleName)) {
if (log.isDebugEnabled()) {
log.debug("Creating role: " + roleName);
}
String tenantAdminName = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getRealmConfiguration().getAdminUserName();
String[] userList = new String[] { tenantAdminName };
manager.addRole(roleName, userList, permissions);
}
} catch (UserStoreException e) {
throw new APIManagementException("Error while creating role: " + roleName, e);
}
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class BasicAuthCredentialValidator method validateScopes.
/**
* Validates the roles of the given user against the roles of the scopes of the API resource.
*
* @param username given username
* @param openAPI OpenAPI of the API
* @param synCtx The message to be authenticated
* @param userRoleList The list of roles of the user
* @return true if the validation passed
* @throws APISecurityException If an authentication failure or some other error occurs
*/
@MethodStats
public boolean validateScopes(String username, OpenAPI openAPI, MessageContext synCtx, BasicAuthValidationInfoDTO basicAuthValidationInfoDTO) throws APISecurityException {
String[] userRoleList = basicAuthValidationInfoDTO.getUserRoleList();
String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
String apiElectedResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
String httpMethod = (String) axis2MessageContext.getProperty(APIConstants.DigestAuthConstants.HTTP_METHOD);
String resourceKey = apiContext + ":" + apiVersion + ":" + apiElectedResource + ":" + httpMethod;
Map<String, Scope> scopeMap = apiKeyValidator.retrieveScopes(tenantDomain);
String resourceCacheKey = resourceKey + ":" + username;
if (gatewayKeyCacheEnabled && getGatewayBasicAuthResourceCache().get(resourceCacheKey) != null && basicAuthValidationInfoDTO.isCached()) {
return true;
}
if (openAPI != null) {
// retrieve the user roles related to the scope of the API resource
List<String> resourceScopes = OpenAPIUtils.getScopesOfResource(openAPI, synCtx);
if (resourceScopes != null && resourceScopes.size() > 0) {
for (String resourceScope : resourceScopes) {
Scope scope = scopeMap.get(resourceScope);
if (scope != null) {
if (scope.getRoles().isEmpty()) {
log.debug("Scope " + resourceScope + " didn't have roles");
if (gatewayKeyCacheEnabled) {
getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
}
return true;
} else {
// any of the role of the user
if (validateInternalUserRoles(scope.getRoles(), userRoleList)) {
if (gatewayKeyCacheEnabled) {
getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
}
return true;
}
// check if the roles related to the API resource contains any of the role of the user
for (String role : userRoleList) {
if (scope.getRoles().contains(role)) {
if (gatewayKeyCacheEnabled) {
getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
}
return true;
}
}
}
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Basic Authentication: No scopes for the API resource: ".concat(resourceKey));
}
return true;
}
} else if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
HashMap<String, String> operationScopeMappingList = (HashMap<String, String>) synCtx.getProperty(APIConstants.SCOPE_OPERATION_MAPPING);
String[] operationList = ((String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE)).split(",");
for (String operation : operationList) {
String operationScope = operationScopeMappingList.get(operation);
if (operationScope != null) {
if (scopeMap.containsKey(operationScope)) {
List<String> operationRoles = scopeMap.get(operationScope).getRoles();
boolean userHasOperationRole = false;
if (operationRoles.isEmpty()) {
userHasOperationRole = true;
} else {
for (String role : userRoleList) {
if (operationRoles.contains(role)) {
userHasOperationRole = true;
break;
}
}
}
if (!userHasOperationRole) {
throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
}
} else {
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
}
}
if (gatewayKeyCacheEnabled) {
getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
}
return true;
} else {
if (log.isDebugEnabled()) {
log.debug("Basic Authentication: No OpenAPI found in the gateway for the API: ".concat(apiContext).concat(":").concat(apiVersion));
}
return true;
}
if (log.isDebugEnabled()) {
log.debug("Basic Authentication: Scope validation failed for the API resource: ".concat(apiElectedResource));
}
throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
}
use of org.wso2.carbon.identity.role.mgt.core.Role 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.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class SystemScopesIssuer method configureForJWTGrant.
protected void configureForJWTGrant(OAuthTokenReqMessageContext tokReqMsgCtx) {
SignedJWT signedJWT = null;
JWTClaimsSet claimsSet = null;
String[] roles = null;
try {
signedJWT = getSignedJWT(tokReqMsgCtx);
} catch (IdentityOAuth2Exception e) {
log.error("Couldn't retrieve signed JWT", e);
}
if (signedJWT != null) {
claimsSet = getClaimSet(signedJWT);
}
String jwtIssuer = claimsSet != null ? claimsSet.getIssuer() : null;
String tenantDomain = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();
try {
identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
if (identityProvider != null) {
if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
identityProvider = this.getResidentIDPForIssuer(tenantDomain, jwtIssuer);
if (identityProvider == null) {
log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
}
}
} else {
log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
}
} catch (IdentityProviderManagementException | IdentityOAuth2Exception e) {
log.error("Couldn't initiate identity provider instance", e);
}
try {
roles = claimsSet != null ? claimsSet.getStringArrayClaim(identityProvider.getClaimConfig().getRoleClaimURI()) : null;
} catch (ParseException e) {
log.error("Couldn't retrieve roles:", e);
}
List<String> updatedRoles = new ArrayList<>();
if (roles != null) {
for (String role : roles) {
String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, role);
if (updatedRoleClaimValue != null) {
updatedRoles.add(updatedRoleClaimValue);
} else {
updatedRoles.add(role);
}
}
}
AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
Map<ClaimMapping, String> userAttributes = user.getUserAttributes();
String roleClaim = identityProvider.getClaimConfig().getRoleClaimURI();
if (roleClaim != null) {
userAttributes.put(ClaimMapping.build(roleClaim, roleClaim, null, false), updatedRoles.toString().replace(" ", ""));
tokReqMsgCtx.addProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM, roleClaim);
}
user.setUserAttributes(userAttributes);
tokReqMsgCtx.setAuthorizedUser(user);
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class UserPostSelfRegistrationHandler method executeUserRegistrationWorkflow.
/**
* This method adds new role to the existing user roles
* @param tenantDomain tenant domain extracted from the event
* @param userName username extracted from the event
* @throws org.wso2.carbon.identity.recovery.IdentityRecoveryServerException when unable to retrieve
* userStoreManager instance
*/
private void executeUserRegistrationWorkflow(String tenantDomain, String userName) throws org.wso2.carbon.identity.recovery.IdentityRecoveryServerException {
try {
// Realm service is used for user management tasks
RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
UserStoreManager userStoreManager;
try {
userStoreManager = realmService.getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getUserStoreManager();
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, userName, e);
}
// Start a tenant flow
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setTenantId(IdentityTenantUtil.getTenantId(tenantDomain));
carbonContext.setTenantDomain(tenantDomain);
if (userStoreManager.isExistingUser(userName)) {
List<String> roleList = asList(userStoreManager.getRoleListOfUser(userName));
// User should have selfSignup role. Checking whether the user is in the new role
if (roleList.contains(SELF_SIGNUP_ROLE) && !roleList.contains(SUBSCRIBER_ROLE)) {
WorkflowExecutor userSignUpWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
// initiate a new signup workflow
WorkflowDTO signUpWFDto = new WorkflowDTO();
signUpWFDto.setWorkflowReference(userName);
signUpWFDto.setStatus(WorkflowStatus.CREATED);
signUpWFDto.setCreatedTime(System.currentTimeMillis());
signUpWFDto.setTenantDomain(tenantDomain);
signUpWFDto.setTenantId(IdentityTenantUtil.getTenantId(tenantDomain));
signUpWFDto.setExternalWorkflowReference(userSignUpWFExecutor.generateUUID());
signUpWFDto.setWorkflowType(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
signUpWFDto.setCallbackUrl(userSignUpWFExecutor.getCallbackURL());
userSignUpWFExecutor.execute(signUpWFDto);
}
}
} catch (UserStoreException | WorkflowException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, userName, e);
} finally {
Utils.clearArbitraryProperties();
PrivilegedCarbonContext.endTenantFlow();
}
}
Aggregations