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.blackducksoftware.tools.appedit.web.auth.AppEditAuthenticationProvider.java
private UsernamePasswordAuthenticationToken generateAuthenticationToken(String username, String password) { AuthenticationResult authResult = authenticateUser(username, password); // Grant access List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority(authResult.getRole().name())); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, password, authorities);/*w w w. j a v a2 s. co m*/ auth.setDetails(authResult); return auth; }
From source file:io.gravitee.management.security.config.basic.filter.JWTAuthenticationFilter.java
@Override @SuppressWarnings(value = "unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; final Optional<Cookie> optionalStringToken; if (req.getCookies() == null) { optionalStringToken = Optional.empty(); } else {//from www. java 2s.co m optionalStringToken = Arrays.stream(req.getCookies()) .filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).findAny(); } if (optionalStringToken.isPresent()) { String stringToken = optionalStringToken.get().getValue(); final String authorizationSchema = "Bearer"; if (stringToken.contains(authorizationSchema)) { stringToken = stringToken.substring(authorizationSchema.length()).trim(); try { final Map<String, Object> verify = jwtVerifier.verify(stringToken); final List<SimpleGrantedAuthority> authorities = ((List<Map>) verify.get(JWTClaims.PERMISSIONS)) .stream().map(map -> new SimpleGrantedAuthority(map.get("authority").toString())) .collect(Collectors.toList()); final UserDetails userDetails = new UserDetails(getStringValue(verify.get(JWTClaims.SUBJECT)), "", authorities, getStringValue(verify.get(JWTClaims.EMAIL)), getStringValue(verify.get(JWTClaims.FIRSTNAME)), getStringValue(verify.get(JWTClaims.LASTNAME))); SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities())); } catch (Exception e) { LOGGER.error("Invalid token", e); final Cookie bearerCookie = jwtCookieGenerator.generate(null); res.addCookie(bearerCookie); res.sendError(HttpStatusCode.UNAUTHORIZED_401); } } else { LOGGER.info("Authorization schema not found"); } } else { LOGGER.info("Authorization cookie not found"); } chain.doFilter(request, response); }
From source file:com.gs.config.MyAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UserDetails userDetails = this.customJDBCDaoImpl.loadUserByUsername(authentication.getName()); //Obtengo los intentos de inicio de sesin hechos por un usuario int intentos = usuarioConIntentoFallido.getIntentosUsuario(authentication.getName()); if (intentos < intentosPosibles && !listUsersLockoutIntentFail.findUserBlockout(authentication.getName())) { if (userDetails.isEnabled()) { if (userDetails != null && shaPasswordEncoder.isPasswordValid(userDetails.getPassword(), authentication.getCredentials().toString(), null)) { usuarioConIntentoFallido.removeUsuario(userDetails.getUsername()); //Verifico si el usuario ya tiene una sesin abierta, si es as la cierro y le creo su nueva instancia verifUserInSession(userDetails.getUsername()); return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); }// w w w .j a v a 2 s. c o m throw new BadCredentialsException("Bad credentials"); } else { throw new DisabledException("User disabled"); } } else { throw new IntentLimitExceeded("limite de intentos excedidos"); } }
From source file:org.syncope.core.security.SyncopeAuthenticationProvider.java
@Override @Transactional(noRollbackFor = { BadCredentialsException.class }) public Authentication authenticate(final Authentication authentication) throws AuthenticationException { boolean authenticated; SyncopeUser passwordUser = new SyncopeUser(); SyncopeUser user = null;//from www . j av a2 s . co m if (adminUser.equals(authentication.getPrincipal())) { passwordUser.setPassword(authentication.getCredentials().toString(), CipherAlgorithm.MD5, 0); authenticated = adminMD5Password.equalsIgnoreCase(passwordUser.getPassword()); } else { String username; try { username = authentication.getPrincipal().toString(); } catch (NumberFormatException e) { throw new UsernameNotFoundException("Invalid username: " + authentication.getName(), e); } user = userDAO.find(username); if (user == null) { throw new UsernameNotFoundException("Could not find user " + username); } passwordUser.setPassword(authentication.getCredentials().toString(), user.getCipherAlgoritm(), 0); authenticated = user.getPassword().equalsIgnoreCase(passwordUser.getPassword()); } Authentication result; if ((user == null || !user.getSuspended()) && authenticated) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), null, userDetailsService .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities()); token.setDetails(authentication.getDetails()); result = token; LOG.debug("User {} authenticated with roles {}", authentication.getPrincipal(), token.getAuthorities()); if (user != null) { user.setLastLoginDate(new Date()); user.setFailedLogins(0); userDAO.save(user); } } else { result = authentication; if (user != null && !user.getSuspended()) { user.setFailedLogins(user.getFailedLogins() + 1); userDAO.save(user); } LOG.debug("User {} not authenticated", authentication.getPrincipal()); throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated"); } return result; }
From source file:com.github.jens_meiss.blog.server.service.json.user.UserController.java
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final String userName = authentication.getName(); final UserDetailsDTO userDetailsDTO = userService.findByUserName(userName); if (userDetailsDTO == null) { logger.error("username not found"); return null; }//from w w w . j av a2s . c o m final String crendentials = authentication.getCredentials().toString(); if (crendentials.equals(userDetailsDTO.getPassword()) == false) { logger.error("password mismatch"); return null; } logger.debug("user successfully authenticated"); return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), new ArrayList<GrantedAuthority>()); }
From source file:cz.muni.fi.editor.services.commons.impl.SecurityServiceImpl.java
@Override @Transactional(readOnly = true)// ww w. j a va 2 s . com public void refresh(Long userID) { if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) { Authentication current = SecurityContextHolder.getContext().getAuthentication(); UserDTO principal = (UserDTO) current.getPrincipal(); if (principal.getId().equals(userID)) { User dao = new User(); dao.setId(principal.getId()); List<OrganizationDTO> member = organizationDAO.getOrganizationForUser(dao, true).stream().map(o -> { OrganizationDTO dto = new OrganizationDTO(); dto.setId(o.getId()); return dto; }).collect(Collectors.toList()); List<OrganizationDTO> owner = organizationDAO.ownedBy(dao).stream().map(o -> { OrganizationDTO dto = new OrganizationDTO(); dto.setId(o.getId()); return dto; }).collect(Collectors.toList()); principal.init(owner, member); SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken( principal, current.getCredentials(), principal.getAuthorities())); } } }
From source file:com.emergya.spring.security.oauth.UserServiceAuthenticationConverter.java
/** * Converts the user info provided by the OAuth endpoint into a Spring Security Authentication object. * * @param map A map containing the authentication info provided by the OAuth service. * @return An Authentication object instance containg the data extracted from the de details service. *///from w w w.j av a2 s . c o m @Override public final Authentication extractAuthentication(final Map<String, ?> map) { if (detailsService == null) { throw new IllegalStateException("userDetailsService must have been set before."); } UserDetails userDetails = null; if (map.containsKey(EMAIL)) { userDetails = detailsService.loadUserByUsername((String) map.get(EMAIL)); } else if (map.containsKey(USERNAME)) { userDetails = detailsService.loadUserByUsername((String) map.get(USERNAME)); } if (userDetails != null) { return new UsernamePasswordAuthenticationToken(userDetails, "N/A", getAuthorities(map, userDetails.getAuthorities())); } return null; }
From source file:fr.esiea.esieaddress.service.login.facebook.FacebookAuthenticationService.java
@Override public void handleFacebookRedirect(String code) throws DaoException, ServiceException { String accessToken = getAccessToken(code); FacebookClient facebookClient = new DefaultFacebookClient(accessToken); User user = facebookClient.fetchObject("me", User.class); user.setAccountFacebook(true);//from w w w .j ava 2s. c om //Update or create the contact User one = userDao.getOneByEmail(user.getMail()); if (null == one) { userDao.insert(user); //insert a new user } else { user.setId(one.getId()); if (one.equals(user)) userDao.save(user); //Update the user } //Authorities Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); for (String authority : user.getProfile().getRoleList()) { authorities.add(new SimpleGrantedAuthority(authority)); } //Make the autentication UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getMail(), accessToken, authorities); token.setDetails(user.getId()); SecurityContextHolder.getContext().setAuthentication(token); }
From source file:de.uni_koeln.spinfo.maalr.login.SocialSignInAdapter.java
private UserDetails signIn(MaalrUserInfo user) { UserDetails details = getUserDetails(user); UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(details, details.getPassword(), details.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authToken); logger.info("User '{}' signed in...", user); return details; }
From source file:org.opentides.util.SecurityUtilTest.java
@Test public void testCurrentUserHasPermission() { 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);/*from w ww. ja v a 2 s .c o m*/ SecurityContextHolder.getContext().setAuthentication(authentication); assertTrue(SecurityUtil.currentUserHasPermission("ROLE1")); assertFalse(SecurityUtil.currentUserHasPermission("ROLE3")); }