Search in sources :

Example 51 with SimpleGrantedAuthority

use of org.springframework.security.core.authority.SimpleGrantedAuthority 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 52 with SimpleGrantedAuthority

use of org.springframework.security.core.authority.SimpleGrantedAuthority in project ocvn by devgateway.

the class TestUserDetailsConfiguration method testUserDetailsAdminProcuringEntity.

@Bean("testUserDetailsAdminProcuringEntity")
public UserDetailsService testUserDetailsAdminProcuringEntity() {
    return new UserDetailsService() {

        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            Person person = new Person();
            person.setUsername(username);
            person.setPassword("idontcare");
            person.setAuthorities(Arrays.asList(new SimpleGrantedAuthority("ROLE_PROCURING_ENTITY"), new SimpleGrantedAuthority("ROLE_ADMIN")));
            return personRepository.save(person);
        }
    };
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetailsService(org.springframework.security.core.userdetails.UserDetailsService) Person(org.devgateway.toolkit.persistence.dao.Person) Bean(org.springframework.context.annotation.Bean)

Example 53 with SimpleGrantedAuthority

use of org.springframework.security.core.authority.SimpleGrantedAuthority in project uplace.es by Uplace.

the class JWTFilterTest method testJWTFilter.

@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("test-user", "test-password", Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)));
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) MockFilterChain(org.springframework.mock.web.MockFilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 54 with SimpleGrantedAuthority

use of org.springframework.security.core.authority.SimpleGrantedAuthority in project vft-capture by videofirst.

the class EncryptedLockOutSupportAuthenticationProvider method getAuthorities.

// Private methods
private Collection<? extends GrantedAuthority> getAuthorities(String role) {
    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(role));
    return Collections.unmodifiableSet(authorities);
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HashSet(java.util.HashSet)

Example 55 with SimpleGrantedAuthority

use of org.springframework.security.core.authority.SimpleGrantedAuthority in project ArachneCentralAPI by OHDSI.

the class AuthenticationSystemTokenFilter method doFilter.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    String token = request.getHeader(tokenHeader);
    if (token != null) {
        DataNode dataNode = baseDataNodeService.findByToken(token).orElseThrow(() -> new BadCredentialsException("dataNode not found"));
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            GrantedAuthority dataNodeAuthority = new SimpleGrantedAuthority("ROLE_" + Roles.ROLE_DATA_NODE);
            Collection<GrantedAuthority> authorityCollection = new ArrayList<>();
            authorityCollection.add(dataNodeAuthority);
            DataNodeAuthenticationToken authentication = new DataNodeAuthenticationToken(token, dataNode, authorityCollection);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }
    filterChain.doFilter(servletRequest, servletResponse);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DataNode(com.odysseusinc.arachne.portal.model.DataNode) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Aggregations

SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)109 GrantedAuthority (org.springframework.security.core.GrantedAuthority)64 Test (org.junit.Test)49 ArrayList (java.util.ArrayList)30 Authentication (org.springframework.security.core.Authentication)27 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)22 HashSet (java.util.HashSet)14 User (org.springframework.security.core.userdetails.User)11 ObjectIdentity (org.springframework.security.acls.model.ObjectIdentity)8 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)8 MutableAcl (org.springframework.security.acls.model.MutableAcl)7 AnonymousAuthenticationToken (org.springframework.security.authentication.AnonymousAuthenticationToken)7 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)7 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)7 Before (org.junit.Before)6 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)6 ScopePathType (org.orcid.jaxb.model.message.ScopePathType)6 List (java.util.List)5 Map (java.util.Map)5 DBUnitTest (org.orcid.test.DBUnitTest)5