List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken setDetails
public void setDetails(Object details)
From source file:com.skywell.social.custom.OAuth2AuthenticationProcessingFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try {//from w ww . j av a 2s .com Authentication authentication = tokenExtractor.extract(request); if (authentication == null) { if (stateless && isAuthenticated()) { if (debug) { logger.debug("Clearing security context."); } SecurityContextHolder.clearContext(); } if (debug) { logger.debug("No token in request, will continue chain."); } } else { request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal()); if (authentication instanceof AbstractAuthenticationToken) { AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication; needsDetails.setDetails(authenticationDetailsSource.buildDetails(request)); } User user = userRepository.findByAccessToken(authentication.getName()); UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken( user.getProviderUserId(), user.getAccessToken(), user.getAuthorities()); authenticate.setDetails(authentication.getDetails()); SecurityContextHolder.getContext().setAuthentication(authenticate); } } catch (OAuth2Exception failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request failed: " + failed); } eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), new PreAuthenticatedAuthenticationToken("access-token", "N/A")); authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(failed.getMessage(), failed)); return; } chain.doFilter(request, response); }
From source file:org.glassmaker.spring.oauth.OAuth2AuthenticationProcessingFilter.java
private Authentication createAuthentication(HttpServletRequest request) throws BadCredentialsException { try {//from w ww . ja v a2 s . co m if (request.getParameter("code") != null) { AuthorizationCodeFlow flow = oAuth2Util.newAuthorizationCodeFlow(); TokenResponse tokenResponse = null; try { tokenResponse = oAuth2Util.newTokenRequest(flow, request.getParameter("code")).execute(); } catch (TokenResponseException e) { if (e.getDetails().getError().contains("invalid_grant")) { logger.warn("User disabled Glassware. Attempting to re-authenticate"); throw new BadCredentialsException("Start Login flow"); } } // 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."); Object mirrorCre = flow.createAndStoreCredential(tokenResponse, subject); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(subject, mirrorCre, (Collection<? extends GrantedAuthority>) new ArrayList<GrantedAuthority>()); auth.setDetails(tokenResponse.getAccessToken()); return this.getAuthenticationManager().authenticate(auth); } if (request.getParameter("error") != null) { logger.error("Something went wrong during auth: " + request.getParameter("error")); throw new AccessDeniedException(request.getParameter("error")); } else { Authentication auth = getAuthentication(request); if (auth == null) throw new BadCredentialsException("Start Login flow"); else return auth; } } catch (IOException e) { logger.error(e); throw new BadCredentialsException("CreateAuthentication Failed", e); } }
From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java
/** * Creates a successful {@link Authentication} object. * <p>/*w w w . j a va 2s . c o m*/ * Protected so subclasses can override. * </p> * <p> * Subclasses will usually store the original credentials the user supplied * (not salted or encoded passwords) in the returned * <code>Authentication</code> object. * </p> * * @param principal * that should be the principal in the returned object (defined * by the {@link #isForcePrincipalAsString()} method) * @param authentication * that was presented to the provider for validation * @param user * that was loaded by the implementation * * @return the successful authentication token */ private Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) { /* * Ensure we return the original credentials the user supplied, so * subsequent attempts are successful even with encoded passwords. Also * ensure we return the original getDetails(), so that future * authentication events after cache expiry contain the details */ UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities()); result.setDetails(authentication.getDetails()); return result; }
From source file:net.d53.syman.web.controller.PatientController.java
@RequestMapping(value = "/api/auth", method = RequestMethod.POST) @ResponseBody/*w w w . j a va2 s . co m*/ public String APIauthenticate(@RequestParam String username, @RequestParam String password, HttpServletRequest request, HttpServletResponse response) { String token = null; UsernamePasswordAuthenticationToken authenticationRequest = new UsernamePasswordAuthenticationToken( username, password); authenticationRequest.setDetails(APIAuthenticationToken.API_TOKEN_IDENTIFIER); try { APIAuthenticationToken res = (APIAuthenticationToken) authenticationManager .authenticate(authenticationRequest); LOGGER.info(ToStringBuilder.reflectionToString(res)); if (res != null) { token = res.getCredentials().toString(); LOGGER.info("Generated token " + token); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(res); this.securityContextRepository.saveContext(context, request, response); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } catch (AuthenticationException e) { LOGGER.info("Authentication error: " + e.getMessage()); SecurityContextHolder.clearContext(); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } return token; }
From source file:edu.zipcloud.cloudstreetmarket.core.authentication.CustomOAuth2RequestFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { final boolean debug = logger.isDebugEnabled(); String userIdentifier = request.getHeader(SPI_HEADER); if (userIdentifier == null) { chain.doFilter(request, response); return;/*from w w w . ja v a2 s .com*/ } try { SocialUser socialUser = getRegisteredUser(userIdentifier); if (socialUser == null) { response.setHeader(MUST_REGISTER_HEADER, request.getHeader(SPI_HEADER)); chain.doFilter(request, response); return; } if (authenticationIsRequired(socialUser.getUserId())) { User registeredUser = communityService.findOne(socialUser.getUserId()); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( registeredUser, registeredUser.getPassword(), registeredUser.getAuthorities()); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); if (debug) { logger.debug("Authentication success: " + authResult); } SecurityContextHolder.getContext().setAuthentication(authResult); rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request for failed: " + failed); } rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (ignoreFailure) { chain.doFilter(request, response); } return; } chain.doFilter(request, response); }
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;/* w ww.ja va2 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:it.smartcommunitylab.carpooling.controllers.UserAuthController.java
private BasicProfile processTokenData(HttpServletRequest request, HttpServletResponse response, TokenData tokenData) throws ProfileServiceException { BasicProfile basicProfile = profileService.getBasicProfile(tokenData.getAccess_token()); AccountProfile accountProfile = profileService.getAccountProfile(tokenData.getAccess_token()); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( basicProfile.getUserId(), basicProfile.getUserId(), CarPoolingUserDetails.CARPOOLER_AUTHORITIES); token.setDetails(new WebAuthenticationDetails(request)); Authentication authenticatedUser = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authenticatedUser); User user = User.fromUserProfile(basicProfile); User dbUser = userManager.findUser(user.getUserId()); if (dbUser != null) { user = dbUser;// w ww . j ava2 s. c o m } // if (!userManager.exist(user)) { user.setEmail(getEmail(accountProfile)); userManager.saveUser(user); // } /** add user to community after checking it against list of emails. **/ for (Community community : communityRepository.findAll()) { if (!community.getUsers().contains(user.getUserId()) && communityEmailSetup.getEmailAccounts(community.getId()).contains(user.getEmail())) { community.getUsers().add(user.getUserId()); communityRepository.save(community); } } rememberMeServices.loginSuccess(request, response, authenticatedUser); return basicProfile; }
From source file:com.singbon.service.CustomAuthenticationFilter.java
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); }/*www . jav a 2s.c o m*/ String username = obtainUsername(request); String password = obtainPassword(request); String companyName = null; try { companyName = new String(obtainCompanyName(request).getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (username == null) { username = ""; } if (password == null) { password = ""; } if (companyName == null) { companyName = ""; } try { username = DesUtil.encrypt(username.trim()); password = DesUtil.encrypt(password.trim()); } catch (Exception e) { e.printStackTrace(); } companyName = companyName.trim(); // ?? SysUser user = this.sysUserDAO.login(companyName, username, password); username = DesUtil.decrypt(username); password = DesUtil.decrypt(password); if (user == null) { username = 0 + USERNAME_LOGINID_SPLIT + username + USERNAME_LOGINID_SPLIT + password; } else { Company company = (Company) this.companyDAO.selectById(user.getCompanyId()); request.getSession().setAttribute("company", company); user.setLoginName(username); request.getSession().setAttribute("sysUser", user); username = user.getOperId() + USERNAME_LOGINID_SPLIT + username + USERNAME_LOGINID_SPLIT + password; if (user.getDeviceId() != null && user.getDeviceId() != 0) { Device device = (Device) this.deviceDAO.selectById(user.getDeviceId()); request.getSession().setAttribute("device", device); } } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); // Allow subclasses to set the "details" property authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); return this.getAuthenticationManager().authenticate(authRequest); }