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:net.maritimecloud.identityregistry.security.MCAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); logger.debug("In authenticate"); // The login name is the org shortname // Organization org = this.organizationService.getOrganizationByShortName(name); // if an org was found, test the password // if (org != null && (new BCryptPasswordEncoder().matches(password, org.getPasswordHash()))) { if (!password.isEmpty()) { List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN")); grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); Authentication auth = new UsernamePasswordAuthenticationToken(name, authentication.getCredentials(), grantedAuths);//from w w w . j a va 2 s .c om logger.debug("Got authenticated: " + auth.isAuthenticated()); return auth; } else { logger.debug("Didn't get authenticated"); throw new BadCredentialsException("Bad Credentials"); } }
From source file:com.mastercard.test.spring.security.WithUserDetailsSecurityContextFactory.java
public SecurityContext createSecurityContext(WithUserDetails withUser) { String beanName = withUser.userDetailsServiceBeanName(); UserDetailsService userDetailsService = StringUtils.hasLength(beanName) ? this.beans.getBean(beanName, UserDetailsService.class) : this.beans.getBean(UserDetailsService.class); String username = withUser.value(); Assert.hasLength(username, "value() must be non empty String"); UserDetails principal = userDetailsService.loadUserByUsername(username); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }
From source file:com.exp.tracker.services.impl.ReportControllerTests.java
@Before public void setup() { userDetailService = wac.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); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); ////from w ww .j a v a 2s . c o m // Add 1st user UserBean ub1 = new UserBean(); ub1.setEmailId("a@b.com"); ub1.setEnabled(true); ub1.setFirstName("Test1"); ub1.setLastName("User1"); ub1.setMiddleInit("1"); ub1.setPassword("password"); ub1.setUsername("testuserX"); UserBean userBean1 = userService.addUser(ub1, rCtx); Assert.assertNotNull("Failed to create userX. 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("testuserY"); UserBean userBean2 = userService.addUser(ub2, rCtx); Assert.assertNotNull("Failed to create userY", 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("testuserX"); ed.setSettlementId(null); // now set shares UserShare us1 = new UserShare("testuserX", 10.0F, 0.0F, true); UserShare us2 = new UserShare("testuserY", 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:sample.contact.service.impl.UserServiceImpl.java
/** * Efetua a autenticao de um usurio j existente, buscando-o atravs do <code>loadUserByUsername</code>. * * @param username Username a ser autenticado. *//* w ww .j av a2s . c om*/ @Override public void setAuthentication(String username) { UserDetails user = jdbcUserDetailsManager.loadUserByUsername(username); Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }
From source file:org.meruvian.yama.service.DefaultSessionCredential.java
@Override public void registerAuthentication(String userId) { org.meruvian.yama.repository.user.User user = userService.getUserById(userId); UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername()); Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth); }
From source file:com.company.project.web.controller.service.CustomAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); // CustomUserDetailsService will take care of password comparison // return null if username is not existing or password comparison fails UserDetails userDetails = customUserDetailsService.loadUserByUsername(name); if (userDetails == null) { throw new BadCredentialsException("Username not found or password incorrect."); }/*from w w w .java 2s . c om*/ if (userDetails != null) { // 3. Preferably clear the password in the user object before storing in authentication object //return new UsernamePasswordAuthenticationToken(name, null, userDetails.getAuthorities()); // OR return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); // use authentication.getPrincipal() to get the "userDetails" object } return null; }
From source file:com.ushahidi.swiftriver.core.api.auth.crowdmapid.CrowdmapIDAuthenticationProvider.java
@Transactional(readOnly = true) @Override/*from ww w .j a v a2 s . c om*/ public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); User user = userDao.findByUsernameOrEmail(username); if (user == null || !crowdmapIDClient.signIn(username, password)) { throw new BadCredentialsException(String.format("Invalid username/password pair for %s", username)); } Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); for (Role role : user.getRoles()) { authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName().toUpperCase())); } UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(username, authentication.getCredentials(), authorities); result.setDetails(authentication.getDetails()); return result; }
From source file:md.ibanc.rm.sessions.CustomAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); LoginFormValidator loginFormValidator = new LoginFormValidator(); if (!loginFormValidator.isLoginValid(username)) { throw new BadCredentialsException("Numele de utilizator contine simboluri interzise"); }//from w w w .j a v a 2s . c o m if (!loginFormValidator.isValidPassword(password)) { throw new BadCredentialsException("Parola contine simboluri interzise"); } Users users = usersService.findUserByEmail(username); if (users == null) { throw new UsernameNotFoundException("Asa utilizator nu exista in baza de date"); } String hashPassword = UtilHashMD5.createMD5Hash(FormatPassword.CreatePassword(users.getId(), password)); if (!hashPassword.equals(users.getPassword())) { throw new BadCredentialsException("Parola este gresita"); } if (!users.getActive()) { throw new AccountExpiredException("Nu aveti drept sa accesati acest serviciu"); } Collection<? extends GrantedAuthority> authoritiesRoles = getAuthorities(users); return new UsernamePasswordAuthenticationToken(username, hashPassword, authoritiesRoles); }
From source file:nz.net.orcon.kanban.security.SecurityToolImpl.java
@Override public void iAmSystem() throws Exception { SecurityContext context = SecurityContextHolder.getContext(); Collection<? extends GrantedAuthority> authorities = this.getRoles(SYSTEM); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(SYSTEM, "", authorities);// ww w . j av a 2 s . c o m context.setAuthentication(authentication); }
From source file:de.iew.web.utils.WebAutoLogin.java
public void autoLogin(UserDetails userDetails, HttpServletRequest request) { SecurityContext securityContext = SecurityContextHolder.getContext(); HttpSession session = request.getSession(true); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); try {/*w w w . ja v a2 s . c o m*/ // @TODO Das funktioniert so nicht direkt. Habe es ohne Passwort Angabe nicht hinbekommen. UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), "test", userDetails.getAuthorities()); token.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = this.authenticationManager.authenticate(token); securityContext.setAuthentication(authentication); } catch (Exception e) { if (log.isInfoEnabled()) { log.info("Fehler whrend des Einlog-Versuchs.", e); } securityContext.setAuthentication(null); } }