List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken setDetails
public void setDetails(Object details)
From source file:com.organization.projectname.config.AuthenticationTokenFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authToken = request.getHeader(this.tokenHeader); // authToken.startsWith("Bearer ") // String authToken = header.substring(7); String username = jwtTokenUtil.getUsernameFromToken(authToken); String ip = SecurityUtil.getClientIP(request); log.info("checking authentication for user " + username + " and IP " + ip); IPWhitelist iPWhitelist = iPWhitelistRepository.findByIpAddr(ip); System.out.println(iPWhitelist); if (iPWhitelist != null && username != null && SecurityContextHolder.getContext().getAuthentication() == null) { // It is not compelling necessary to load the use details from the database. You could also store the information // in the token and read it from it. It's up to you ;) UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); // For simple validation it is completely sufficient to just check the token integrity. You don't have to call // the database compellingly. Again it's up to you ;) if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); log.info("authenticated user " + username + ", setting security context"); SecurityContextHolder.getContext().setAuthentication(authentication); }/*www .java 2 s . c o m*/ } chain.doFilter(request, response); }
From source file:org.openwms.client.security.AuthenticationTokenProcessingFilter.java
/** * {@inheritDoc}/* w w w .j a v a2s . com*/ * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Expecting a http servlet request"); } HttpServletRequest httpRequest = (HttpServletRequest) request; String authToken = httpRequest.getHeader(AUTH_TOKEN); String userName = TokenUtils.getUserNameFromToken(authToken); if (userName != null) { // The returned UserDetails object has credentials encoded, we rely // on two AuthenticationProviders here to // come around this issue, one with PasswordEncoder and one without UserDetails userDetails = this.userService.loadUserByUsername(userName); if (TokenUtils.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword()); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext() .setAuthentication(this.authenticationManager.authenticate(authentication)); } } chain.doFilter(request, response); SecurityContextHolder.clearContext(); }
From source file:be.bittich.quote.security.AuthenticationTokenProcessingFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = this.getAsHttpRequest(request); String authToken = extractAuthTokenFromRequest(httpRequest); String username = tokenService.getUsernameFromToken(authToken); if (username != null) { UserDetails userDetails = this.userService.loadUserByUsername(username); if (tokenService.validateToken(authToken, request.getRemoteAddr(), userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest)); SecurityContextHolder.getContext().setAuthentication(authentication); }/*from www .j ava2 s.c om*/ } chain.doFilter(request, response); }
From source file:com.amediamanager.controller.UserController.java
@RequestMapping(value = "/register", method = RequestMethod.POST) public String register(@Valid NewUser newUser, BindingResult result, RedirectAttributes attr, ModelMap model) { try {//ww w .j a va 2 s . c o m if (result.hasErrors()) { model.addAttribute("templateName", "welcome"); return "base"; } userService.save(newUser); User user = userService.find(newUser.getEmail()); List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>(); grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); // Authenticate the user UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getEmail(), null, grantedAuths); // Save user in session auth.setDetails(user); SecurityContextHolder.getContext().setAuthentication(auth); } catch (UserExistsException e) { attr.addFlashAttribute("error", "That user already exists."); LOG.info("User already exists.", e); } return "redirect:/welcome"; }
From source file:org.osiam.auth.login.ldap.OsiamLdapAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) { Preconditions.checkArgument(authentication instanceof OsiamLdapAuthentication, "OsiamLdapAuthenticationProvider only supports OsiamLdapAuthentication."); final OsiamLdapAuthentication userToken = (OsiamLdapAuthentication) authentication; String username = userToken.getName(); String password = (String) authentication.getCredentials(); if (Strings.isNullOrEmpty(username)) { throw new BadCredentialsException("OsiamLdapAuthenticationProvider: Empty Username"); }// ww w .j a va2 s. c o m if (Strings.isNullOrEmpty(password)) { throw new BadCredentialsException("OsiamLdapAuthenticationProvider: Empty Password"); } User user = resourceServerConnector.getUserByUsername(username); checkIfInternalUserExists(user); DirContextOperations userData = doAuthentication(userToken); UserDetails ldapUser = osiamLdapUserContextMapper.mapUserFromContext(userData, authentication.getName(), loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials())); user = synchronizeLdapData(userData, user); User authUser = new User.Builder(username).setId(user.getId()).build(); List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (Role role : user.getRoles()) { grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue())); } UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authUser, null, grantedAuthorities); result.setDetails(authentication.getDetails()); return result; }
From source file:net.firejack.platform.web.security.spring.AuthenticationManager.java
private Authentication generateDefaultToken(IUserInfoProvider user, List<GrantedAuthority> authorities, HttpSession session) {//from w w w .ja va2 s.com UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), authorities); token.setDetails(user); sessionManager.addUserToSession(user, session); return token; }
From source file:com.gm.machine.web.RegisterAction.java
@Override public String save() throws Exception { try {//from ww w. ja v a 2 s . c o m HttpServletRequest request = Struts2Utils.getRequest(); String rcode = Struts2Utils.getParameter("rcode"); String scode = (String) Struts2Utils.getSession().getAttribute("scode"); if (StringUtils.isBlank(rcode)) { this.tip = "??!"; return input(); } else { if (!rcode.equalsIgnoreCase(scode)) { this.tip = "??!"; return input(); } } userManager.save(entity); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( entity.getLoginName(), entity.getPassword()); token.setDetails(new WebAuthenticationDetails(request)); Authentication authenticatedUser = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authenticatedUser); request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); entity.setLastLoginDate(new Date());// ? entity.setLoginTimes(entity.getLoginTimes() + 1);// userManager.save(entity); request.getSession().setAttribute("loginuser", entity); request.getSession().setAttribute("userid", entity.getId()); } catch (Exception e) { this.addActionMessage(Global.SAVE_LOSE); e.printStackTrace(); } return RELOAD; }
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);// www . j a v a2 s. c o m //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:org.apache.cxf.fediz.service.idp.service.security.GrantedAuthorityEntitlements.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try {// w w w.ja v a 2s.c om 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: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 2s.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); }