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.mycompany.login.filter.AutenticacaoFilter.java
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { String login = request.getParameter("j_login"); String senha = request.getParameter("j_senha"); try {//from ww w. jav a 2 s. c o m Usuario usuario = buscarUsuario(login, senha); if (usuario != null) { Collection<GrantedAuthority> regras = new ArrayList<GrantedAuthority>(); regras.add(new SimpleGrantedAuthority(usuario.getPermissao())); request.getSession().setAttribute("usuarioLogado", usuario); mensagem = "Bem vindo: " + usuario.getNomeusuario(); return new UsernamePasswordAuthenticationToken(usuario.getLogin(), usuario.getSenha(), regras); } else { mensagem = "Dados Incorretos"; throw new BadCredentialsException(mensagem); } } catch (Exception e) { throw new BadCredentialsException(e.getMessage()); } }
From source file:com.spfsolutions.ioms.auth.UserAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { try {/* ww w . ja va2 s.c o m*/ UserEntity userEntity = userDao.queryForFirst( userDao.queryBuilder().where().eq("Username", authentication.getName()).prepare()); String inputHash = MD5.encrypt(authentication.getCredentials().toString()); if (userEntity == null || !userEntity.getPassword().equals(inputHash)) { throw new BadCredentialsException("Username or password incorrect."); } else if (!userEntity.isEnabled()) { throw new DisabledException("The username is disabled. Please contact your System Administrator."); } userEntity.setLastSuccessfulLogon(new DateTime(DateTimeZone.UTC).toDate()); userDao.createOrUpdate(userEntity); Collection<SimpleGrantedAuthority> authorities = buildRolesFromUser(userEntity); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( authentication.getName(), authentication.getCredentials(), authorities); return token; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { userDao.getConnectionSource().closeQuietly(); } return null; }
From source file:example.springdata.mongodb.security.PersonRepositoryIntegrationTest.java
@Test public void adminCallingShouldReturnAllUsers() throws Exception { UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(admin, "x", Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN"))); SecurityContextHolder.getContext().setAuthentication(auth); List<Person> persons = repository.findAllForCurrentUserById(); assertThat(persons, hasSize(4));/*from ww w .j av a 2s . com*/ assertThat(persons, containsInAnyOrder(admin, dave, carter, oliver)); }
From source file:com.seyren.core.security.AuthenticationTokenFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!seyrenConfig.isSecurityEnabled()) { SecurityContextHolder.getContext().setAuthentication(new SecurityDisabledAuthentication()); } else {//from w w w . ja v a 2 s . c o m HttpServletRequest httpRequest = this.getAsHttpRequest(request); String authToken = this.extractAuthTokenFromRequest(httpRequest); String userName = Token.getUserNameFromToken(authToken); if (userName != null) { UserDetails userDetails = this.userService.loadUserByUsername(userName); if (Token.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest)); SecurityContextHolder.getContext().setAuthentication(authentication); } } } chain.doFilter(request, response); }
From source file:com.exp.tracker.services.impl.JpaUserServiceTests.java
@Test public void userServiceTests() { 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 a user UserBean ub1 = new UserBean(); ub1.setEmailId("a@b.com"); ub1.setEnabled(true);/*from w w w. ja v a 2 s .co m*/ ub1.setFirstName("Test1"); ub1.setLastName("User1"); ub1.setMiddleInit("1"); ub1.setPassword("password"); ub1.setUsername("ustest1"); // add auth // ub1.addAuth("ROLE_SITE_ADMIN"); // add again // ub1.addAuth("ROLE_SITE_ADMIN"); UserBean userBean1 = userService.addUser(ub1, rCtx); Assert.assertNotNull("Failed to create ustest1. Why", userBean1); // send mail emailService.sendWelcomeEmail(userBean1); // try to add again UserBean userBean2 = userService.addUser(ub1, rCtx); Assert.assertNull("Should not have created duplicate user", userBean2); // Get users List<UserEntity> ueList = userService.getUsers(); Assert.assertNotNull("Should have got users", ueList); // Note that when the embedded db is initialized in tests, one admin // user is created : Admin/password Assert.assertTrue("Expected at least 2 users.", ueList.size() >= 2); // Get user name list List<String> unList = userService.getUserNames(); Assert.assertNotNull("Obtained null list of user names", unList); Assert.assertTrue("Expected at least 2 user name in list", unList.size() >= 2); // Look for Frodo UserBean frodo = userService.getUser("Frodo"); Assert.assertNotNull("Could not find Frodo", frodo); List<String> groups = frodo.getGroups(); Assert.assertNotNull("No groups for frodo?", groups); Assert.assertTrue("Expected exactly two groups for frodo", groups.size() == 2); Assert.assertTrue("Frodo must belong to the group named 'Weekend Outings'", groups.contains("Weekend Outings")); Assert.assertTrue("Frodo must belong to the group named 'Official Lunches'", groups.contains("Official Lunches")); // Get my user UserBean myUser = userService.getUser("ustest1"); Assert.assertNotNull("Failed to retrieve user by name", myUser); // Change password PasswordChangeBean pcb = new PasswordChangeBean(); pcb.setOldPassword("password"); pcb.setNewPassword("catanddog"); pcb.setNewPasswordAgain("catanddog"); boolean result = userService.changePassword(pcb, myUser, rCtx); Assert.assertTrue("Password change should have succeded", result); // send email emailService.sendPasswordResetEmail(myUser); // Fail this time pcb.setOldPassword("catanddog"); pcb.setNewPassword("tiger"); pcb.setNewPasswordAgain("tigeragain"); Assert.assertFalse("Password change should have failed", userService.changePassword(pcb, myUser, rCtx)); // Fail again pcb.setOldPassword("tiger"); pcb.setNewPassword("lion"); pcb.setNewPasswordAgain("lion"); Assert.assertFalse("Password change should have failed", userService.changePassword(pcb, myUser, rCtx)); // reset password of the user userService.resetPassword("ustest1", rCtx); // Is password change needed Assert.assertTrue("User is supposed to change password after reset by admin", userService.isPasswordChangeNeeded("ustest1")); // Update user myUser.setEmailId("d@g.com"); userService.updateUser(myUser, rCtx); // Get user name select items Assert.assertNotNull("Expected user select items", userService.getUserNamesSelectItems()); // Update authorization Assert.assertNotNull("Update auth failed", userService.updateAutorization(myUser, rCtx)); // delete user int result2 = userService.deleteUser(myUser.getId(), "Admin", rCtx); Assert.assertTrue("Failed to delete user", result2 == 0); // clear user data userBean1.clearUserData(); // remove Auths for (AuthBean ab : myUser.getAuthSet()) { userService.removeAuthById(ab.getAuthEntity().getId(), rCtx); } myUser.getAuthSet(); // get user beans Collection<UserBean> ubs = userService.getUserBeans(); Assert.assertNotNull("Failed to get user beans", ubs); }
From source file:gr.brid.castamuv.infrastructure.security.UserSignInAdaptor.java
public String signIn(String userId, Connection<?> connection, NativeWebRequest request) { UserProfile profile = connection.fetchUserProfile(); User user = userRepository.findByEmail(profile.getEmail()); if (user == null) { user = signUpService.signUp(profile.getEmail(), UUID.randomUUID().toString(), connection.getImageUrl()); }/* ww w. j a v a 2 s. com*/ SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken( user.getId().getId(), user.getPassword(), user.getAuthorities())); return null; }
From source file:org.callistasoftware.netcare.web.security.MobileAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { log.info("==== Mobile Authentication [DEV MODE] ===="); log.info("User: {}", authentication.getName()); final UserDetails details = getUserDetailsService().loadUserByUsername(authentication.getName()); log.info("User found: {}", details != null); log.info("=========================================="); return new UsernamePasswordAuthenticationToken(details, "", details.getAuthorities()); }
From source file:com.gisnet.cancelacion.web.controller.AutenticarUsuario.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); FindResponse<UsuarioInfo> find = service.findByUsername(username); UsuarioInfo usuario = find.getInfo(); if (usuario != null) { if (service.loguear(new FindByRequest(username, password))) { List<GrantedAuthority> grants = new ArrayList<>(); for (String rol : usuario.getRoles()) { grants.add(new SimpleGrantedAuthority(rol)); }/* w w w . ja va 2 s . c o m*/ return new UsernamePasswordAuthenticationToken(username, password, grants); } throw new AuthenticationServiceException("Autenticacion fallida"); } throw new UsernameNotFoundException("Usuario no encontrado."); }
From source file:org.btc4j.ws.impl.BtcUsernameTokenValidator.java
@Override protected void verifyPlaintextPassword(UsernameToken usernameToken, RequestData data) throws WSSecurityException { final String username = String.valueOf(usernameToken.getName()); final String password = String.valueOf(usernameToken.getPassword()); final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); try {/*w w w. j a va 2s. co m*/ SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken(new UserDetails() { private static final long serialVersionUID = -6884000787746976920L; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }, password, authorities)); } catch (Throwable t) { throw new WSSecurityException(t.getMessage(), t); } }
From source file:de.iew.framework.security.access.WebResourceAccessEvaluatorTest.java
/** * Testet den Fall, dass der Benutzer in der Rolle der geschtzten * Web-Ressource ist. Ergebnis Zugriff erlaubt. * * @throws Exception//from w ww . j a va 2s .c o m */ @Test public void testEvaluateHasAuthorityConfigAttributeUserIsInRole() throws Exception { // Testfix erstellen List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_JUNIT_TEST")); Authentication authenticationToken = new UsernamePasswordAuthenticationToken("JUnit", "JUnit", grantedAuthorities); FilterInvocation filterInvocation = new FilterInvocation("/junit", "GET"); Authority authority = new Authority(); authority.setSystemName("ROLE_JUNIT_TEST"); WebResourceAccessRule rule = new WebResourceAccessRule(); rule.setAuthority(authority); HasAuthorityConfigAttribute configAttribute = new HasAuthorityConfigAttribute(rule); // Das Testobjekt erstellen WebResourceAccessEvaluator webResourceAccessEvaluator = new WebResourceAccessEvaluator(); // Test und Auswertung assertTrue(webResourceAccessEvaluator.evaluate(authenticationToken, filterInvocation, configAttribute)); }