Search in sources :

Example 36 with Role

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);
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager)

Example 37 with Role

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");
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) Scope(org.wso2.carbon.apimgt.keymgt.model.entity.Scope) HashMap(java.util.HashMap) List(java.util.List) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 38 with Role

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;
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) AccessInformation(org.apache.synapse.commons.throttle.core.AccessInformation) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 39 with Role

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);
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 40 with Role

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();
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) RealmService(org.wso2.carbon.user.core.service.RealmService) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Aggregations

Test (org.testng.annotations.Test)85 ArrayList (java.util.ArrayList)74 UserStoreException (org.wso2.carbon.user.api.UserStoreException)56 HashMap (java.util.HashMap)52 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)42 Connection (java.sql.Connection)36 SQLException (java.sql.SQLException)34 Role (org.wso2.charon3.core.objects.Role)33 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)31 CharonException (org.wso2.charon3.core.exceptions.CharonException)29 RoleBasicInfo (org.wso2.carbon.identity.role.mgt.core.RoleBasicInfo)26 PreparedStatement (java.sql.PreparedStatement)25 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 RoleMapping (org.wso2.carbon.identity.application.common.model.RoleMapping)24 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)23 HashSet (java.util.HashSet)20 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)20 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)19 IdentityRoleManagementClientException (org.wso2.carbon.identity.role.mgt.core.IdentityRoleManagementClientException)19 Matchers.anyString (org.mockito.Matchers.anyString)18