Java 类org.springframework.security.core.userdetails.UserDetails 实例源码

项目:SoftUni    文件:ListUserDetailsService.java   
@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);
    }
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:sporticus    文件:ServiceDetailsImplRepositoryUser.java   
@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);
}
项目:web-qq    文件:User.java   
@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;
}
项目:esup-sgc    文件:DatabaseUserDetailsService.java   
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);

}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:cas-security-spring-boot-starter    文件:GrantedAuthoritiesFromAssertionAttributesWithDefaultRolesUserDetailsService.java   
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);
}
项目:spring-backend-boilerplate    文件:UserDetailsAuthenticationProviderImpl.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:OMIPlatform    文件:TzUserDetailsService.java   
@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;
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:nordvisa_calendar    文件:WebSecurityConfig.java   
@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");
            }
        }
    };
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:SpringBootStudy    文件:JsonWebTokenAuthenticationProvider.java   
@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;
}
项目:shoucang    文件:UserDetailsService.java   
@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"));
}
项目:springboot-sec-tutor    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:CalendarUserDetailsService.java   
/**
 * 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);
}
项目:spring-cloud-template    文件:CustomUserServiceImpl.java   
@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;
}
项目:web-framework-for-java    文件:UserDetailsServiceImpl.java   
@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;
}
项目:Spring-Security-Third-Edition    文件:CalendarUserDetailsService.java   
/**
 * 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);
}
项目:oauth2-with-jdbc    文件:AccountUserDetailsService.java   
@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));
}
项目:markdown-redactor    文件:UserDetailsServiceImpl.java   
@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();
}
项目:jhipster-microservices-example    文件:SecurityUtils.java   
/**
 * 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;
}
项目:spring-auth-example    文件:HybridUserDetailsService.java   
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;
}
项目:FCat    文件:SecurityController.java   
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() + "; ");
        }
    }
}
项目:forum    文件:TopicController.java   
@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";
}
项目:TorgCRM-Server    文件:DomainUserDetailsService.java   
@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"));
    });
}
项目:DAFramework    文件:SysUserDetailsService.java   
/**
 * 根据用户名获取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;
}
项目:spring-security-oauth2-boot    文件:AuthenticationConfiguration.java   
@Bean
UserDetailsService userDetailsService() {
    UserDetails greg = User.withDefaultPasswordEncoder()
            .username("greg")
            .password("turnquist")
            .roles("read")
            .build();
    return new InMemoryUserDetailsManager(greg);
}
项目:pingguopai    文件:TokenHelper.java   
/**
 * 校验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()));
}
项目:MTC_Labrat    文件:SecurityUtils.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
@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);
}
项目:OAuth-2.0-Cookbook    文件:CustomUserDetailsService.java   
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<CustomUser> user =
        repository.findByUsername(username);

    return user.orElseThrow(() ->
        new UsernameNotFoundException("user does not exists"));
}
项目:yadaframework    文件:YadaSecurityUtil.java   
/**
 * 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;
}
项目:borabeber-api    文件:JwtUserDetailsServiceImpl.java   
@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.");
}
项目:Armory    文件:SecurityUtils.java   
/**
 * 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;
}