Search in sources :

Example 86 with GrantedAuthority

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

the class DhisConvenienceTest method createUserAndInjectSecurityContext.

/**
     * Creates a user and injects into the security context with username
     * "username". Requires <code>identifiableObjectManager</code> and
     * <code>userService</code> to be injected into the test.
     *
     * @param organisationUnits         the organisation units of the user.
     * @param dataViewOrganisationUnits user's data view organisation units.
     * @param allAuth                   whether to grant the ALL authority.
     * @param auths                     authorities to grant to user.
     * @return the user.
     */
protected User createUserAndInjectSecurityContext(Set<OrganisationUnit> organisationUnits, Set<OrganisationUnit> dataViewOrganisationUnits, boolean allAuth, String... auths) {
    Assert.notNull(userService, "UserService must be injected in test");
    Set<String> authorities = new HashSet<>();
    if (allAuth) {
        authorities.add(UserAuthorityGroup.AUTHORITY_ALL);
    }
    if (auths != null) {
        authorities.addAll(Lists.newArrayList(auths));
    }
    UserAuthorityGroup userAuthorityGroup = new UserAuthorityGroup();
    userAuthorityGroup.setName("Superuser");
    userAuthorityGroup.getAuthorities().addAll(authorities);
    userService.addUserAuthorityGroup(userAuthorityGroup);
    User user = createUser('A');
    if (organisationUnits != null) {
        user.setOrganisationUnits(organisationUnits);
    }
    if (dataViewOrganisationUnits != null) {
        user.setDataViewOrganisationUnits(dataViewOrganisationUnits);
    }
    user.getUserCredentials().getUserAuthorityGroups().add(userAuthorityGroup);
    userService.addUser(user);
    user.getUserCredentials().setUserInfo(user);
    userService.addUserCredentials(user.getUserCredentials());
    Set<GrantedAuthority> grantedAuths = authorities.stream().map(a -> new SimpleGrantedAuthority(a)).collect(Collectors.toSet());
    UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUserCredentials().getUsername(), user.getUserCredentials().getPassword(), grantedAuths);
    Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, "", grantedAuths);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    return user;
}
Also used : UniqunessType(org.hisp.dhis.program.UniqunessType) AopUtils(org.springframework.aop.support.AopUtils) ProgramStageDataElement(org.hisp.dhis.program.ProgramStageDataElement) ProgramMessage(org.hisp.dhis.program.message.ProgramMessage) SqlView(org.hisp.dhis.sqlview.SqlView) Autowired(org.springframework.beans.factory.annotation.Autowired) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) ProgramRuleVariableSourceType(org.hisp.dhis.programrule.ProgramRuleVariableSourceType) UserCredentials(org.hisp.dhis.user.UserCredentials) MonthlyPeriodType(org.hisp.dhis.period.MonthlyPeriodType) ValidationRuleGroup(org.hisp.dhis.validation.ValidationRuleGroup) NamespaceContext(javax.xml.namespace.NamespaceContext) DataElementCategoryService(org.hisp.dhis.dataelement.DataElementCategoryService) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) IndicatorGroup(org.hisp.dhis.indicator.IndicatorGroup) PrintWriter(java.io.PrintWriter) OrganisationUnitGroup(org.hisp.dhis.organisationunit.OrganisationUnitGroup) UserGroup(org.hisp.dhis.user.UserGroup) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance) CacheStrategy(org.hisp.dhis.common.cache.CacheStrategy) Set(java.util.Set) ProgramRuleActionType(org.hisp.dhis.programrule.ProgramRuleActionType) DataElementCategoryOption(org.hisp.dhis.dataelement.DataElementCategoryOption) Operator(org.hisp.dhis.expression.Operator) GrantedAuthority(org.springframework.security.core.GrantedAuthority) DimensionalObject(org.hisp.dhis.common.DimensionalObject) Predictor(org.hisp.dhis.predictor.Predictor) ProgramType(org.hisp.dhis.program.ProgramType) LogFactory(org.apache.commons.logging.LogFactory) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Legend(org.hisp.dhis.legend.Legend) DataDimensionType(org.hisp.dhis.common.DataDimensionType) XPath(javax.xml.xpath.XPath) Advised(org.springframework.aop.framework.Advised) DataSet(org.hisp.dhis.dataset.DataSet) ProgramStageInstance(org.hisp.dhis.program.ProgramStageInstance) Attribute(org.hisp.dhis.attribute.Attribute) Lists(com.google.common.collect.Lists) ProgramNotificationRecipient(org.hisp.dhis.program.notification.ProgramNotificationRecipient) DataElementCategoryCombo(org.hisp.dhis.dataelement.DataElementCategoryCombo) LegendSet(org.hisp.dhis.legend.LegendSet) Indicator(org.hisp.dhis.indicator.Indicator) DataElementGroupSet(org.hisp.dhis.dataelement.DataElementGroupSet) IndicatorType(org.hisp.dhis.indicator.IndicatorType) NotificationTrigger(org.hisp.dhis.program.notification.NotificationTrigger) CategoryOptionGroupSet(org.hisp.dhis.dataelement.CategoryOptionGroupSet) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) StringWriter(java.io.StringWriter) AggregationType(org.hisp.dhis.analytics.AggregationType) CategoryOptionGroup(org.hisp.dhis.dataelement.CategoryOptionGroup) IOException(java.io.IOException) OrganisationUnitGroupSet(org.hisp.dhis.organisationunit.OrganisationUnitGroupSet) SqlViewType(org.hisp.dhis.sqlview.SqlViewType) File(java.io.File) OptionSet(org.hisp.dhis.option.OptionSet) StringReader(java.io.StringReader) TrackedEntity(org.hisp.dhis.trackedentity.TrackedEntity) ProgramTrackedEntityAttribute(org.hisp.dhis.program.ProgramTrackedEntityAttribute) DataValue(org.hisp.dhis.datavalue.DataValue) PeriodType(org.hisp.dhis.period.PeriodType) CodeGenerator(org.hisp.dhis.common.CodeGenerator) Expression(org.hisp.dhis.expression.Expression) DataElementGroup(org.hisp.dhis.dataelement.DataElementGroup) OrganisationUnitLevel(org.hisp.dhis.organisationunit.OrganisationUnitLevel) IndicatorGroupSet(org.hisp.dhis.indicator.IndicatorGroupSet) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ProgramTrackedEntityAttributeGroup(org.hisp.dhis.program.ProgramTrackedEntityAttributeGroup) ValueType(org.hisp.dhis.common.ValueType) Date(java.util.Date) RenderService(org.hisp.dhis.render.RenderService) Constant(org.hisp.dhis.constant.Constant) Method(java.lang.reflect.Method) Period(org.hisp.dhis.period.Period) DataEntryForm(org.hisp.dhis.dataentryform.DataEntryForm) UserService(org.hisp.dhis.user.UserService) Chart(org.hisp.dhis.chart.Chart) ProgramNotificationTemplate(org.hisp.dhis.program.notification.ProgramNotificationTemplate) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) ProgramRule(org.hisp.dhis.programrule.ProgramRule) List(java.util.List) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) PostConstruct(javax.annotation.PostConstruct) ValidationCriteria(org.hisp.dhis.validation.ValidationCriteria) ProgramIndicator(org.hisp.dhis.program.ProgramIndicator) Authentication(org.springframework.security.core.Authentication) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute) ProgramMessageStatus(org.hisp.dhis.program.message.ProgramMessageStatus) AttributeValue(org.hisp.dhis.attribute.AttributeValue) LocationManager(org.hisp.dhis.external.location.LocationManager) ValidationNotificationTemplate(org.hisp.dhis.validation.notification.ValidationNotificationTemplate) ClassPathResource(org.springframework.core.io.ClassPathResource) ProgramRuleVariable(org.hisp.dhis.programrule.ProgramRuleVariable) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) ProgramDataElementDimensionItem(org.hisp.dhis.program.ProgramDataElementDimensionItem) ProgramRuleAction(org.hisp.dhis.programrule.ProgramRuleAction) Program(org.hisp.dhis.program.Program) DataElement(org.hisp.dhis.dataelement.DataElement) HashSet(java.util.HashSet) ProgramMessageRecipients(org.hisp.dhis.program.message.ProgramMessageRecipients) RelationshipType(org.hisp.dhis.relationship.RelationshipType) User(org.hisp.dhis.user.User) UserDetails(org.springframework.security.core.userdetails.UserDetails) XMLConstants(javax.xml.XMLConstants) InputSource(org.xml.sax.InputSource) DataElementCategory(org.hisp.dhis.dataelement.DataElementCategory) Iterator(java.util.Iterator) DataElementDomain(org.hisp.dhis.dataelement.DataElementDomain) DateTime(org.joda.time.DateTime) ValidationRule(org.hisp.dhis.validation.ValidationRule) ProgramStage(org.hisp.dhis.program.ProgramStage) ProgramStageSection(org.hisp.dhis.program.ProgramStageSection) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) XPathFactory(javax.xml.xpath.XPathFactory) Option(org.hisp.dhis.option.Option) DeliveryChannel(org.hisp.dhis.common.DeliveryChannel) Log(org.apache.commons.logging.Log) Collections(java.util.Collections) ChartType(org.hisp.dhis.chart.ChartType) Assert(org.springframework.util.Assert) User(org.hisp.dhis.user.User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) Authentication(org.springframework.security.core.Authentication) HashSet(java.util.HashSet)

Example 87 with GrantedAuthority

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

the class ModuleAccessVoter method vote.

/**
     * Votes. Votes ACCESS_ABSTAIN if the object class is not supported. Votes
     * ACCESS_GRANTED if there is a granted authority which equals attribute
     * prefix + module name, or the module name is in the always accessible set.
     * Otherwise votes ACCESS_DENIED.
     */
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    if (!supports(object.getClass())) {
        LOG.debug("ACCESS_ABSTAIN [" + object.toString() + "]: Class not supported.");
        return ACCESS_ABSTAIN;
    }
    ActionConfig target = (ActionConfig) object;
    if (alwaysAccessible.contains(target.getPackageName())) {
        LOG.debug("ACCESS_GRANTED [" + target.getPackageName() + "] by configuration.");
        return ACCESS_GRANTED;
    }
    String requiredAuthority = attributePrefix + target.getPackageName();
    for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
        if (grantedAuthority.getAuthority().equals(requiredAuthority)) {
            LOG.debug("ACCESS_GRANTED [" + target.getPackageName() + "]");
            return ACCESS_GRANTED;
        }
    }
    LOG.debug("ACCESS_DENIED [" + target.getPackageName() + "]");
    return ACCESS_DENIED;
}
Also used : ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig) GrantedAuthority(org.springframework.security.core.GrantedAuthority)

Example 88 with GrantedAuthority

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

the class ActionAccessVoter method anyAuthority.

private int anyAuthority(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    int supported = 0;
    boolean found = false;
    for (ConfigAttribute attribute : attributes) {
        if (supports(attribute)) {
            ++supported;
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                if (authority.getAuthority().equals(attribute.getAttribute())) {
                    found = true;
                    break;
                }
            }
        }
    }
    if (!found && supported > 0) {
        LOG.debug("ACCESS_DENIED [" + object.toString() + "]");
        return ACCESS_DENIED;
    }
    if (supported > 0) {
        LOG.debug("ACCESS_GRANTED [" + object.toString() + "]");
        return ACCESS_GRANTED;
    }
    LOG.debug("ACCESS_ABSTAIN [" + object.toString() + "]: No supported attributes.");
    return ACCESS_ABSTAIN;
}
Also used : ConfigAttribute(org.springframework.security.access.ConfigAttribute) GrantedAuthority(org.springframework.security.core.GrantedAuthority)

Example 89 with GrantedAuthority

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

the class AllRequiredRoleVoter method vote.

@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    int supported = 0;
    for (ConfigAttribute attribute : attributes) {
        if (this.supports(attribute)) {
            ++supported;
            boolean found = false;
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                if (attribute.getAttribute().equals(authority.getAuthority())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return ACCESS_DENIED;
            }
        }
    }
    if (supported > 0) {
        return ACCESS_GRANTED;
    }
    return ACCESS_ABSTAIN;
}
Also used : ConfigAttribute(org.springframework.security.access.ConfigAttribute) GrantedAuthority(org.springframework.security.core.GrantedAuthority)

Example 90 with GrantedAuthority

use of org.springframework.security.core.GrantedAuthority in project oc-explorer by devgateway.

the class CustomJPAUserDetailsService method loadUserByUsername.

/**
 * Returns a populated {@link UserDetails} object. The username is first
 * retrieved from the database and then mapped to a {@link UserDetails}
 * object. We are currently using the {@link User} implementation from
 * Spring
 */
@Override
public Person loadUserByUsername(final String username) throws UsernameNotFoundException {
    try {
        Person domainUser = personRepository.findByUsername(username);
        Set<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(domainUser);
        domainUser.setAuthorities(grantedAuthorities);
        return domainUser;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Person(org.devgateway.toolkit.persistence.dao.Person) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException)

Aggregations

GrantedAuthority (org.springframework.security.core.GrantedAuthority)188 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)90 Authentication (org.springframework.security.core.Authentication)55 ArrayList (java.util.ArrayList)43 Test (org.junit.Test)42 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)37 HashSet (java.util.HashSet)27 UserDetails (org.springframework.security.core.userdetails.UserDetails)16 SecurityContextImpl (org.springframework.security.core.context.SecurityContextImpl)15 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)11 Before (org.junit.Before)10 SecurityContext (org.springframework.security.core.context.SecurityContext)10 User (org.springframework.security.core.userdetails.User)10 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)10 DefaultGrantedAuthority (eu.bcvsolutions.idm.core.security.api.domain.DefaultGrantedAuthority)9 List (java.util.List)9 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)9 IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)8