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:io.github.autsia.crowly.security.CrowlyAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { try {/*ww w .j a v a 2 s . co m*/ CrowlyUser dbUser = userRepository.findByEmail(authentication.getName()); if (bCryptPasswordEncoder.matches(authentication.getCredentials().toString(), dbUser.getPassword())) { return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), getAuthorities(dbUser)); } } catch (Exception e) { logger.error(e.getMessage()); } throw new BadCredentialsException(authentication.getName()); }
From source file:com.brienwheeler.web.spring.security.SecurityUtils.java
public static void setLoggedInUser(User user, Collection<? extends GrantedAuthority> authorities) { ValidationUtils.assertNotNull(user, "user cannot be null"); ValidationUtils.assertTrue(user.getId() != 0, "user cannot be unpersisted"); ValidationUtils.assertNotNull(authorities, "authorities cannot be null"); SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext == null) throw new IllegalStateException("can't set logged in user if securityContext is null"); if ((securityContext.getAuthentication() != null) && (!(securityContext.getAuthentication() instanceof AnonymousAuthenticationToken)) && (securityContext.getAuthentication().getPrincipal() != null)) { Object principal = securityContext.getAuthentication().getPrincipal(); if (!(principal instanceof UserDetails) || (((UserDetails) principal).getUserId() != user.getId())) { throw new IllegalStateException("cannot overwrite currently logged in user"); }//w w w .jav a 2 s . c o m // fall through to set new Authentication object in case authorities have changed } securityContext.setAuthentication(new UsernamePasswordAuthenticationToken( new UserDetails(user, authorities), user.getHashedPassword(), authorities)); }
From source file:uk.org.rbc1b.roms.scheduled.DailyVolunteerEmailScheduledService.java
/** * Scheduled execution method for formatting the email and saving * into the database which will then be sent using {@code EmailScheduledService}. * This will be executed every day at noon. *///from w w w. j a va2s. c om //@Scheduled(cron = "0 0/5 * * * ?") - for testing @Scheduled(cron = "0 0 12 * * ?") public void queueVolunteerInformationEmails() { UserDetails system = userDetailsService.loadUserByUsername("System"); Authentication authentication = new UsernamePasswordAuthenticationToken(system, system.getUsername(), system.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); VolunteerSearchCriteria searchCriteria = new VolunteerSearchCriteria(); searchCriteria.setMaxResults(findMaxVolunteersForEmail()); List<Volunteer> volunteersForEmail = volunteerDao.findVolunteersWhoNeedBiannualEmail(searchCriteria); for (Volunteer volunteer : volunteersForEmail) { try { Email email = volunteerContactDetailsEmailGenerator.generateEmailForVolunteers(volunteer); LOGGER.info("Volunteer: " + volunteer.getPersonId()); if (email != null) { emailDao.save(email); } // update the update contact details email last sent date to today for volunteer final DateTime dt = new DateTime(); volunteer.setUpdateContactDetailsEmailLastSent(DataConverterUtil.toSqlDate(dt)); volunteerDao.updateVolunteer(volunteer); } catch (IOException | TemplateException ex) { LOGGER.error("Failed to send the volunteer contact details email: ", ex); } } }
From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenDeserializer.java
/** * This method construct {@link UsernamePasswordAuthenticationToken} object from serialized json. *///from w ww . j a v a2s .c o m @Override public UsernamePasswordAuthenticationToken deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException { UsernamePasswordAuthenticationToken token; ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec(); JsonNode jsonNode = mapper.readTree(jsonParser); Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean(); JsonNode principalNode = readJsonNode(jsonNode, "principal"); Object principal; if (principalNode.isObject()) { Class principalClass = LinkedHashMap.class; if (principalNode.hasNonNull("@class")) { try { principalClass = Class.forName(principalNode.get("@class").asText()); } catch (ClassNotFoundException e) { throw new RuntimeException( "Could not load principal class [" + principalNode.get("@class").asText() + "]", e); } } principal = mapper.readValue(principalNode.toString(), principalClass); } else { principal = principalNode.asText(); } Object credentials = readJsonNode(jsonNode, "credentials").asText(); List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").toString(), new TypeReference<List<GrantedAuthority>>() { }); if (authenticated) { token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities); } else { token = new UsernamePasswordAuthenticationToken(principal, credentials); } token.setDetails(readJsonNode(jsonNode, "details")); return token; }
From source file:de.iew.services.impl.TreeSketchPadServiceImplIntegrationTest.java
@Before public void setup() { SecurityContext securityContext = SecurityContextHolder.getContext(); List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_SKETCHPAD_USER")); Account account = new Account(); account.setUsername("SketchPad User 1"); account.setLocked(false);/* w ww . ja v a 2s . c om*/ account.setEnabled(true); this.user1 = new UsernamePasswordAuthenticationToken(account, "anonymous", grantedAuthorities); securityContext.setAuthentication(this.user1); account = new Account(); account.setUsername("SketchPad User 2"); account.setLocked(false); account.setEnabled(true); this.user2 = new UsernamePasswordAuthenticationToken(account, "anonymous", grantedAuthorities); }
From source file:org.apache.cxf.fediz.service.idp.STSUPAuthenticationProvider.java
private Authentication handleUsernamePassword(UsernamePasswordAuthenticationToken usernamePasswordToken, IdpSTSClient sts) {/*from w w w .ja va 2s. c o m*/ sts.getProperties().put(SecurityConstants.USERNAME, usernamePasswordToken.getName()); sts.getProperties().put(SecurityConstants.PASSWORD, (String) usernamePasswordToken.getCredentials()); try { // Line below may be uncommented for debugging // setTimeout(sts.getClient(), 3600000L); SecurityToken token = sts.requestSecurityToken(this.appliesTo); List<GrantedAuthority> authorities = createAuthorities(token); UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken( usernamePasswordToken.getName(), usernamePasswordToken.getCredentials(), authorities); STSUserDetails details = new STSUserDetails(usernamePasswordToken.getName(), (String) usernamePasswordToken.getCredentials(), authorities, token); upat.setDetails(details); LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), usernamePasswordToken.getName()); return upat; } catch (Exception ex) { LOG.info("Failed to authenticate user '" + usernamePasswordToken.getName() + "'", ex); return null; } }
From source file:org.sharetask.security.StoreUserInformationAuthenticationSuccessHandler.java
@Override public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, Authentication authentication) throws IOException, ServletException { if (authentication instanceof ClientAuthenticationToken) { log.debug("Token is pac4j token."); String language = Language.EN.getCode(); UsernamePasswordAuthenticationToken authentToken; final CommonProfile profile = (CommonProfile) ((ClientAuthenticationToken) authentication) .getUserProfile();//www . j av a 2 s . c o m if (userRepository.findByUsername(profile.getEmail()) == null) { log.debug("User with name: {} doesne exist's. Will be created", profile.getEmail()); final UserInformation userInformation = new UserInformation(profile.getEmail()); userInformation.setName(profile.getFirstName()); userInformation.setSurName(profile.getFamilyName()); userInformation.setLanguage(language); final ArrayList<Role> list = new ArrayList<Role>(); list.add(Role.ROLE_USER); userInformation.setRoles(list); userRepository.save(userInformation); final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority(Role.ROLE_USER.name())); authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities); } else { final UserInformation user = userRepository.read(profile.getEmail()); language = user.getLanguage(); final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities); } // language cookie final Cookie locale = new Cookie(RequestUltil.LOCALE, language); locale.setMaxAge(-1); locale.setPath("/"); response.addCookie(locale); SecurityContextHolder.getContext().setAuthentication(authentToken); } super.onAuthenticationSuccess(request, response, authentication); }
From source file:ch.ge.ve.protopoc.jwt.JwtAuthenticationTokenFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String authToken = httpRequest.getHeader(this.tokenHeader); String username = jwtTokenUtil.getUsernameFromToken(authToken); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest)); SecurityContextHolder.getContext().setAuthentication(authentication); }/*w w w . j a va 2s. c o m*/ } chain.doFilter(request, response); }
From source file:nc.noumea.mairie.appock.core.security.AppockAuthenticationProvider.java
/** * Override la mthode authenticate//from w w w . j a va2s. c om * * @param authentication Authentication * @throws AuthenticationException Exception d'authentification */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication authenticationResult = null; if (provider != null) try { authenticationResult = provider.authenticate(authentication); } catch (BadCredentialsException e) { LOGGER.error("Error lors de l'authentification", e); throw new BadCredentialsException(messageProvider); } String username = authentication.getName(); String password = (String) authentication.getCredentials(); List<GrantedAuthority> roles = new ArrayList<>(); try { AppUser appUser = appUserService.findByLogin(username); if (appUser == null || !appUser.isActif()) { throw new BadCredentialsException(messageAppock); } } catch (NoResultException e) { throw new BadCredentialsException(messageAppock); } return (provider == null) ? new UsernamePasswordAuthenticationToken(username, password, roles) : authenticationResult; }
From source file:org.glassmaker.spring.oauth.OAuth2AuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getParameter("code") != null) { AuthorizationCodeFlow flow = oAuth2Util.newAuthorizationCodeFlow(); TokenResponse tokenResponse = oAuth2Util.newTokenRequest(flow, request.getParameter("code")).execute(); // Extract the Google User ID from the ID token in the auth // response //String userId = ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload().getUserId(); String subject = ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload().getSubject(); //String email = (String) ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload().get("email"); logger.info("Code exchange worked. User " + subject + " logged in."); flow.createAndStoreCredential(tokenResponse, subject); Authentication auth = new UsernamePasswordAuthenticationToken(subject, tokenResponse.getAccessToken(), (Collection<? extends GrantedAuthority>) new ArrayList<GrantedAuthority>()); authManager.authenticate(auth);//from ww w. j a v a2 s. com SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(auth)); ((HttpServletRequest) request).getSession().setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); if (auth != null) { onAuthenticationSuccess((HttpServletRequest) request, (HttpServletResponse) response, auth); } } chain.doFilter(request, response); }