當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。