Example usage for org.springframework.security.core.authority SimpleGrantedAuthority SimpleGrantedAuthority

List of usage examples for org.springframework.security.core.authority SimpleGrantedAuthority SimpleGrantedAuthority

Introduction

In this page you can find the example usage for org.springframework.security.core.authority SimpleGrantedAuthority SimpleGrantedAuthority.

Prototype

public SimpleGrantedAuthority(String role) 

Source Link

Usage

From source file:com.ge.predix.test.utils.UaaTestUtil.java

private void createNoPolicyScopeClient(final List<String> acsZones) {
    this.createClientWithAuthorities("acs_no_policy_client", "acs_no_policy_secret",
            Arrays.asList(new SimpleGrantedAuthority[] {
                    new SimpleGrantedAuthority("predix-acs.zones." + acsZones.get(0) + ".user") }));
}

From source file:eionet.transfer.controller.UserController.java

/**
 * Save user record to database.//from  w  ww.  java 2  s .  co m
 *
 * @param user
 * @param bindingResult
 * @param model - contains attributes for the view
 * @return view name
 */
@RequestMapping("/edit")
public String editUser(Authorisation user, BindingResult bindingResult, ModelMap model) {
    ArrayList<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
    if (user.getAuthorisations() != null) {
        for (String authority : user.getAuthorisations()) {
            grantedAuthorities.add(new SimpleGrantedAuthority(authority));
        }
    }
    User userDetails = new User(user.getUserId(), "", grantedAuthorities);
    userManagementService.updateUser(userDetails);
    model.addAttribute("message",
            "User " + user.getUserId() + " updated with " + rolesAsString(user.getAuthorisations()));
    return "redirect:view";
}

From source file:com.ebay.pulsar.analytics.service.UserPermissionControlTest.java

@Test
public void testDb() throws Exception {
    RDBMS db = Mockito.mock(RDBMS.class);
    final GeneratedKeyHolder keyHolder = PowerMockito.mock(GeneratedKeyHolder.class);
    PowerMockito.whenNew(GeneratedKeyHolder.class).withNoArguments().thenReturn(keyHolder);
    when(keyHolder.getKey()).thenReturn(1L).thenReturn(2L);
    GroupService gs = (GroupService) ReflectFieldUtil.getField(control, "groupService");
    BaseDBService<?> ggs = (BaseDBService<?>) ReflectFieldUtil.getField(gs, "groupService");
    BaseDBService<?> grgs = (BaseDBService<?>) ReflectFieldUtil.getField(gs, "rightGroupService");
    BaseDBService<?> gugs = (BaseDBService<?>) ReflectFieldUtil.getField(gs, "userGroupService");
    BaseDBService<?> gus = (BaseDBService<?>) ReflectFieldUtil.getField(gs, "userService");
    ReflectFieldUtil.setField(BaseDBService.class, ggs, "db", db);
    ReflectFieldUtil.setField(BaseDBService.class, grgs, "db", db);
    ReflectFieldUtil.setField(BaseDBService.class, gugs, "db", db);
    ReflectFieldUtil.setField(BaseDBService.class, gus, "db", db);

    BaseDBService<?> rgs = (BaseDBService<?>) ReflectFieldUtil.getField(control, "rightGroupService");
    ReflectFieldUtil.setField(BaseDBService.class, rgs, "db", db);

    DashboardService ds = (DashboardService) ReflectFieldUtil.getField(control, "dashboardService");
    BaseDBService<?> dds = (BaseDBService<?>) ReflectFieldUtil.getField(ds, "dashboardService");
    BaseDBService<?> drgs = (BaseDBService<?>) ReflectFieldUtil.getField(ds, "rightGroupService");
    ReflectFieldUtil.setField(BaseDBService.class, dds, "db", db);
    ReflectFieldUtil.setField(BaseDBService.class, drgs, "db", db);

    DataSourceService dss = (DataSourceService) ReflectFieldUtil.getField(control, "datasourceService");
    BaseDBService<?> dsds = (BaseDBService<?>) ReflectFieldUtil.getField(dss, "datasourceService");
    BaseDBService<?> dsrgs = (BaseDBService<?>) ReflectFieldUtil.getField(dss, "rightGroupService");
    ReflectFieldUtil.setField(BaseDBService.class, dsds, "db", db);
    ReflectFieldUtil.setField(BaseDBService.class, dsrgs, "db", db);

    DirectSQLAccessService dqs = (DirectSQLAccessService) ReflectFieldUtil.getField(control,
            "directSQLAccessService");
    ReflectFieldUtil.setField(DirectSQLAccessService.class, dqs, "db", db);

    when(db.queryForList(Matchers.anyString(), Matchers.eq(ImmutableMap.of("userName", "qxing")),
            Matchers.eq(-1))).thenReturn(Lists.<Object>newArrayList("D1_VIEW", "D2_MANAGE", "ADD_DATASOURCE"));
    Set<SimpleGrantedAuthority> rights = control.getAllRightsForValidUser("qxing");
    Set<SimpleGrantedAuthority> sample = Sets.newHashSet(new SimpleGrantedAuthority("D1_VIEW"),
            new SimpleGrantedAuthority("D2_VIEW"), new SimpleGrantedAuthority("D2_MANAGE"),
            new SimpleGrantedAuthority("ADD_DATASOURCE"));

    //Assert.assertEquals(sample, rights);

    DBDataSource datasourceCondition = new DBDataSource();
    datasourceCondition.setOwner(uttestuser);
    datasourceCondition.setName(uttestdatasource1);
    datasourceCondition.setType("druid");
    datasourceCondition.setEndpoint("http://endpoint.test.com");
    DBDataSource datasourceCondition2 = new DBDataSource();
    datasourceCondition2.setOwner(uttestuser);
    datasourceCondition2.setName(uttestdatasource2);
    datasourceCondition2.setType("druid");
    datasourceCondition2.setEndpoint("http://endpoint.test.com");

    DBDashboard dashboardCondition = new DBDashboard();
    dashboardCondition.setOwner(uttestuser);
    dashboardCondition.setName(uttestdashbaord1);
    DBDashboard dashboardCondition2 = new DBDashboard();
    dashboardCondition2.setOwner(uttestuser);
    dashboardCondition2.setName("UTDashboard2");

    DBGroup group1 = new DBGroup();
    group1.setOwner(uttestuser);//from  w  ww.  ja va2 s  .c  om
    group1.setName(uttestgroup1);
    group1.setDisplayName("DisplayName1");

    when(db.query(Matchers.anyString(), Matchers.eq(ImmutableMap.of("owner", uttestuser)), Matchers.eq(-1),
            Matchers.argThat(new ArgumentMatcher<DBGroupMapper>() {

                @Override
                public boolean matches(Object argument) {
                    return argument.getClass().equals(DBGroupMapper.class);
                }

            }))).thenReturn(Lists.newArrayList(group1));

    when(db.query(Matchers.anyString(), Matchers.eq(ImmutableMap.of("owner", uttestuser)), Matchers.eq(-1),
            Matchers.argThat(new ArgumentMatcher<DBDashboardMapper>() {

                @Override
                public boolean matches(Object argument) {
                    return argument.getClass().equals(DBDashboardMapper.class);
                }

            }))).thenReturn(Lists.newArrayList(dashboardCondition, dashboardCondition2));

    when(db.query(Matchers.anyString(), Matchers.eq(ImmutableMap.of("owner", uttestuser)), Matchers.eq(-1),
            Matchers.argThat(new ArgumentMatcher<DBDataSourceMapper>() {

                @Override
                public boolean matches(Object argument) {
                    return argument.getClass().equals(DBDataSourceMapper.class);
                }

            }))).thenReturn(Lists.newArrayList(datasourceCondition, datasourceCondition2));

    List<String> allRightsForOwner = control.getAllRightsForOwner(uttestuser);
    System.out.println(allRightsForOwner);

    control.getAllRightsByUserName("qxing");

}

From source file:org.opendatakit.configuration.TestDigestSecurityConfiguration.java

@Bean
public UserDetailsService digestAndBasicLoginService() throws ODKDatastoreException, PropertyVetoException {
    UserDetailsServiceImpl userDetailsServiceImpl = new UserDetailsServiceImpl();
    userDetailsServiceImpl.setCredentialType(CredentialType.Username);
    userDetailsServiceImpl.setPasswordType(PasswordType.DigestAuth);
    userDetailsServiceImpl.setDatastore(testDataConfiguration.datastore());
    userDetailsServiceImpl.setUserService(testUserServiceConfiguration.userService());

    List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("AUTH_LOCAL"));
    userDetailsServiceImpl.setAuthorities(authorities);
    return userDetailsServiceImpl;
}

From source file:org.opendatakit.configuration.SecurityConfiguration.java

@Bean
public AnonymousAuthenticationFilter anonymousFilter()
        throws ODKEntityNotFoundException, ODKOverQuotaException, ODKDatastoreException, PropertyVetoException {
    String siteKey = ServerPreferencesPropertiesTable.getSiteKey(userServiceConfiguration.callingContext());
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("USER_IS_ANONYMOUS"));

    return new AnonymousAuthenticationFilter(siteKey, "anonymousUser", authorities);

}

From source file:org.ng200.openolympus.model.User.java

@JsonView(PriviligedView.class)
@Override//www.  jav  a 2  s  .c o m
public Collection<? extends GrantedAuthority> getAuthorities() {
    final Collection<GrantedAuthority> authorities = new ArrayList<>();
    final Set<Role> userRoles = this.roles;
    if (userRoles != null) {
        for (final Role role : userRoles) {
            final SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
            authorities.add(authority);
        }
    }
    return authorities;
}

From source file:it.geosolutions.geoserver.authentication.filter.GeoFenceAuthFilter.java

private void doAuth(ServletRequest request, ServletResponse response) {

    BasicUser basicUser = getBasicAuth(request);
    AuthUser authUser = null;/* w w w  .  java  2  s. c  om*/

    if (basicUser != null) {
        LOGGER.fine("Checking auth for user " + basicUser.name);
        authUser = ruleReaderService.authorize(basicUser.name, basicUser.pw);

        if (authUser == null) {
            LOGGER.info("Could not authenticate user " + basicUser.name);
        }

    } else {
        LOGGER.fine("No basicauth");
    }

    if (authUser != null) {
        LOGGER.fine("Found user " + authUser);

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(GeoServerRole.AUTHENTICATED_ROLE);

        if (authUser.getRole() == AuthUser.Role.ADMIN) {
            authorities.add(GeoServerRole.ADMIN_ROLE);
            authorities.add(new SimpleGrantedAuthority("ADMIN")); // needed for REST?!?
        } else {
            authorities.add(new SimpleGrantedAuthority(USER_ROLE)); // ??
        }

        UsernamePasswordAuthenticationToken upa = new UsernamePasswordAuthenticationToken(basicUser.name,
                basicUser.pw, authorities);
        SecurityContextHolder.getContext().setAuthentication(upa);

    } else {
        LOGGER.fine("Anonymous access");
        //
        //            Authentication authentication = new AnonymousAuthenticationToken("geoserver", "null",
        //                    Arrays.asList(new GrantedAuthority[] { new SimpleGrantedAuthority(ANONYMOUS_ROLE) }));
        //            SecurityContextHolder.getContext().setAuthentication(authentication);

    }
}

From source file:org.mitre.openid.connect.assertion.SAML3AssertionTokenEndpointFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    LOG.debug("Arrive dans attemptAuthentication");
    Authentication ret = null;//from w w w .  j  a  va 2 s .c o  m
    String SAMLResponse = request.getParameter("SAMLResponse");
    String relayState = request.getParameter(RELAYSTATE);
    if (relayState == null) {
        logger.debug("Pas de relayState null");
    } else if (relayState.isEmpty()) {
        logger.debug("Pas de relayState vide");
    } else {
        if (relayStateRepository == null) {
            relayStateRepository = ApplicationContextProvider.getApplicationContext()
                    .getBean(RelayStateRepositoryService.class);
        }

        if (relayStateRepository.existRelayState(relayState)) {
            logger.debug("retour avec relayState=" + relayState);
        } else {
            logger.error("retour avec mauvais relayState=" + relayState);
            throw new BadCredentialsException("bad csrf relayState");
        }
    }
    EIDASAuthnResponse authnResponse = null;
    IPersonalAttributeList personalAttributeList = null;
    logger.debug("Arrive dans filtre SAML attemptAuthentication");
    //spUrl = configs.getProperty(Constants.SP_URL);

    //Decodes SAML Response
    byte[] decSamlToken = EIDASUtil.decodeSAMLToken(SAMLResponse);

    //Get SAMLEngine instance

    try {
        EIDASSAMLEngine engine = SPUtil.createSAMLEngine(Constants.SP_CONF);
        //validate SAML Token
        authnResponse = engine.validateEIDASAuthnResponse(decSamlToken, request.getRemoteHost(), 0);

    } catch (EIDASSAMLEngineException e) {
        logger.error(e.getMessage());
        if (StringUtils.isEmpty(e.getErrorDetail())) {
            throw new IOException(SAML_VALIDATION_ERROR, e);
        } else {
            throw new IOException(SAML_VALIDATION_ERROR, e);
        }
    }

    Set<GrantedAuthority> authorities = new HashSet<>();
    String userId = null;
    if (authnResponse.isFail()) {
        throw new IOException("Saml Response is fail" + authnResponse.getMessage());
    } else {
        LOG.info("token saml valide cherche userId");
        personalAttributeList = authnResponse.getPersonalAttributeList();

        for (PersonalAttribute pa : personalAttributeList) {
            if (pa.getName().equalsIgnoreCase("personidentifier")) {
                userId = pa.getValue().get(0);
                break;
            }
        }
    }
    if (userId == null) {
        throw new IOException("Pas trouve personidentifier dans attributs SAML");
    }
    //ajoute les attributs de l'utilisateur
    for (String nom : lesNoms()) {
        for (PersonalAttribute pa : personalAttributeList) {
            if (pa.getName().equalsIgnoreCase(nom)) {
                authorities.add(new SimpleGrantedAuthority(pa.getValue().get(0)));
                break;
            }
        }
    }
    //attention c'est un raccourci normalement il faut passer par authentProvider !!!
    authorities.add(ROLE_CLIENT);
    authorities.add(ROLE_USER);
    authorities.add(ROLE_ADMIN);
    authorities.add(ROLE_ANONYMOUS);
    SAML2AssertionAuthenticationToken authTok = new SAML2AssertionAuthenticationToken(userId, authorities);
    authTok.setDetails(personalAttributeList);
    UserInfo userInf = new SamlUserInfo(personalAttributeList);
    if (userInfServ != null) {
        ((DefaultUserInfoService) userInfServ).addUserInfo(userInf);
    } else {
        LOG.error("marche pas injection GRRRRR !");
    }
    authTok.setAuthnResponse(authnResponse);
    ret = ((Authentication) authTok);
    return ret;
}

From source file:com.hp.autonomy.frontend.configuration.authentication.CommunityAuthenticationProviderTest.java

@Test
public void testAuthenticateReturnsCorrectUserWithDefaultRoles() {
    final UserRoles userRoles = mock(UserRoles.class);
    when(userRoles.getRoles()).thenReturn(Collections.<String>emptyList());

    when(userService.getUser(anyString(), eq(true))).thenReturn(userRoles);

    final Authentication authentication = communityAuthenticationProviderWithDefaultRoles
            .authenticate(springAuthentication);

    //noinspection unchecked
    assertThat((Iterable<GrantedAuthority>) authentication.getAuthorities(),
            hasItem(new SimpleGrantedAuthority(DEFAULT_ROLE)));
}

From source file:de.iew.framework.security.access.WebResourceAccessEvaluatorTest.java

@Test
public void testEvaluateFlagConfigAttributeIsPermitAll() throws Exception {
    // Fall 1: Nutzer ist Anonym //////////////////////////////////////////
    // Testfix erstellen
    Authentication authenticationToken = newAnonymousAuthenticationToken();

    FilterInvocation filterInvocation = new FilterInvocation("/junit", "GET");

    WebResourceAccessRule rule = new WebResourceAccessRule();
    rule.setPermitAll(true);/*from ww  w  .  ja  va2s  .  c  om*/

    FlagConfigAttribute configAttribute = new FlagConfigAttribute(rule);

    // Das Testobjekt erstellen
    WebResourceAccessEvaluator webResourceAccessEvaluator = new WebResourceAccessEvaluator();

    // Test und Auswertung
    assertTrue(webResourceAccessEvaluator.evaluate(authenticationToken, filterInvocation, configAttribute));

    // Fall 2: Nutzer ist angemeldet //////////////////////////////////////
    // Testfix erstellen
    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
    grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_JUNIT_TEST"));
    authenticationToken = new UsernamePasswordAuthenticationToken("JUnit", "JUnit", grantedAuthorities);

    rule = new WebResourceAccessRule();
    rule.setPermitAll(true);

    configAttribute = new FlagConfigAttribute(rule);

    // Das Testobjekt erstellen
    webResourceAccessEvaluator = new WebResourceAccessEvaluator();

    // Test und Auswertung
    assertTrue(webResourceAccessEvaluator.evaluate(authenticationToken, filterInvocation, configAttribute));
}