Search in sources :

Example 61 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project midpoint by Evolveum.

the class SecurityEnforcerImpl method decide.

/**
	 * Spring security method. It is practically applicable only for simple cases.
	 */
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if (object instanceof MethodInvocation) {
        MethodInvocation methodInvocation = (MethodInvocation) object;
    // TODO
    } else if (object instanceof FilterInvocation) {
        FilterInvocation filterInvocation = (FilterInvocation) object;
    // TODO
    } else {
        SecurityUtil.logSecurityDeny(object, ": Unknown type of secure object");
        throw new IllegalArgumentException("Unknown type of secure object");
    }
    Object principalObject = authentication.getPrincipal();
    if (!(principalObject instanceof MidPointPrincipal)) {
        if (authentication.getPrincipal() instanceof String && "anonymousUser".equals(principalObject)) {
            SecurityUtil.logSecurityDeny(object, ": Not logged in");
            throw new InsufficientAuthenticationException("Not logged in.");
        }
        throw new IllegalArgumentException("Expected that spring security principal will be of type " + MidPointPrincipal.class.getName() + " but it was " + principalObject.getClass());
    }
    Collection<String> configActions = SecurityUtil.getActions(configAttributes);
    for (String configAction : configActions) {
        boolean isAuthorized;
        try {
            isAuthorized = isAuthorized(configAction, null, null, null, null, null);
        } catch (SchemaException e) {
            throw new SystemException(e.getMessage(), e);
        }
        if (isAuthorized) {
            return;
        }
    }
    SecurityUtil.logSecurityDeny(object, ": Not authorized", null, configActions);
    // Better message is logged.
    throw new AccessDeniedException("Not authorized");
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) SystemException(com.evolveum.midpoint.util.exception.SystemException) MethodInvocation(org.aopalliance.intercept.MethodInvocation) FilterInvocation(org.springframework.security.web.FilterInvocation) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 62 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project midpoint by Evolveum.

the class AuthenticationEvaluatorImpl method authenticateUserPreAuthenticated.

@Override
public PreAuthenticatedAuthenticationToken authenticateUserPreAuthenticated(ConnectionEnvironment connEnv, String enteredUsername) {
    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);
    // Authorizations
    if (!hasAnyAuthorization(principal)) {
        recordAuthenticationFailure(principal, connEnv, "no authorizations");
        throw new AccessDeniedException("web.security.provider.access.denied");
    }
    PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, null, principal.getAuthorities());
    recordAuthenticationSuccess(principal, connEnv);
    return token;
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 63 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project midpoint by Evolveum.

the class MidpointRestAuthenticator method handleRequest.

public void handleRequest(AuthorizationPolicy policy, Message m, ContainerRequestContext requestCtx) {
    if (policy == null) {
        RestServiceUtil.createAbortMessage(requestCtx);
        return;
    }
    T authenticationContext = createAuthenticationContext(policy, requestCtx);
    if (authenticationContext == null) {
        return;
    }
    String enteredUsername = authenticationContext.getUsername();
    if (enteredUsername == null) {
        RestServiceUtil.createAbortMessage(requestCtx);
        return;
    }
    LOGGER.trace("Authenticating username '{}' to REST service", enteredUsername);
    // We need to create task before attempting authentication. Task ID is also a session ID.
    Task task = taskManager.createTaskInstance(ModelRestService.OPERATION_REST_SERVICE);
    task.setChannel(SchemaConstants.CHANNEL_REST_URI);
    ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_REST_URI);
    connEnv.setSessionIdOverride(task.getTaskIdentifier());
    UsernamePasswordAuthenticationToken token;
    try {
        token = getAuthenticationEvaluator().authenticate(connEnv, authenticationContext);
    } catch (UsernameNotFoundException | BadCredentialsException e) {
        LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername, e.getMessage(), e);
        requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic authentication failed. Cannot authenticate user.").build());
        return;
    } catch (DisabledException | LockedException | CredentialsExpiredException | AccessDeniedException | AuthenticationCredentialsNotFoundException | AuthenticationServiceException e) {
        LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername, e.getMessage(), e);
        requestCtx.abortWith(Response.status(Status.FORBIDDEN).build());
        return;
    }
    UserType user = ((MidPointPrincipal) token.getPrincipal()).getUser();
    task.setOwner(user.asPrismObject());
    //  m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
    if (!authorizeUser(user, null, enteredUsername, connEnv, requestCtx)) {
        return;
    }
    String oid = requestCtx.getHeaderString("Switch-To-Principal");
    OperationResult result = task.getResult();
    if (StringUtils.isNotBlank(oid)) {
        try {
            PrismObject<UserType> authorizedUser = model.getObject(UserType.class, oid, null, task, result);
            task.setOwner(authorizedUser);
            if (!authorizeUser(AuthorizationConstants.AUTZ_REST_PROXY_URL, user, authorizedUser, enteredUsername, connEnv, requestCtx)) {
                return;
            }
            if (!authorizeUser(authorizedUser.asObjectable(), null, authorizedUser.getName().getOrig(), connEnv, requestCtx)) {
                return;
            }
        } catch (ObjectNotFoundException | SchemaException | SecurityViolationException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
            LOGGER.trace("Exception while authenticating user identified with '{}' to REST service: {}", oid, e.getMessage(), e);
            requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Proxy Authentication failed. Cannot authenticate user.").build());
            return;
        }
    }
    m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
    LOGGER.trace("Authorized to use REST service ({})", user);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Task(com.evolveum.midpoint.task.api.Task) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) DisabledException(org.springframework.security.authentication.DisabledException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) LockedException(org.springframework.security.authentication.LockedException) AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)

Example 64 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project midpoint by Evolveum.

the class MidPointGuiAuthorizationEvaluator method decide.

@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if (!(object instanceof FilterInvocation)) {
        return;
    }
    FilterInvocation filterInvocation = (FilterInvocation) object;
    Collection<ConfigAttribute> guiConfigAttr = new ArrayList<>();
    for (PageUrlMapping urlMapping : PageUrlMapping.values()) {
        addSecurityConfig(filterInvocation, guiConfigAttr, urlMapping.getUrl(), urlMapping.getAction());
    }
    Map<String, DisplayableValue<String>[]> actions = DescriptorLoader.getActions();
    for (Map.Entry<String, DisplayableValue<String>[]> entry : actions.entrySet()) {
        addSecurityConfig(filterInvocation, guiConfigAttr, entry.getKey(), entry.getValue());
    }
    if (configAttributes == null || guiConfigAttr.isEmpty()) {
        return;
    }
    Collection<ConfigAttribute> configAttributesToUse = guiConfigAttr;
    if (guiConfigAttr.isEmpty()) {
        configAttributesToUse = configAttributes;
    }
    try {
        securityEnforcer.decide(authentication, object, configAttributesToUse);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("DECIDE: authentication={}, object={}, configAttributesToUse={}: OK", authentication, object, configAttributesToUse);
        }
    } catch (AccessDeniedException | InsufficientAuthenticationException e) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("DECIDE: authentication={}, object={}, configAttributesToUse={}: {}", authentication, object, configAttributesToUse, e);
        }
        throw e;
    }
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) ConfigAttribute(org.springframework.security.access.ConfigAttribute) ArrayList(java.util.ArrayList) FilterInvocation(org.springframework.security.web.FilterInvocation) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) Map(java.util.Map)

Example 65 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project dhis2-core by dhis2.

the class AddUserAction method execute.

// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute() throws Exception {
    if (!userService.canAddOrUpdateUser(ugSelected)) {
        throw new AccessDeniedException("You cannot add this user");
    }
    User currentUser = currentUserService.getCurrentUser();
    // ---------------------------------------------------------------------
    // User credentials and user
    // ---------------------------------------------------------------------
    UserCredentials userCredentials = new UserCredentials();
    User user = new User();
    userCredentials.setUserInfo(user);
    user.setUserCredentials(userCredentials);
    userCredentials.setUsername(StringUtils.trimToNull(username));
    userCredentials.setExternalAuth(externalAuth);
    userCredentials.setOpenId(StringUtils.trimToNull(openId));
    userCredentials.setLdapId(StringUtils.trimToNull(ldapId));
    if (ACCOUNT_ACTION_INVITE.equals(accountAction)) {
        userCredentials.setUsername(StringUtils.trimToNull(inviteUsername));
        userCredentials.setInvitation(true);
        user.setEmail(StringUtils.trimToNull(inviteEmail));
        securityService.prepareUserForInvite(user);
    } else {
        user.setSurname(StringUtils.trimToNull(surname));
        user.setFirstName(StringUtils.trimToNull(firstName));
        user.setEmail(StringUtils.trimToNull(email));
        user.setPhoneNumber(StringUtils.trimToNull(phoneNumber));
        userService.encodeAndSetPassword(userCredentials, StringUtils.trimToNull(rawPassword));
    }
    if (jsonAttributeValues != null) {
        attributeService.updateAttributeValues(user, jsonAttributeValues);
    }
    // ---------------------------------------------------------------------
    // Organisation units
    // ---------------------------------------------------------------------
    Set<OrganisationUnit> dataCaptureOrgUnits = new HashSet<>(selectionManager.getSelectedOrganisationUnits());
    user.updateOrganisationUnits(dataCaptureOrgUnits);
    Set<OrganisationUnit> dataViewOrgUnits = new HashSet<>(selectionTreeManager.getReloadedSelectedOrganisationUnits());
    user.setDataViewOrganisationUnits(dataViewOrgUnits);
    if (dataViewOrgUnits.size() == 0 && currentUser.getDataViewOrganisationUnits().size() != 0) {
        user.setDataViewOrganisationUnits(new HashSet<>(currentUser.getDataViewOrganisationUnits()));
    }
    // ---------------------------------------------------------------------
    // User roles
    // ---------------------------------------------------------------------
    Set<UserAuthorityGroup> userAuthorityGroups = new HashSet<>();
    for (String id : urSelected) {
        userAuthorityGroups.add(userService.getUserAuthorityGroup(id));
    }
    userService.canIssueFilter(userAuthorityGroups);
    userCredentials.setUserAuthorityGroups(userAuthorityGroups);
    // ---------------------------------------------------------------------
    // Dimension constraints. Note that any new user must inherit dimension 
    // constraints if any from the current user.
    // ---------------------------------------------------------------------
    userCredentials.setCogsDimensionConstraints(new HashSet<>(currentUser.getUserCredentials().getCogsDimensionConstraints()));
    userCredentials.setCatDimensionConstraints(new HashSet<>(currentUser.getUserCredentials().getCatDimensionConstraints()));
    for (String id : dcSelected) {
        CategoryOptionGroupSet cogs = categoryService.getCategoryOptionGroupSet(id);
        if (cogs != null) {
            userCredentials.getCogsDimensionConstraints().add(cogs);
            continue;
        }
        DataElementCategory cat = categoryService.getDataElementCategory(id);
        if (cat != null) {
            userCredentials.getCatDimensionConstraints().add(cat);
            continue;
        }
    }
    // ---------------------------------------------------------------------
    // Add User
    // ---------------------------------------------------------------------
    userService.addUser(user);
    userService.addUserCredentials(userCredentials);
    // ---------------------------------------------------------------------
    // User settings
    // ---------------------------------------------------------------------
    userSettingService.saveUserSetting(UserSettingKey.UI_LOCALE, LocaleUtils.getLocale(localeUi), user);
    userSettingService.saveUserSetting(UserSettingKey.DB_LOCALE, LocaleUtils.getLocale(localeDb), user);
    if (ACCOUNT_ACTION_INVITE.equals(accountAction)) {
        RestoreOptions restoreOptions = inviteUsername == null || inviteUsername.isEmpty() ? RestoreOptions.INVITE_WITH_USERNAME_CHOICE : RestoreOptions.INVITE_WITH_DEFINED_USERNAME;
        securityService.sendRestoreMessage(userCredentials, getRootPath(), restoreOptions);
    }
    for (String id : ugSelected) {
        UserGroup userGroup = userGroupService.getUserGroup(id);
        userGroup.addUser(user);
        userGroupService.updateUserGroup(userGroup);
    }
    if (ouwtSelected != null && manager.search(OrganisationUnit.class, ouwtSelected) != null) {
        selectionManager.setSelectedOrganisationUnits(Lists.newArrayList(manager.search(OrganisationUnit.class, ouwtSelected)));
    } else {
        selectionManager.setSelectedOrganisationUnits(currentUser.getOrganisationUnits());
    }
    return SUCCESS;
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) RestoreOptions(org.hisp.dhis.security.RestoreOptions) AccessDeniedException(org.springframework.security.access.AccessDeniedException) User(org.hisp.dhis.user.User) CategoryOptionGroupSet(org.hisp.dhis.dataelement.CategoryOptionGroupSet) DataElementCategory(org.hisp.dhis.dataelement.DataElementCategory) UserGroup(org.hisp.dhis.user.UserGroup) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) UserCredentials(org.hisp.dhis.user.UserCredentials) HashSet(java.util.HashSet)

Aggregations

AccessDeniedException (org.springframework.security.access.AccessDeniedException)74 Test (org.junit.Test)21 Authentication (org.springframework.security.core.Authentication)14 ConfigAttribute (org.springframework.security.access.ConfigAttribute)13 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)8 User (amu.zhcet.data.user.User)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)6 ArrayList (java.util.ArrayList)5 AuthorizationFailureEvent (org.springframework.security.access.event.AuthorizationFailureEvent)5 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)5 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)5 MethodInvocation (org.aopalliance.intercept.MethodInvocation)4 Interpretation (org.hisp.dhis.interpretation.Interpretation)4 User (org.hisp.dhis.user.User)4 SecurityConfig (org.springframework.security.access.SecurityConfig)4 GetMapping (org.springframework.web.bind.annotation.GetMapping)4 IOException (java.io.IOException)3