List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities)
AuthenticationManager
or AuthenticationProvider
implementations that are satisfied with producing a trusted (i.e. From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java
@Test public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException { String expectedJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\"," + " \"principal\": \"user1\", \"credentials\": \"password\", \"authenticated\": true, \"details\": null, " + "\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]], \"name\": \"user1\"}"; UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user1", "password", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); String serializedJson = buildObjectMapper().writeValueAsString(token); JSONAssert.assertEquals(expectedJson, serializedJson, true); }
From source file:fr.gael.dhus.service.TestNetworkService.java
@BeforeClass public void setUp() { String name = "authenticateduser"; this.user = new User(); this.user.setUsername(name); this.user.setPassword("test"); this.user.setEmail("test@test.com"); this.user.setCountry("France"); ApplicationContextProvider.getBean(UserDao.class).create(this.user); Set<GrantedAuthority> roles = new HashSet<>(); roles.add(new SimpleGrantedAuthority(Role.DOWNLOAD.getAuthority())); roles.add(new SimpleGrantedAuthority(Role.SEARCH.getAuthority())); roles.add(new SimpleGrantedAuthority(Role.USER_MANAGER.getAuthority())); SandBoxUser user = new SandBoxUser(name, name, true, 0, roles); auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(), roles); SecurityContextHolder.getContext().setAuthentication(auth); }
From source file:com.boundlessgeo.geoserver.api.controllers.MapControllerTest.java
@Before public void setUpAuth() { GeoServerUser bob = GeoServerUser.createDefaultAdmin(); //GroupAdminProperty.set(bob.getProperties(), new String[]{"users"}); Authentication auth = new UsernamePasswordAuthenticationToken(bob, bob.getPassword(), Collections.singletonList(GeoServerRole.GROUP_ADMIN_ROLE)); SecurityContextHolder.getContext().setAuthentication(auth); }
From source file:com.trenako.web.security.SpringSignupService.java
@Override public void authenticate(Account account) { final Collection<? extends GrantedAuthority> authorities = Collections .unmodifiableList(AuthorityUtils.createAuthorityList("ROLE_USER")); // must authenticate 'AccountDetails' Authentication authentication = new UsernamePasswordAuthenticationToken(new AccountDetails(account), account.getPassword(), authorities); getSecurityContext().setAuthentication(authentication); }
From source file:org.apache.cxf.fediz.service.idp.service.security.GrantedAuthorityEntitlements.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try {//from w w w . j ava2 s . co m Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication(); if (currentAuth == null) { chain.doFilter(request, response); return; } final Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); if (currentAuth.getAuthorities() != null) { authorities.addAll(currentAuth.getAuthorities()); } Iterator<? extends GrantedAuthority> authIt = currentAuth.getAuthorities().iterator(); while (authIt.hasNext()) { GrantedAuthority ga = authIt.next(); String roleName = ga.getAuthority(); try { Role role = roleDAO.getRole(roleName.substring(5), Arrays.asList("all")); for (Entitlement e : role.getEntitlements()) { authorities.add(new SimpleGrantedAuthority(e.getName())); } } catch (Exception ex) { LOG.error("Role '" + roleName + "' not found"); } } if (LOG.isDebugEnabled()) { LOG.debug(authorities.toString()); } UsernamePasswordAuthenticationToken enrichedAuthentication = new UsernamePasswordAuthenticationToken( currentAuth.getName(), currentAuth.getCredentials(), authorities); enrichedAuthentication.setDetails(currentAuth.getDetails()); SecurityContextHolder.getContext().setAuthentication(enrichedAuthentication); LOG.info("Enriched AuthenticationToken added"); } catch (Exception ex) { LOG.error("Failed to enrich security context with entitlements", ex); } chain.doFilter(request, response); }
From source file:uk.org.rbc1b.roms.scheduled.PersonChangesScheduledService.java
/** * Queue up emails if there are outstanding person form changes. * Scheduled to run at 1am every day//from w w w. j a va 2 s . c o m */ // @Scheduled(cron = "*/5 * * * * ?") Test setting @Scheduled(cron = "0 0 01 * * ?") public void checkIfOutstandingChanges() { UserDetails system = userDetailsService.loadUserByUsername("System"); Authentication authentication = new UsernamePasswordAuthenticationToken(system, system.getUsername(), system.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); List<PersonChange> personChangeList = personChangeDao.findPersonChangeNotUpdated(); if (personChangeList.isEmpty()) { return; } List<EmailRecipient> mailRecipients = emailDao.getRecipientByEmailCode(VOLUNTEER_UPDATE); for (EmailRecipient mailRecipient : mailRecipients) { try { createEmailForRecipient(mailRecipient); } catch (IOException e) { LOGGER.error("Failed to send person change notification email", e); } catch (TemplateException e) { LOGGER.error("Failed to send person change notification email", e); } } }
From source file:org.opentides.util.SecurityUtilTest.java
@Test public void testGetUser() { List<GrantedAuthority> auths = new ArrayList<>(); auths.add(new SimpleGrantedAuthority("ROLE1")); auths.add(new SimpleGrantedAuthority("ROLE2")); UserDetails userDetails = new User("admin", "password", auths); SessionUser sessionUser = new SessionUser(userDetails); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(sessionUser, null, auths);/* ww w . j a v a2s. c om*/ SecurityContextHolder.getContext().setAuthentication(authentication); SecurityUtil securityUtil = new SecurityUtil(); SessionUser actual = securityUtil.getUser(); assertNotNull(actual); assertEquals("admin", actual.getUsername()); }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateUserAuthenticationConverter.java
/** * {@inheritDoc}//from w w w . j av a2s . co m */ //TODO: might be too much unnecessary validation in here @Override public Authentication extractAuthentication(final Map<String, ?> map) { // Make sure we have a client id to use as the Principle if (!map.containsKey(CLIENT_ID_KEY)) { throw new InvalidTokenException("No client id key found in map"); } final Object clientIdObject = map.get(CLIENT_ID_KEY); if (!(clientIdObject instanceof String)) { throw new InvalidTokenException("Client id wasn't string"); } final String userName = (String) clientIdObject; if (StringUtils.isBlank(userName)) { throw new InvalidTokenException("Client id was blank. Unable to use as user name"); } // Scopes were already validated in PingFederateRemoteTokenServices final Object scopeObject = map.get(SCOPE_KEY); if (!(scopeObject instanceof Collection)) { throw new InvalidTokenException("Scopes were not a collection"); } @SuppressWarnings("unchecked") final Collection<String> scopes = (Collection<String>) scopeObject; if (scopes.isEmpty()) { throw new InvalidTokenException("No scopes available. Unable to authenticate"); } // Default to user role final Set<GrantedAuthority> authorities = Sets.newHashSet(USER_AUTHORITY); scopes.stream().filter(scope -> scope.contains(GENIE_PREFIX)).distinct() .forEach(scope -> authorities.add(new SimpleGrantedAuthority( ROLE_PREFIX + StringUtils.removeStartIgnoreCase(scope, GENIE_PREFIX).toUpperCase()))); return new UsernamePasswordAuthenticationToken(userName, "N/A", authorities); }