List of usage examples for org.springframework.security.core.userdetails User User
public User(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities)
User
with the details required by org.springframework.security.authentication.dao.DaoAuthenticationProvider . From source file:in.mycp.service.MycpAuthService.java
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String password = (String) authentication.getCredentials(); if (StringUtils.isBlank(password)) { throw new BadCredentialsException("Please enter password"); }/*from w w w . j a va 2s .c om*/ List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); in.mycp.domain.User mycpUser = null; try { ShaPasswordEncoder passEncoder = new ShaPasswordEncoder(256); String encodedPass = passEncoder.encodePassword(password, username); mycpUser = in.mycp.domain.User .findUsersByEmailEqualsAndPasswordEqualsAndActiveNot(username, encodedPass, false) .getSingleResult(); mycpUser.setLoggedInDate(new Date()); mycpUser = mycpUser.merge(); List<Role> roles = Role.findRolesByIntvalLessThan(mycpUser.getRole().getIntval() + 1).getResultList(); //everybody gets role_user //authorities.add(new GrantedAuthorityImpl("ROLE_USER")); for (Iterator iterator = roles.iterator(); iterator.hasNext();) { Role role = (Role) iterator.next(); authorities.add(new GrantedAuthorityImpl(role.getName())); } } catch (EmptyResultDataAccessException e) { log.error(e.getMessage());//e.printStackTrace(); throw new BadCredentialsException("Invalid username or password"); } catch (EntityNotFoundException e) { log.error(e.getMessage());//e.printStackTrace(); throw new BadCredentialsException("Invalid user"); } catch (NonUniqueResultException e) { throw new BadCredentialsException("Non-unique user, contact administrator"); } catch (Exception e) { throw new BadCredentialsException("Invalid username or password"); } return new User(mycpUser.getEmail(), mycpUser.getPassword(), mycpUser.getActive(), // enabled true, // account not expired true, // credentials not expired true, // account not locked authorities); }
From source file:com.persistent.cloudninja.web.security.CloudNinjaUserDetailsService.java
public UserDetails loadUserByCookie(String cookieValue) throws UsernameNotFoundException, DataAccessException { String[] cookieStrings = cookieValue.split("!"); List<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>(); String[] roleArray = cookieStrings[2].split(","); for (String role : roleArray) { userAuthorities.add(new GrantedAuthorityImpl(role)); }/*from w ww . j a v a2 s . co m*/ User user = new User(cookieStrings[0], "", true, true, true, true, userAuthorities); return user; }
From source file:org.opentides.persistence.user.AuthenticationDaoJdbcImpl.java
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { try {/*from www . j a v a2 s . c om*/ UserDetails user = super.loadUserByUsername(username); SessionUser sessUser = null; sessUser = new SessionUser(user); Map<String, Object> result = getJdbcTemplate() .queryForMap(loadUserByUsernameQuery.replace("?", "'" + username + "'")); for (String key : result.keySet()) sessUser.addProfile(key, result.get(key)); if (enableUserLockCheck) { if (userService.isUserLockedOut(username, maxAttempts, lockoutSeconds)) { user = new User(sessUser.getUsername(), sessUser.getPassword(), sessUser.isEnabled(), sessUser.isAccountNonExpired(), sessUser.isCredentialsNonExpired(), false, sessUser.getAuthorities()); return user; } } return sessUser; } catch (UsernameNotFoundException ex1) { _log.error(ex1); throw ex1; } catch (DataAccessException ex2) { _log.error(ex2); throw ex2; } }
From source file:org.carewebframework.security.spring.AbstractAuthenticationProvider.java
/** * Authentication Provider. Produces a trusted <code>UsernamePasswordAuthenticationToken</code> * if/*from w ww. j a v a 2 s .co m*/ * * @param authentication The authentication context. * @return authentication Authentication object if authentication succeeded. Null if not. */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { CWFAuthenticationDetails details = (CWFAuthenticationDetails) authentication.getDetails(); String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); String domain = null; if (log.isDebugEnabled()) { log.debug("User: " + username); log.debug("Details, RA: " + details == null ? "null" : details.getRemoteAddress()); } if (username != null) { String pcs[] = username.split("\\\\", 2); domain = pcs[0]; username = pcs.length > 1 ? pcs[1] : null; } ISecurityDomain securityDomain = domain == null ? null : SecurityUtil.getSecurityService().getSecurityDomain(domain); if (username == null || password == null || securityDomain == null) { throw new BadCredentialsException("Missing security credentials."); } IUser user = authenticate(username, password, securityDomain, details); details.setDetail("user", user); List<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>(); List<String> list = getAuthorities(user); Set<String> authorities = list == null ? new HashSet<String>() : new HashSet<String>(list); for (String grantedAuthority : grantedAuthorities) { if (grantedAuthority.startsWith("-")) { authorities.remove(grantedAuthority.substring(1)); } else { authorities.add(grantedAuthority); } } for (String authority : authorities) { if (!authority.isEmpty()) { userAuthorities.add(new SimpleGrantedAuthority(authority)); } } User principal = new User(username, password, true, true, true, true, userAuthorities); authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); ((UsernamePasswordAuthenticationToken) authentication).setDetails(details); return authentication; }
From source file:org.pentaho.custom.authentication.CustomUserDetailsService.java
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { final boolean ACCOUNT_NON_EXPIRED = true; final boolean CREDS_NON_EXPIRED = true; final boolean ACCOUNT_NON_LOCKED = true; // Retrieve the user from the custom authentication system IUser user;/*from ww w .j a v a2 s . co m*/ try { user = userRoleDao.getUser(getUserNameUtils().getPrincipleName(username)); } catch (UncategorizedUserRoleDaoException e) { throw new UserDetailsException("Unable to get the user role dao"); //$NON-NLS-1$ } // If the user is null, throw a NameNotFoundException if (user == null) { throw new UsernameNotFoundException( "Username [ " + getUserNameUtils().getPrincipleName(username) + "] not found"); //$NON-NLS-1$ } else { // convert IUser to a UserDetails instance int authsSize = user.getRoles() != null ? user.getRoles().size() : 0; GrantedAuthority[] auths = new GrantedAuthority[authsSize]; int i = 0; for (IRole role : user.getRoles()) { auths[i++] = new SimpleGrantedAuthority(role.getName()); } List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(Arrays.asList(auths)); if (authorities.size() == 0) { throw new UsernameNotFoundException( "User [ " + getUserNameUtils().getPrincipleName(username) + "] does not have any role"); //$NON-NLS-1$ } // Add default role to all authenticating users if (defaultRole != null && !authorities.contains(defaultRole)) { authorities.add(defaultRole); } GrantedAuthority[] arrayAuths = authorities.toArray(new GrantedAuthority[authorities.size()]); return new User(user.getUsername(), user.getPassword(), user.isEnabled(), ACCOUNT_NON_EXPIRED, CREDS_NON_EXPIRED, ACCOUNT_NON_LOCKED, Arrays.asList(arrayAuths)); } }
From source file:com.company.project.web.controller.service.CustomUserDetailsService.java
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try {// ww w . jav a 2 s . c o m // Map<String, String> user = new HashMap<String, String>(); // user.put("username", "admin"); // user.put("password", "admin"); // user.put("role", "ROLE_ADMIN"); // users.put("admin", user); // user = new HashMap<String, String>(); // user.put("username", "sadmin"); // user.put("password", "sadmin"); // user.put("role", "ROLE_SYS_ADMIN"); // users.put("sadmin", user); // user = new HashMap<String, String>(); // user.put("username", "user"); // user.put("password", "user"); // user.put("role", "ROLE_USER"); // users.put("user", user); // // user = users.get(username); Map<String, Object> user = null; //user = userService.get(username); //user = userDao.get(username); user = userMapperImpl.get(username); if (user == null) { return null; } if (username.contains("admin")) { user.put("role", "ROLE_ADMIN"); } else { user.put("role", "ROLE_USER"); } List<GrantedAuthority> authorities = getAuthorities("" + user.get("role")); boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; // BCryptPasswordEncoder automatically generates a salt and concatenates it. PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String encodedPassword = passwordEncoder.encode("" + user.get("password")); return new User("" + user.get("username"), encodedPassword, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.orchestra.portale.externalauth.FbAuthenticationManager.java
public static User fbLoginJs(HttpServletRequest request, HttpServletResponse response, UserRepository userRepository) { //Get access_token from request String access_token = request.getParameter("access_token"); User user = null;//from ww w. j a v a 2s. co m if (StringUtils.isNotEmpty(access_token)) { try { Boolean validity = FacebookUtils.ifTokenValid(access_token); //if token is valid, retrieve userid and email from Facebook if (validity) { Map<String, String> userId_mail = FacebookUtils.getUserIDMail(access_token); String id = userId_mail.get("id"); String email = userId_mail.get("email"); try { user = fbUserCheck(id, email, userRepository); } catch (UserNotFoundException ioex) { /*Retrieve User Data to Registration*/ Map<String, String> userData = FacebookUtils.getUserData(access_token); /*Create User*/ com.orchestra.portale.persistence.sql.entities.User new_user = new com.orchestra.portale.persistence.sql.entities.User(); new_user.setFbEmail(userData.get("email")); new_user.setFbUser(userData.get("id")); new_user.setUsername(userData.get("email")); new_user.setFirstName(userData.get("firstName")); new_user.setLastName(userData.get("lastName")); new_user.setPassword(new BigInteger(130, new SecureRandom()).toString(32)); /*Create Role*/ com.orchestra.portale.persistence.sql.entities.Role new_user_role = new com.orchestra.portale.persistence.sql.entities.Role(); new_user_role.setRole("ROLE_USER"); new_user_role.setUser(new_user); ArrayList<com.orchestra.portale.persistence.sql.entities.Role> new_user_roles = new ArrayList<com.orchestra.portale.persistence.sql.entities.Role>(); new_user_roles.add(new_user_role); new_user.setRoles(new_user_roles); /*Save User*/ userRepository.save(new_user); //Save user image try { String img_url = userData.get("img"); String user_id_img = userRepository.findByUsername(new_user.getUsername()).getId() .toString(); HttpSession session = request.getSession(); ServletContext sc = session.getServletContext(); String destination = sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img" + File.separator + user_id_img + File.separator; NetworkUtils.saveImageFromURL(img_url, destination, "avatar.jpg"); } catch (MalformedURLException ex) { throw new FacebookException(); } catch (IOException ioexc) { ioexc.getMessage(); } /*Create Spring User*/ boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; user = new User(new_user.getUsername(), new_user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(new_user.getRoles())); } } } catch (FacebookException ioex) { ioex.printStackTrace(); } } return user; }
From source file:com.healthcit.cacure.businessdelegates.UserManager.java
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { userService.setAuthType(Constants.DB_AUTH_VALUE); UserCredentials user = findByName(username); if (user == null) { throw new UsernameNotFoundException("Username not found"); }/*from w w w . j ava2 s.c o m*/ //local inner class class GrantedAuthorityImpl implements GrantedAuthority { private static final long serialVersionUID = -4708051153956036063L; private final String role; public GrantedAuthorityImpl(String role) { this.role = role; } @Override public String getAuthority() { return role; } @SuppressWarnings("unused") public int compareTo(Object o) { if (o instanceof GrantedAuthority) { return role.compareTo(((GrantedAuthority) o).getAuthority()); } return -1; } } //getting user Roles List<Role> roles = userManagerDao.getUserRoles(user); List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>(); if (roles != null && !roles.isEmpty()) { for (Role role : roles) { grantedAuthorityList.add(new GrantedAuthorityImpl(role.getName())); } } UserDetails res = new User(user.getUserName(), user.getPassword(), true, true, true, true, grantedAuthorityList); return res; }
From source file:org.jutge.joc.porra.security.MongoDBAuthenticationProvider.java
@Override public UserDetails retrieveUser(final String name, final UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { this.logger.info("MongoDBAuthenticationProvider.retrieveUser"); boolean valid = true; // Make sure an actual password was entered final String password = (String) authentication.getCredentials(); if (!StringUtils.hasText(password)) { this.logger.warn("Username {}: no password provided", name); valid = false;/*from w w w. j a va2 s . co m*/ } // Look for user and check their account is activated final Account account = this.accountService.getByName(name); if (account == null) { this.logger.warn("Username {}: user not found", name); valid = false; } else { if (!AccountStatus.STATUS_APPROVED.name().equals(account.getStatus())) { this.logger.warn("Username {}: not approved", name); valid = false; } // Check password final String hashedPassword = BCrypt.hashpw(password, account.getSalt()); if (!hashedPassword.equals(account.getHashedPass())) { this.logger.warn("Username {}: bad password entered", name); valid = false; } } if (!valid) { final Locale locale = LocaleContextHolder.getLocale(); final String message = this.messageSource.getMessage("exception.wrongAccountNameAndPass", null, locale); final MessageBox messageBox = new MessageBox("wrongAccountNameAndPass", message, new ArrayList<String>()); final List<MessageBox> errorMessages = new ArrayList<MessageBox>(); errorMessages.add(messageBox); final LoginException loginException = new LoginException(errorMessages, name); throw new BadCredentialsException("Invalid Username/Password", loginException); } // Create Springframework-typed User instance final List<String> roles = account.getRoles(); final List<GrantedAuthority> auths = !roles.isEmpty() ? AuthorityUtils.commaSeparatedStringToAuthorityList(account.getRolesCSV()) : AuthorityUtils.NO_AUTHORITIES; // enabled, account not expired, credentials not expired, account not locked return new User(name, password, true, true, true, true, auths); }
From source file:org.syncope.core.notification.NotificationTest.java
@Before public void setupSecurity() { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); for (Entitlement entitlement : entitlementDAO.findAll()) { authorities.add(new SimpleGrantedAuthority(entitlement.getName())); }//from www .j a v a 2 s . c o m UserDetails userDetails = new User(adminUser, "FAKE_PASSWORD", true, true, true, true, authorities); Authentication authentication = new TestingAuthenticationToken(userDetails, "FAKE_PASSWORD", authorities); SecurityContextHolder.getContext().setAuthentication(authentication); }