org.springframework.security.core.userdetails.UserDetails Java Examples

The following examples show how to use org.springframework.security.core.userdetails.UserDetails. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserDetailsServiceImpl.java    From Spring-Security-Third-Edition with MIT License 8 votes vote down vote up
@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);
}
 
Example #2
Source File: UserUtils.java    From syhthems-platform with MIT License 8 votes vote down vote up
/**
 * 从 Spring Security Context中获取 username 再获取 CustomUserDetails,若找不到则返回 null
 *
 * @return
 */
public CustomUserDetails getCustomUserDetailsFromSecurityContextHolderWithUsername() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        return null;
    }
    String username;
    if (authentication instanceof JwtAuthenticationToken) {
        username = ((JwtAuthenticationToken) authentication).getTokenAttributes().get("user_name").toString();
    } else {
        username = authentication.getName();
    }
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails instanceof CustomUserDetails) {
            return ((CustomUserDetails) userDetails).erasePassword();
        }
        return null;
    } catch (IllegalArgumentException e) {
        return null;
    }
}
 
Example #3
Source File: SecurityUtils.java    From java-microservices-examples with Apache License 2.0 8 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user.
 */
public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                return springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
                Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
                if (attributes.containsKey("preferred_username")) {
                    return (String) attributes.get("preferred_username");
                }
            } else if (authentication.getPrincipal() instanceof String) {
                return (String) authentication.getPrincipal();
            }
            return null;
        });
}
 
Example #4
Source File: UserDetailService.java    From SpringAll with MIT License 8 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 模拟一个用户,替代数据库获取逻辑
    MyUser user = new MyUser();
    user.setUserName(username);
    user.setPassword(this.passwordEncoder.encode("123456"));
    // 输出加密后的密码
    System.out.println(user.getPassword());

    List<GrantedAuthority> authorities = new ArrayList<>();
    if (StringUtils.equalsIgnoreCase("mrbird", username)) {
        authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
    } else {
        authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("test");
    }
    return new User(username, user.getPassword(), user.isEnabled(),
            user.isAccountNonExpired(), user.isCredentialsNonExpired(),
            user.isAccountNonLocked(), authorities);
}
 
Example #5
Source File: UserDetailsServiceImpl2.java    From ExamStack with GNU General Public License v2.0 8 votes vote down vote up
public UserDetails loadUserByUsername(String username)
		throws UsernameNotFoundException {
	// TODO Auto-generated method stub
	
	User user = userMapper.getUserByName(username);
	if(user == null)
		throw new UsernameNotFoundException("user not found!");
	//roles=角色代码
	List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles());
	userInfo = new UserInfo(username,"",user.isEnabled(),true,true,true,authorities);
	userInfo.setUserid(user.getUserId());
	userInfo.setRolesName(user.getRoles());
	userInfo.setTrueName(user.getTrueName());
	userInfo.setEmail(user.getEmail());
	userInfo.setPhoneNum(user.getPhoneNum());
	userInfo.setNationalId(user.getNationalId());
	userInfo.setDepId(user.getDepId());
	return userInfo;
}
 
Example #6
Source File: HomePageController.java    From Spring-Boot-2-Fundamentals with MIT License 8 votes vote down vote up
@GetMapping("/")
public String homePage(Model model) {
    // Fill in authorities for the model
    val authentication = SecurityContextHolder.getContext().getAuthentication();
    model.addAttribute("authorities", authentication.getAuthorities());

    // Fill in username (from principal) for the model
    Object principal = authentication.getPrincipal();
    String username = principal instanceof UserDetails
            ? ((UserDetails) principal).getUsername()
            : principal.toString();
    model.addAttribute("username", username);

    // Fill in the messages for the model
    List<ShortMessage> shortMessages = sms.findAll();
    model.addAttribute("shortMessages", shortMessages);
    return "index";
}
 
Example #7
Source File: UserDetailsServiceImpl.java    From Spring-Security-Third-Edition with MIT License 7 votes vote down vote up
@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);
}
 
Example #8
Source File: UserDetailsServiceImpl.java    From Spring-Security-Third-Edition with MIT License 7 votes vote down vote up
@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);
}
 
Example #9
Source File: SysUserDetailsServiceTest.java    From DAFramework with MIT License 7 votes vote down vote up
@Test
public void testLoadUserByUsername() {
	//test found user
	String username = "watano";
	UserDetails ud = userDetailsService.loadUserByUsername(username);
	notNull(ud, "UserDetails is not null");
	notNull(ud.getUsername(), "Username is not null");
	isTrue(username.equals(ud.getUsername()), "Username is not " + username);
	notNull(ud.getPassword(), "Password is not null");

	//UsernameNotFoundException
	try {
		username = "watano1";
		ud = userDetailsService.loadUserByUsername(username);
		fail("UserDetails is not null");
	} catch (UsernameNotFoundException e) {}
}
 
Example #10
Source File: CustomAuthenticationProvider.java    From Building-Web-Apps-with-Spring-5-and-Angular with MIT License 7 votes vote down vote up
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
	final String username = authentication.getName();
	final String password = authentication.getCredentials().toString();

	User user = null;
	try {
		user = userService.doesUserExist(username);
	} catch (UserNotFoundException e) {
	}

	if (user == null || !user.getEmail().equalsIgnoreCase(username)) {
		throw new BadCredentialsException("Username not found.");
	}

	if (!password.equals(user.getPassword())) {
		throw new BadCredentialsException("Wrong password.");
	}
	List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
	if(user.getRole() == 1) {
		authorities.add(new SimpleGrantedAuthority("ROLE_DOCTOR"));
	} else {
		authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
	}		
       final UserDetails principal = new org.springframework.security.core.userdetails.User(username, password, authorities);        
	return new UsernamePasswordAuthenticationToken(principal, password, authorities);
}
 
Example #11
Source File: WebFluxSecurityConfig.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public MapReactiveUserDetailsService userDetailsService() {
    UserDetails admin = User
            .withUsername("admin")
            .password(encoder().encode("password"))
            .roles("ADMIN")
            .build();

    UserDetails user = User
            .withUsername("user")
            .password(encoder().encode("password"))
            .roles("USER")
            .build();

    return new MapReactiveUserDetailsService(admin, user);
}
 
Example #12
Source File: JwtAuthenticationFilter.java    From MovieApp with MIT License 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    try {
        // Get jwt token
        String jwt = getJwtFromRequest(request);

        // Validate the token
        if (StringUtils.hasText(jwt) && tokenValidator.validateToken(jwt)) {
            // Build userDetails
            UserDetails userDetails = tokenValidator.getUserPrincipalFromJWT(jwt);

            // Crate auth object
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            // Authenticate the user
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    } catch (Exception ex) {
        logger.error("Could not set user authentication in security context", ex);
        // In case of failure. Make sure it's clear; so guarantee user won't be authenticated.
        SecurityContextHolder.clearContext();
    }

    filterChain.doFilter(request, response);
}
 
Example #13
Source File: UserServiceTest.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasics() throws IOException {
    userService.deleteUser("MODELER");

    Assert.assertTrue(!userService.userExists("MODELER"));

    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(Constant.ROLE_ADMIN));
    ManagedUser user = new ManagedUser("MODELER", "PWD", false, authorities);
    userService.createUser(user);

    Assert.assertTrue(userService.userExists("MODELER"));

    UserDetails ud = userService.loadUserByUsername("MODELER");
    Assert.assertEquals("MODELER", ud.getUsername());
    Assert.assertEquals("PWD", ud.getPassword());
    Assert.assertEquals(Constant.ROLE_ADMIN, ud.getAuthorities().iterator().next().getAuthority());
    Assert.assertEquals(2, ud.getAuthorities().size());

}
 
Example #14
Source File: User.java    From web-qq with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #15
Source File: Pac4jAuthenticationSuccessHandler.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
private ClientAuthenticationToken getAuthenticationTokenWithUserDetails(Authentication authentication) {
	Collection<? extends GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
	ClientAuthenticationToken token = getAuthenticationToken(authentication);
	
	if (token != null) {
		UserDetails userDetails = pac4jUserDetailsService.loadUserDetails(token);
		
		if (userDetails != null) {
			this.userDetailsChecker.check(userDetails);
			authorities = userDetails.getAuthorities();
		}
		ClientAuthenticationToken result =  new ClientAuthenticationToken((Credentials) token.getCredentials(),
				token.getClientName(), token.getUserProfile(), authorities);
		result.setDetails(userDetails);
		return result;
	}
	return null;
}
 
Example #16
Source File: CustomDeviceUserDetailsServiceImpl.java    From syhthems-platform with MIT License 6 votes vote down vote up
@Override
@Cacheable(cacheNames = "DeviceUserDetails",
        unless = "#username == null",
        cacheManager = "JDKCacheManager")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Device device;
    try {
        device = deviceService.selectByPrimaryKey(Long.valueOf(username));
    } catch (NumberFormatException e) {
        throw new UsernameNotFoundException("用户名必须为设备ID");
    }
    if (device == null) {
        throw new UsernameNotFoundException("该设备不存在");
    }
    if (device.getProductId() == null) {
        throw new ServiceException("设备没有绑定产品");
    }
    Product product = productService.selectByPrimaryKey(device.getProductId());
    if (product == null) {
        throw new ServiceException("设备没有绑定产品");
    }
    // List<DataStream> dataStreams = dataStreamService.selectByDeviceId(device.getDeviceId());
    List<DataStream> dataStreams = dataStreamService.selectByProductId(product.getProductId());
    return new CustomDeviceUserDetails(username,
            device.getDeviceSecret(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_DEVICE")), product, device, dataStreams);
}
 
Example #17
Source File: UserAuthenticationProvider.java    From java-tutorial with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    UserDetails userDetails = authUserService.loadUserByUsername(name);
    //认证逻辑
    if (null != userDetails) {
        //检查密码是否匹配
        if (bCryptPasswordEncoder.matches(password, userDetails.getPassword())) {
            // 这里设置权限和角色

            // 生成令牌 这里令牌里面存入了:name,password,authorities, 当然你也可以放其他内容
            Authentication auth = new UsernamePasswordAuthenticationToken(name, password, emptyList());
            return auth;
        } else {
            throw new BizException("密码错误");
        }
    } else {
        throw new BizException("用户不存在");
    }
}
 
Example #18
Source File: AuthenticationController.java    From spring-security-mybatis-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "${jwt.route.authentication.path}/personal", method = RequestMethod.POST)
public ResponseEntity<?> createPersonalAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
    authenticationRequest.setUsername(authenticationRequest.getPhone());
    // Perform the security
    Authentication authentication = null;

    try {
        authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        authenticationRequest.getUsername(),
                        authenticationRequest.getPassword()
                )
        );
    } catch (AuthenticationException e) {
        System.out.println(e.getMessage());
    }

    SecurityContextHolder.getContext().setAuthentication(authentication);

    // Reload password post-security so we can generate token
    final UserDetails userDetails = userDetailsService.loadUserByPhone(authenticationRequest.getPhone());
    final String token = jwtTokenUtil.generateToken(userDetails, device);

    // Return the token
    return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
 
Example #19
Source File: JwtAuthenticationFilter.java    From Spring-Boot-Blog-REST-API with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    try{
        String jwt = getJwtFromRequest(request);

        if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)){
            Long userId = tokenProvider.getUserIdFromJWT(jwt);

            UserDetails userDetails = customUserDetailsService.loadUserById(userId);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
    } catch (Exception ex){
        LOGGER.error("Could not set user authentication in security context", ex);
    }

    filterChain.doFilter(request, response);
}
 
Example #20
Source File: UserDetailsServiceImpl.java    From spring-boot-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    CustomUserDetails userDetails = userRepository.getUser(username);
    if (userDetails == null) {
        LOGGER.warn("{} not exist.", username);
        throw new UsernameNotFoundException(username + " not exists");
    }

    return new User(
            userDetails.getUsername(),
            userDetails.getPassword(),
            userDetails.getAccountEnabled(),
            userDetails.generateAccountNonExpired(),
            userDetails.generateCredentialsNonExpired(),
            !userDetails.getAccountLocked(),
            userDetails.generateAuthorities());

}
 
Example #21
Source File: UserDetailServiceImpl.java    From cloud-service with MIT License 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 为了支持多类型登录,这里username后面拼装上登录类型,如username|type
    String[] params = username.split("\\|");
    username = params[0];// 真正的用户名

    LoginAppUser loginAppUser = userClient.findByUsername(username);
    if (loginAppUser == null) {
        throw new AuthenticationCredentialsNotFoundException("用户不存在");
    } else if (!loginAppUser.isEnabled()) {
        throw new DisabledException("用户已作废");
    }

    if (params.length > 1) {
        // 登录类型
        CredentialType credentialType = CredentialType.valueOf(params[1]);
        if (CredentialType.PHONE == credentialType) {// 短信登录
            handlerPhoneSmsLogin(loginAppUser, params);
        } else if (CredentialType.WECHAT_OPENID == credentialType) {// 微信登陆
            handlerWechatLogin(loginAppUser, params);
        }
    }

    return loginAppUser;
}
 
Example #22
Source File: UserDetailsServiceImpl.java    From hellokoding-courses with MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
    User user = userRepository.findByUsername(username);
    if (user == null) throw new UsernameNotFoundException(username);

    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.getUsername(), user.getPassword(), grantedAuthorities);
}
 
Example #23
Source File: CalendarUserDetailsService.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example #24
Source File: SecurityUtils.java    From TeamDojo with Apache License 2.0 5 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user
 */
public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                return springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof String) {
                return (String) authentication.getPrincipal();
            }
            return null;
        });
}
 
Example #25
Source File: SecurityServiceImpl.java    From registration-login-spring-hsql with MIT License 5 votes vote down vote up
@Override
public String findLoggedInUsername() {
    Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
    if (userDetails instanceof UserDetails) {
        return ((UserDetails)userDetails).getUsername();
    }

    return null;
}
 
Example #26
Source File: UserService.java    From twissandra-j with Apache License 2.0 5 votes vote down vote up
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	LOG.info("Looking for user named {}", username);
	String password = m_tweetRepository.getPassword(username);
	if (password == null) {
		throw new UsernameNotFoundException("No user named " + username);
	}
	
	return new User(username, password);
}
 
Example #27
Source File: DbUserDetailService.java    From cymbal with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    User user = userEntityService.getByUserName(userName);
    if (Objects.isNull(user)) {
        throw new UsernameNotFoundException(String.format("Can not find a user with name '%s'.", userName));
    }
    if (userRoleProcessService.isAdmin(userName)) {
        return new org.springframework.security.core.userdetails.User(userName, user.getPassword(),
                AuthorityUtils.createAuthorityList(UserRole.ADMIN.getValue()));
    } else {
        return new org.springframework.security.core.userdetails.User(userName, user.getPassword(),
                AuthorityUtils.NO_AUTHORITIES);
    }
}
 
Example #28
Source File: MyUserDetailService.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    // 数据库存储密码为加密后的密文(明文为123456)
    String password = passwordEncoder.encode("123456");

    System.out.println("username: " + username);
    System.out.println("password: " + password);

    // 模拟查询数据库,获取属于Admin和Normal角色的用户
    User user = new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));

    return user;
}
 
Example #29
Source File: CalendarUserDetailsService.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example #30
Source File: SecurityUtils.java    From OpenIoE with Apache License 2.0 5 votes vote down vote up
/**
 * If the current user has a specific authority (security role).
 *
 * <p>The name of this method comes from the isUserInRole() method in the Servlet API</p>
 *
 * @param authority the authorithy to check
 * @return true if the current user has the authority, false otherwise
 */
public static boolean isCurrentUserInRole(String authority) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(authority));
        }
    }
    return false;
}