当前位置: 首页>>代码示例>>Java>>正文


Java UserDetails类代码示例

本文整理汇总了Java中org.springframework.security.core.userdetails.UserDetails的典型用法代码示例。如果您正苦于以下问题:Java UserDetails类的具体用法?Java UserDetails怎么用?Java UserDetails使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


UserDetails类属于org.springframework.security.core.userdetails包,在下文中一共展示了UserDetails类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: loadUserByUsername

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:kostovhg,项目名称:SoftUni,代码行数:22,代码来源:ListUserDetailsService.java

示例2: doFilter

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest httpServletRequest = (HttpServletRequest) request;

	String header_authorization = httpServletRequest.getHeader("Authorization");
	String token = (StringUtils.isBlank(header_authorization) ? null : header_authorization.split(" ")[1]);

	if (StringUtils.isBlank(header_authorization) && token == null) {
		logger.info("Token Not found in header.");
	} else {

		UserDetails principal = null;
		try {
			principal = authBuilder.getDefaultUserDetailsService().loadUserByUsername(token);
			UsernamePasswordAuthenticationToken userAuthenticationToken = new UsernamePasswordAuthenticationToken(
					principal, "", principal.getAuthorities());
			userAuthenticationToken
					.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
			SecurityContextHolder.getContext().setAuthentication(userAuthenticationToken);
		} catch (Exception e) {
			HttpServletResponse httpresposne = (HttpServletResponse) response;
			httpresposne.setContentType("application/json");
			httpresposne.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			ObjectMapper jsonMapper = new ObjectMapper();
			PrintWriter out = httpresposne.getWriter();
			Map<String, String> jsonResponse = new HashMap<String, String>();
			jsonResponse.put("msg", "Invalid Token");
			out.write(jsonMapper.writeValueAsString(jsonResponse));
			out.flush();
			out.close();
			return;
		}
		chain.doFilter(request, response);
	}
}
 
开发者ID:PacktPublishing,项目名称:Practical-Microservices,代码行数:37,代码来源:JwtAuthenticationTokenFilter.java

示例3: loadUserByUsername

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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;
}
 
开发者ID:TZClub,项目名称:OMIPlatform,代码行数:21,代码来源:TzUserDetailsService.java

示例4: loadUserByUsername

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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);
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:18,代码来源:UserDetailsServiceImpl.java

示例5: loadUserByUsername

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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);
}
 
开发者ID:howma03,项目名称:sporticus,代码行数:25,代码来源:ServiceDetailsImplRepositoryUser.java

示例6: equals

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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;
}
 
开发者ID:damingerdai,项目名称:web-qq,代码行数:24,代码来源:User.java

示例7: loadUserByUser

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
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);

}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:21,代码来源:DatabaseUserDetailsService.java

示例8: loadUserDetails

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
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);
}
 
开发者ID:kakawait,项目名称:cas-security-spring-boot-starter,代码行数:21,代码来源:GrantedAuthoritiesFromAssertionAttributesWithDefaultRolesUserDetailsService.java

示例9: retrieveUser

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:melthaw,项目名称:spring-backend-boilerplate,代码行数:24,代码来源:UserDetailsAuthenticationProviderImpl.java

示例10: userDetailsService

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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");
            }
        }
    };
}
 
开发者ID:2DV603NordVisaProject,项目名称:nordvisa_calendar,代码行数:24,代码来源:WebSecurityConfig.java

示例11: authenticate

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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;
}
 
开发者ID:jeikerxiao,项目名称:SpringBootStudy,代码行数:18,代码来源:JsonWebTokenAuthenticationProvider.java

示例12: loadUserByUsername

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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"));
}
 
开发者ID:ugouku,项目名称:shoucang,代码行数:20,代码来源:UserDetailsService.java

示例13: loadUserByUsername

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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);
}
 
开发者ID:Zuehlke,项目名称:springboot-sec-tutor,代码行数:16,代码来源:UserDetailsServiceImpl.java

示例14: setCurrentUser

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
@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);
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:11,代码来源:SpringSecurityUserContext.java

示例15: loadUserByUsername

import org.springframework.security.core.userdetails.UserDetails; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:13,代码来源:CalendarUserDetailsService.java


注:本文中的org.springframework.security.core.userdetails.UserDetails类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。