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:com.orange.clara.tool.service.SsoUserDetailsService.java
@Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { OAuth2Authentication oAuth2Authentication = super.loadAuthentication(accessToken); UsernamePasswordAuthenticationToken userAuthentication = (UsernamePasswordAuthenticationToken) oAuth2Authentication .getUserAuthentication();//from w w w. j a va 2 s. c o m User user = this.getUser((Map<String, Object>) userAuthentication.getDetails()); Principal principal = () -> user.getUuid(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "N/A", this.getGrantedAuthorities(user.getRoles())); token.setDetails(this.generateDetailsFromUser(user)); OAuth2Request request = new OAuth2Request(null, this.finalClientId, null, true, null, null, null, null, null); return new OAuth2Authentication(request, token); }
From source file:org.osiam.resource_server.security.authorization.AccessTokenValidationService.java
@Override public OAuth2Authentication loadAuthentication(String token) { AccessToken accessToken = validateAccessToken(token); Set<String> scopes = new HashSet<String>(); if (accessToken.getScopes() != null) { for (Scope scope : accessToken.getScopes()) { scopes.add(scope.toString()); }// ww w . j a v a2s . c om } // TODO, need more params OAuth2Request authRequest = new OAuth2Request(null, accessToken.getClientId(), null, true, scopes, null, null, null, null); Authentication auth = null; if (!accessToken.isClientOnly()) { User authUser = new User.Builder(accessToken.getUserName()).setId(accessToken.getUserId()).build(); auth = new UsernamePasswordAuthenticationToken(authUser, null, new ArrayList<GrantedAuthority>()); } return new OAuth2Authentication(authRequest, auth); }
From source file:uk.org.rbc1b.roms.scheduled.SubmitVolunteerLDCFormService.java
/** * Queue the volunteers every ten minutes for the email. *//*from w w w .j a v a2s. co m*/ @Scheduled(cron = "0 0/10 * * * ?") public void queueVolunteersForLDCFormEmail() { UserDetails system = userDetailsService.loadUserByUsername("System"); Authentication authentication = new UsernamePasswordAuthenticationToken(system, system.getUsername(), system.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); VolunteerSearchCriteria searchCriteria = new VolunteerSearchCriteria(); searchCriteria.setMaxResults(MAX_RECIPIENTS); List<Volunteer> volunteersForEmail = volunteerDao.findVolunteersWhoNeedToSubmitLDCForm(searchCriteria); for (Volunteer volunteer : volunteersForEmail) { try { Email email = submitLDCFormVolunteerEmailGenerator.generateEmailForVolunteers(volunteer); LOGGER.info("Volunteer: " + volunteer.getPersonId()); if (email != null) { emailDao.save(email); } // update the ldc email sent flag for the volunteer volunteer.setSubmitNewLDCFormEmailSent(true); volunteerDao.updateVolunteer(volunteer); } catch (IOException | TemplateException ex) { LOGGER.error("Failed to send the volunteer submit LDC form email: ", ex); } } }
From source file:com.t2tierp.controller.LoginController.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String nomeUsuario = authentication.getName(); String senha = authentication.getCredentials().toString(); try {// w ww .j ava 2 s .c o m InitialContext initialContext = new InitialContext(); dao = (UsuarioDAO) initialContext.lookup("java:comp/ejb/usuarioDAO"); Md5PasswordEncoder enc = new Md5PasswordEncoder(); senha = enc.encodePassword(nomeUsuario + senha, null); Usuario usuario = dao.getUsuario(nomeUsuario, senha); if (usuario != null) { List<PapelFuncao> funcoes = dao.getPapelFuncao(usuario); List<GrantedAuthority> grantedAuths = new ArrayList<>(); for (PapelFuncao p : funcoes) { grantedAuths.add(new SimpleGrantedAuthority(p.getFuncao().getNome())); } Authentication auth = new UsernamePasswordAuthenticationToken(nomeUsuario, senha, grantedAuths); return auth; } } catch (Exception e) { //e.printStackTrace(); } return null; }
From source file:com.exp.tracker.services.impl.JasperReportGenerationServiceTests.java
@Before public void setup() { // Sanity check Assert.assertTrue("Expected an WebApplicationContext", appContext instanceof WebApplicationContext); WebApplicationContext ctx = (WebApplicationContext) appContext; context = ctx.getServletContext();/*from ww w . ja v a 2s . c o m*/ // Set current user userDetailService = appContext.getBean(JdbcDaoImpl.class); UserDetails userDetails = userDetailService.loadUserByUsername("Admin"); Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authToken); rCtx = new MockRequestContext(); MockExternalContext ec = new MockExternalContext(); ec.setCurrentUser("Admin"); ((MockRequestContext) rCtx).setExternalContext(ec); // Create two users // Add 1st user UserBean ub1 = new UserBean(); ub1.setEmailId("a@b.com"); ub1.setEnabled(true); ub1.setFirstName("Test1"); ub1.setLastName("User1"); ub1.setMiddleInit("1"); ub1.setPassword("password"); ub1.setUsername("reptusr1"); UserBean userBean1 = userService.addUser(ub1, rCtx); Assert.assertNotNull("Failed to create user1.", userBean1); // // Add 2nd user UserBean ub2 = new UserBean(); ub2.setEmailId("a@b.com"); ub2.setEnabled(true); ub2.setFirstName("Test2"); ub2.setLastName("User2"); ub2.setMiddleInit("2"); ub2.setPassword("password"); ub2.setUsername("reptusr2"); UserBean userBean2 = userService.addUser(ub2, rCtx); Assert.assertNotNull("Failed to create user2", userBean2); // Setup an expense ExpenseDetail ed = new ExpenseDetail(); ed.setAmount(20.0F); ed.setCategory("Somecategory"); ed.setCreatedBy("Admin"); ed.setDate(new Date()); ed.setDescription("Some Expense"); ed.setPaidBy("reptusr1"); ed.setSettlementId(null); // now set shares UserShare us1 = new UserShare("reptusr1", 10.0F, 0.0F, true); UserShare us2 = new UserShare("reptusr2", 10.0F, 0.0F, true); ed.getUserShares().add(us1); ed.getUserShares().add(us2); // expenseDetail = ed; }
From source file:uk.org.rbc1b.roms.scheduled.ProjectAvailabilityEmailScheduledService.java
/** * Checks volunteers who have not been sent an email. *///w ww. j a va 2 s . co m // For testing // @Scheduled(cron = "0 0/5 * * * ?") @Scheduled(cron = "0 45 * * * ?") public void checkAvailability() { UserDetails system = userDetailsService.loadUserByUsername("System"); Authentication authentication = new UsernamePasswordAuthenticationToken(system, system.getUsername(), system.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); List<ProjectAvailability> projectAvailabilityList = projectAvailabilityDao.findUnnotifiedVolunteers(); if (projectAvailabilityList.isEmpty()) { return; } for (ProjectAvailability projectAvailability : projectAvailabilityList) { try { Email email = projectAvailabilityEmailGenerator .generateVolunteerAvailabilityRequestEmail(projectAvailability); if (email == null) { LOGGER.error("Cannot send email to RBC ID:" + projectAvailability.getPerson().getPersonId()); } else { emailDao.save(email); projectAvailability.setEmailSent(true); projectAvailabilityDao.update(projectAvailability); } } catch (IOException | TemplateException e) { LOGGER.error("Failed to send availability email:", e); } } }
From source file:org.jblogcms.core.security.service.SecurityServiceImpl.java
@Override public void signIn(Account account) { Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); SimpleGrantedAuthority authority = new SimpleGrantedAuthority(account.getAccountRole().toString()); authorities.add(authority);//from w w w .j a va2s. c o m if (account.getPassword() == null) { account.setPassword("socialpass"); } AccountDetails userDetails = new AccountDetails(account.getEmail(), account.getPassword(), authorities); userDetails.setSocialSignInProvider(account.getSignInProvider()); userDetails.setId(account.getId()); userDetails.setLastName(account.getLastName()); userDetails.setFirstName(account.getFirstName()); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }
From source file:hr.foi.sis.conf.PBKDF2AuthProvider.java
@Override public Authentication authenticate(Authentication a) throws AuthenticationException { String username = a.getName(); Logger.getLogger("Auth").log(Level.INFO, "POST on login username -- " + username); if (username == null) throw new BadCredentialsException("Username not found."); String password = (String) a.getCredentials(); Logger.getLogger("Auth").log(Level.INFO, "POST on password -- " + password); if (password == null) throw new BadCredentialsException("Password not found."); Logger.getLogger("Auth").log(Level.INFO, "Getting user from database"); UserSaltDetails user = userService.loadUserByUsername(username); Logger.getLogger("Auth").log(Level.INFO, "User get with username: " + user.getUsername()); Logger.getLogger("Auth").log(Level.INFO, "User get with password: " + user.getPassword()); String pw = user.getPassword(); Logger.getLogger("Auth").log(Level.INFO, "User get with salt : " + user.getUserSalt()); Logger.getLogger("Auth").log(Level.INFO, "User get with authorities : " + user.getAuthorities().toString()); boolean isAuthenticated = false; try {//w w w . j a v a 2 s . co m isAuthenticated = PBKDF2.authenticate(password, user.getPassword(), user.getUserSalt()); Logger.getLogger("Auth").log(Level.INFO, "Is true : " + isAuthenticated); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(PBKDF2AuthProvider.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(PBKDF2AuthProvider.class.getName()).log(Level.SEVERE, null, ex); } if (!isAuthenticated) throw new BadCredentialsException("Wrong password."); else Logger.getLogger("Auth").log(Level.INFO, "Authenticated"); return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); }
From source file:eu.supersede.fe.rest.LocaleRest.java
@RequestMapping(method = RequestMethod.PUT, value = "/current") public void setCurrentLocale(Authentication auth, @RequestParam(required = true) String lang, HttpServletRequest request) {/*from w w w . java 2s.c o m*/ if (lang.equals("any")) { lang = ""; } Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (user instanceof DatabaseUser) { DatabaseUser dbUser = (DatabaseUser) user; dbUser.setLocale(lang); // updating principal in session Authentication authentication = new UsernamePasswordAuthenticationToken(dbUser, dbUser.getPassword(), dbUser.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); request.getSession(false).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); User u = users.getOne(dbUser.getUserId()); u.setLocale(lang); users.save(u); } }
From source file:ltistarter.oauth.MyOAuthAuthenticationHandler.java
@Override public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication, OAuthAccessProviderToken authToken) { Collection<GrantedAuthority> authorities = new HashSet<>(authentication.getAuthorities()); // attempt to create a user Authority String username = request.getParameter("username"); if (StringUtils.isBlank(username)) { username = authentication.getName(); }//from ww w . j av a 2 s . c o m // NOTE: you should replace this block with your real rules for determining OAUTH ADMIN roles if (username.equals("admin")) { authorities.add(userGA); authorities.add(adminGA); } else { authorities.add(userGA); } Principal principal = new NamedOAuthPrincipal(username, authorities, authentication.getConsumerCredentials().getConsumerKey(), authentication.getConsumerCredentials().getSignature(), authentication.getConsumerCredentials().getSignatureMethod(), authentication.getConsumerCredentials().getSignatureBaseString(), authentication.getConsumerCredentials().getToken()); Authentication auth = new UsernamePasswordAuthenticationToken(principal, null, authorities); log.info("createAuthentication generated auth principal (" + principal + "): req=" + request); return auth; }