@Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException{ User user = userRepository.findByEmail(email); if(user == null) { throw new UsernameNotFoundException("Invalid User"); } else { Set<GrantedAuthority> grantedAuthorities = user.getRoles() .stream() .map(role -> new SimpleGrantedAuthority(role.getName())) .collect(Collectors.toSet()); return new org .springframework .security .core .userdetails .User(user.getEmail(), user.getPassword(), grantedAuthorities); } }
@Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { CalendarUser user = userRepository.findByEmail(username); if (user == null) throw new UsernameNotFoundException("username " + username + " not found"); Set<GrantedAuthority> grantedAuthorities = new HashSet<>(); for (Role role : user.getRoles()){ grantedAuthorities.add(new SimpleGrantedAuthority(role.getName())); } return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities); }
@Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException { LOGGER.info(() -> String.format("Checking for email '%s'", email)); final IUser myUser = userRepository.findByEmail(email.toLowerCase().trim()); if(myUser == null) { throw new UsernameNotFoundException("User not found"); } // If the user is a group manager or an organisation owner then they will receive addition List<String> roles = new ArrayList<>(); roles.add("ROLE_USER"); if(myUser.isAdmin()) { LOGGER.info(() -> String.format("\tUser is admin - email='%s'", email)); roles.add("ROLE_ADMIN"); } final List<GrantedAuthority> authorities = buildUserAuthority(roles); return buildUserForAuthentication(myUser, authorities); }
@Override public boolean equals(Object obj) { if(obj == null){ return false; } if(obj == this){ return true; } if(obj instanceof User){ if(obj instanceof UserDetails){ UserDetails userDetails = (UserDetails)obj; if(this.getUsername().equals(userDetails.getUsername())){ return true; } }else{ User user = (User)obj; if(this.getUsername().equals(user.getUsername())){ return true; } } } return false; }
public UserDetails loadUserByUser(User targetUser) throws UsernameNotFoundException { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); resynchronisationUserService.synchronizeUserInfo(targetUser.getEppn()); ldapGroup2UserRoleService.syncUser(targetUser.getEppn()); for(String role : targetUser.getRoles()) { authorities.add(new SimpleGrantedAuthority(role)); } return new org.springframework.security.core.userdetails.User(targetUser.getEppn(), "dummy", true, // enabled true, // account not expired true, // credentials not expired true, // account not locked authorities); }
protected UserDetails loadUserDetails(Assertion assertion) { String username = assertion.getPrincipal().getName(); if (!StringUtils.hasText(username)) { throw new UsernameNotFoundException("Unable to retrieve username from CAS assertion"); } List<GrantedAuthority> authorities = Arrays .stream(attributes) .map(a -> assertion.getPrincipal().getAttributes().get(a)) .filter(Objects::nonNull) .flatMap(v -> (v instanceof Collection) ? ((Collection<?>) v).stream() : Stream.of(v)) .map(v -> toUppercase ? v.toString().toUpperCase() : v.toString()) .map(r -> r.replaceFirst("^ROLE_", "")) .map(r -> new SimpleGrantedAuthority("ROLE_" + r)) .collect(Collectors.toList()); authorities.addAll(defaultGrantedAuthorities); return new User(username, NON_EXISTENT_PASSWORD_VALUE, authorities); }
/** * Implementation of an abstract method defined in the base class. The * retrieveUser() method is called by authenticate() method of the base * class. The latter is called by the AuthenticationManager. */ @Override protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails details; try { details = this.getUserDetailsService().loadUserByUsername(username); authentication.setDetails(details); } catch (DataAccessException repositoryProblem) { throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (details == null) { throw new AuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation"); } return details; }
@Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { User user = this.userService.findByName(name); TzUserDetails userDetails = new TzUserDetails(); if(user == null){ throw new UsernameNotFoundException("用户不存在"); } try { BeanUtils.copyProperties(userDetails,user); } catch (Exception e) { e.printStackTrace(); } logger.info("---->身份验证:"+userDetails.getUsername()+":"+userDetails.getPassword()); return userDetails; }
@Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { User user = dao.getUserByEmail(email); if(user != null) { return new org.springframework.security.core.userdetails.User( user.getEmail(), user.getPassword(), user.valid(), true, true, true, AuthorityUtils.createAuthorityList(user.fetchAuthorities()) ); } else { throw new UsernameNotFoundException("Could not find that user"); } } }; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication authenticationUser = null; // 只处理 PreAuthenticatedAuthenticationToken if (authentication.getClass().isAssignableFrom(PreAuthenticatedAuthenticationToken.class) && authentication.getPrincipal() != null) { String tokenHeader = (String) authentication.getPrincipal(); UserDetails userDetails = parseToken(tokenHeader); if (userDetails != null) { authenticationUser = new JsonWebTokenAuthentication(userDetails, tokenHeader); } } else { // 已经有 JsonWebTokenAuthentication authenticationUser = authentication; } return authenticationUser; }
@Override @Transactional public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); String lowercaseLogin = login.toLowerCase(); Optional<User> userFromDatabase = userRepository.findOneByLoginOrEmail(lowercaseLogin, lowercaseLogin); return userFromDatabase.map(user -> { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())) .collect(Collectors.toList()); return new org.springframework.security.core.userdetails.User(lowercaseLogin, user.getPassword(), grantedAuthorities); }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database")); }
@Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userService .getByUsername(username) .orElseThrow(() -> new UsernameNotFoundException(username + " not found")); HashSet<GrantedAuthority> authorities = new HashSet<>(); if(user.getRoles() != null) { user.getRoles().stream() .map(Role::getName) .map(SimpleGrantedAuthority::new) .forEach(authorities::add); } return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPasswordHash(), authorities); }
@Override public void setCurrentUser(CalendarUser user) { if (user == null) { throw new IllegalArgumentException("user cannot be null"); } UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }
/** * Lookup a {@link CalendarUser} by the username representing the email address. Then, convert the * {@link CalendarUser} into a {@link UserDetails} to conform to the {@link UserDetails} interface. */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { CalendarUser user = calendarUserDao.findUserByEmail(username); if (user == null) { throw new UsernameNotFoundException("Invalid username/password."); } return new CalendarUserDetails(user); }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDetailDTO userDetailDTO = userService.findUserByUsername(username); if (userDetailDTO == null) { throw new UsernameNotFoundException("用户名不存在"); } UserDetailDO userDetailDO = new UserDetailDO(); userDetailDO.setId(userDetailDTO.getUserId()); userDetailDO.setUsername(userDetailDTO.getUsername()); userDetailDO.setPassword(userDetailDTO.getSecret()); userDetailDO.setRoleList(userDetailDTO.getRoleList()); return userDetailDO; }
@Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = this.userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("username " + username + " not found"); } return user; }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return accountRepository .findByUsername(username) .map(account -> new User(account.getUsername(), account.getPassword(), AuthorityUtils.createAuthorityList("ROLE_USER"))) .orElseThrow(() -> new UsernameNotFoundException("Could not find " + username)); }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("loading user by username: {}", username); User user = userRepository.findByUsername(username); if (user == null) { log.info("user with username {} not found", username); throw new UsernameNotFoundException("username " + username + " not found"); } log.info("found user: {}", user); return org.springframework.security.core.userdetails.User .withUsername(user.getUsername()) .password(user.getPassword()) .authorities(new SimpleGrantedAuthority("ROLE_USER")) .build(); }
/** * Get the login of the current user. * * @return the login of the current user */ public static String getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String userName = null; if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userName = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userName = (String) authentication.getPrincipal(); } } return userName; }
private UserDetails loadBarUserDetails(String username) { Response response = userService.loadBarUser(username); if (logger.isDebugEnabled()) logger.debug("Loaded from bar details: " + response); if (response.isOk()) { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("BAR_READ")); authorities.add(new SimpleGrantedAuthority("BAR_WRITE")); return new User(username, "", authorities); } return null; }
private void setUserRole(UserDetails user, Map<String, Object> result, StringBuilder userRole) { if (user != null) { result.put("userName", user.getUsername()); Collection<? extends GrantedAuthority> roleLst = user.getAuthorities(); for (GrantedAuthority sga : roleLst) { userRole.append(sga.toString() + "; "); } } }
@GetMapping("topic/{id}") public String displayTopic(@PathVariable String id, Model model) { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = ((UserDetails)principal).getUsername(); Long idUser = userRepository.getUserByUsername(username).getId(); Topic topic = topicRepository.findTopicById(Long.valueOf(id)); List<Answer> answers = answerRepository.findAnswerByTopic_Id(Long.valueOf(id)); model.addAttribute("topic", topic); model.addAttribute("answers", answers); model.addAttribute("idUser", idUser); return "topic"; }
@Override @Transactional public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); Optional<User> userByEmailFromDatabase = userRepository.findOneWithAuthoritiesByEmail(lowercaseLogin); return userByEmailFromDatabase.map(user -> createSpringSecurityUser(lowercaseLogin, user)).orElseGet(() -> { Optional<User> userByLoginFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin); return userByLoginFromDatabase.map(user -> createSpringSecurityUser(lowercaseLogin, user)) .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database")); }); }
/** * 根据用户名获取UserDetails 默认接口实现方法 * */ @Override @NotNull public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { log.debug("loadUserByUsername:{}", userName); EUser user = fetchByName(userName); if (user == null) { throw new UsernameNotFoundException(userName); } return user; }
@Bean UserDetailsService userDetailsService() { UserDetails greg = User.withDefaultPasswordEncoder() .username("greg") .password("turnquist") .roles("read") .build(); return new InMemoryUserDetailsManager(greg); }
/** * 校验token, 是否被修改过密码 * @param token * @param userDetails * @return */ public Boolean validateToken(String token, UserDetails userDetails) { User user = (User) userDetails; final String username = getUsernameFromToken(token); final Date created = getIssuedAtDateFromToken(token); //final Date expiration = getExpirationDateFromToken(token); return ( username.equals(user.getUsername()) && !isTokenExpired(token) && !isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate())); }
@Override public void setCurrentUser(CalendarUser user) { if (user == null) { throw new IllegalArgumentException("user cannot be null"); } UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(),userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<CustomUser> user = repository.findByUsername(username); return user.orElseThrow(() -> new UsernameNotFoundException("user does not exists")); }
/** * Ritorna uno o l'altro parametro a seconda che l'utente corrente sia autenticato o meno * @param anonymousValue * @param authenticatedValue * @return */ public String caseAnonAuth(String anonymousValue, String authenticatedValue) { boolean authenticated = false; try { authenticated = SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserDetails; } catch (Exception e) { log.error("Can't get user principal (ignored)"); } return authenticated ? authenticatedValue : anonymousValue; }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<Usuario> usuario = usuarioService.buscarPorEmail(username); if (usuario.isPresent()) { return JwtUserFactory.create(usuario.get()); } throw new UsernameNotFoundException("Email não encontrado."); }