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:security.MyAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); // 1. Use the username to load the data for the user, including authorities and password. User user = (User) userRepository.findOneByUsername(username); if (user == null) throw new BadCredentialsException("Bad Credentials"); String saltPassword = Hashing.sha512().hashString(password + user.getSalt(), Charsets.UTF_8).toString(); System.out.println("Salted pass: " + saltPassword); // 2. Check the passwords match. if (!user.getPassword().equals(saltPassword)) { throw new BadCredentialsException("Bad Credentials"); }// w ww . j a v a2 s . c o m // 3. Preferably clear the password in the user object before storing in authentication object //user.clearPassword(); // 4. Return an authenticated token, containing user data and authorities List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); Authentication token = new UsernamePasswordAuthenticationToken(user, saltPassword, authorities); return token; }
From source file:org.geoserver.geofence.gui.AuthenticationFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String header = httpRequest.getHeader("X-CUSTOM-USERID"); Authentication authentication = null; String username = null;//w w w. j a va 2 s. c o m String password = null; if (header != null) { String base64Token = header; String token = new String(Base64.decodeBase64(base64Token.getBytes())); // int delim = token.indexOf(":"); // // if (delim != -1) // { // username = token.substring(0, delim); // password = token.substring(delim + 1); // } httpRequest.getSession().setAttribute(GeofenceKeySessionValues.USER_LOGGED_TOKEN.getValue(), token); List<GrantedAuthority> authorities = Arrays .asList(new GrantedAuthority[] { new SimpleGrantedAuthority(ROOT_ROLE) }); UsernamePasswordAuthenticationToken upa = new UsernamePasswordAuthenticationToken( "1nt3rnAL-G30r3p0-admin", "1geosolutions2", authorities); authentication = upa; SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(httpRequest, response); } else { httpRequest.getSession().setAttribute(GeofenceKeySessionValues.USER_LOGGED_TOKEN.getValue(), ""); // httpResponse.addHeader("WWW-Authenticate", "Basic realm=\"geofence\""); // httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Please authenticate as administrator"); authentication = new AnonymousAuthenticationToken("geofence", "null", Arrays.asList(new GrantedAuthority[] { new SimpleGrantedAuthority(ANONYMOUS_ROLE) })); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(httpRequest, response); } }
From source file:com.hp.autonomy.frontend.configuration.authentication.IdolPreAuthenticatedAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final Object principal = authentication.getPrincipal(); if (principal == null) { throw new BadCredentialsException("Principal not supplied"); }/*from ww w . j a v a2 s . c o m*/ final String username = principal.toString().toLowerCase(); final UserRoles user = userService.getUser(username, true); final Collection<SimpleGrantedAuthority> grantedAuthorities = preAuthenticatedRoles.stream() .map(SimpleGrantedAuthority::new).collect(Collectors.toSet()); final CommunityPrincipal communityPrincipal = new CommunityPrincipal(user.getUid(), username, user.getSecurityInfo(), Collections.emptySet()); final Collection<? extends GrantedAuthority> authorities = authoritiesMapper .mapAuthorities(grantedAuthorities); return new UsernamePasswordAuthenticationToken(communityPrincipal, null, authorities); }
From source file:org.cloudfoundry.identity.uaa.login.ChainedAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication == null) { return authentication; }//from w w w . j a va 2s .c o m UsernamePasswordAuthenticationToken output = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { output = (UsernamePasswordAuthenticationToken) authentication; } else { output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authentication.getAuthorities()); output.setAuthenticated(authentication.isAuthenticated()); output.setDetails(authentication.getDetails()); } boolean authenticated = false; Authentication auth = null; AuthenticationException lastException = null; for (int i = 0; i < delegates.length && (!authenticated); i++) { try { if (logger.isDebugEnabled()) { logger.debug( "Attempting chained authentication of " + output + " with manager:" + delegates[i]); } auth = delegates[i].authenticate(output); authenticated = auth.isAuthenticated(); } catch (AuthenticationException x) { if (logger.isDebugEnabled()) { logger.debug("Chained authentication exception:", x); } lastException = x; } if (logger.isDebugEnabled()) { logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i] + "; Authenticated:" + authenticated); } } if (authenticated) { return auth; } else if (lastException != null) { //we had at least one authentication exception, throw it throw lastException; } else { //not authenticated, but return the last of the result return auth; } }
From source file:com.exp.tracker.services.impl.JpaSettlementServiceTests.java
@Before public void setup() { userDetailService = ctx.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); // Add 1st user UserBean ub1 = new UserBean(); ub1.setEmailId("a@b.com"); ub1.setEnabled(true);/*from w ww.j av a 2 s . c o m*/ ub1.setFirstName("Test1"); ub1.setLastName("User1"); ub1.setMiddleInit("1"); ub1.setPassword("password"); ub1.setUsername("testuser3"); UserBean userBean1 = userService.addUser(ub1, rCtx); Assert.assertNotNull("Failed to create user3. Why Why", userBean1); // // Add 1st 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("testuser4"); UserBean userBean2 = userService.addUser(ub2, rCtx); Assert.assertNotNull("Failed to create user4", userBean2); // ExpenseDetail ed = new ExpenseDetail(); ed.setAmount(20.0F); ed.setCategory("Somecategory"); ed.setCreatedBy("Admin"); ed.setDate(new Date()); ed.setDescription("Some Expense"); ed.setPaidBy("testuser3"); ed.setSettlementId(null); // now set shares UserShare us1 = new UserShare("testuser3", 10.0F, 0.0F, true); UserShare us2 = new UserShare("testuser4", 10.0F, 0.0F, true); ed.getUserShares().add(us1); ed.getUserShares().add(us2); Assert.assertNotNull("Expense detail is null", ed); int result = expenseService.saveExpense(ed); Assert.assertTrue("Failed to save expense.", result == 0); }
From source file:domain.user.social.SocialSignInAdapter.java
@Override public String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) { //Get user with the social ID: localUserId User user = userDao.findById(Long.parseLong(localUserId)); if (user != null && user.getStatus() == 1) { List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); auths.add(new SimpleGrantedAuthority("ROLE_USER")); SecureUser secureUser = new SecureUser(user, auths); Authentication authentication = new UsernamePasswordAuthenticationToken(secureUser, secureUser.getPassword(), secureUser.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); // Return page when login process successfully return SocialConfig.SOCIAL_CONNECT_SUCCESS_URL; } else {//w w w .j a v a2s. com // Return homepage return null; } }
From source file:org.openvpms.component.business.service.security.HibernateSecurityServiceTestCase.java
/** * Create a secure context for authorization testing. * * @param name the user name/* w ww . j a v a 2 s.c o m*/ * @param password the password * @param authorities the authorities of the person */ @Override protected void createSecurityContext(String name, String password, String... authorities) { User user = createUser(name, password); SecurityRole role = createSecurityRole("role1"); for (String authority : authorities) { // bit of a hack. The authority should be created via the archetype // service, but there is no facility to populate it from an // authority string. ArchetypeAwareGrantedAuthority auth = new ArchetypeAwareGrantedAuthority(authority); auth.setArchetypeIdAsString("security.archetypeAuthority.1.0"); dao.save(auth); role.addAuthority(auth); } user.addRole(role); dao.save(role); dao.save(user); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword(), user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(token); }
From source file:com.ar.dev.tierra.api.config.security.CustomAuthenticationProvider.java
@Override public Authentication authenticate(Authentication auth) throws AuthenticationException { String username = String.valueOf(auth.getName()); String password = String.valueOf(auth.getCredentials().toString()); Usuarios us = null;/* w ww . j av a 2 s. c om*/ boolean success = false; try { us = user.findUsuarioByUsername(username); success = passwordEncoder.matches(password, us.getPassword()); } catch (Exception ex) { } if (success == true) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); String authority; switch (us.getRoles().getNombreRol()) { case "ADMINISTRADOR": authority = "ROLE_ADMIN"; break; case "VENDEDOR": authority = "ROLE_VENDEDOR"; break; default: authority = "ROLE_NONE"; break; } GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority); grantedAuths.add(grantedAuthority); final UserDetails principal = new User(username, password, grantedAuths); final Authentication authentication = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths); us = null; return authentication; } else { throw new BadCredentialsException("Bad Credentials"); } }
From source file:com.boxedfolder.carrot.config.security.filter.XAuthTokenFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { try {//from ww w . j ava 2 s . c o m HttpServletRequest httpServletRequest = (HttpServletRequest) request; String authToken = httpServletRequest.getHeader("x-auth-token"); if (StringUtils.hasText(authToken)) { String username = tokenUtils.getUserNameFromToken(authToken); UserDetails details = detailsService.loadUserByUsername(username); if (tokenUtils.validateToken(authToken, details)) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(details, details.getPassword(), details.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(token); } } filterChain.doFilter(request, response); } catch (Exception exception) { throw new RuntimeException(exception); } }
From source file:org.ligoj.app.http.security.DigestAuthenticationFilter.java
@Override public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) { final String token = request.getParameter("token"); if (token != null) { // Token is the last part of URL // First get the cookie final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig( RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build()); // Do the POST try (CloseableHttpClient httpClient = clientBuilder.build()) { final HttpPost httpPost = new HttpPost(getSsoPostUrl()); httpPost.setEntity(new StringEntity(token, StandardCharsets.UTF_8.name())); httpPost.setHeader("Content-Type", "application/json"); final HttpResponse httpResponse = httpClient.execute(httpPost); if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) { return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken( EntityUtils.toString(httpResponse.getEntity()), "N/A", new ArrayList<>())); }/*from www.ja v a2 s . c o m*/ } catch (final IOException e) { log.warn("Local SSO server is not available", e); } } throw new BadCredentialsException("Invalid user or password"); }