下面列出了怎么用org.springframework.security.core.userdetails.UsernameNotFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
SysUser user = userService.selectUserByUserName(username);
if (StringUtils.isNull(user))
{
log.info("登录用户:{} 不存在.", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
{
log.info("登录用户:{} 已被删除.", username);
throw new BaseException("对不起,您的账号:" + username + " 已被删除");
}
else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
{
log.info("登录用户:{} 已被停用.", username);
throw new BaseException("对不起,您的账号:" + username + " 已停用");
}
return createLoginUser(user);
}
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
User user = userRepository.findByName(name);
if (user == null) {
User mobileUser = userRepository.findByMobile(name);
}
else {
user = userRepository.findByMobile(name);
}
/* else if("locked".equals(user.getStatus())) { //被锁定,无法登录
throw new LockedException("用户被锁定");
}*/
return user;
}
@Override
public UserDetails loadByPhoneNumber(String phoneNumber) {
UserDto userDto = userService.findByPhoneNumber(phoneNumber);
if (userDto == null) {
throw new UsernameNotFoundException("User " + phoneNumber + " can not be found");
}
return AuthenticatedUser.builder()
.id(userDto.getId())
.username(userDto.getUsername())
.password(userDto.getPassword())
.phoneNumber(userDto.getPhoneNumber())
.email(userDto.getEmail())
.avatar(userDto.getAvatar())
.locked(UserStatus.LOCKED.getValue().equals(userDto.getStatus()))
.enable(UserStatus.ACTIVE.getValue().equals(userDto.getStatus()))
.build();
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//查询用户
SysUserVo sysUserVo = sysUserService.findByLoginName(username).getData();
//查询权限
List<SysUserAuthorityVo> sysUserAuthorityVoList = sysUserAuthorityService.findByUserId(sysUserVo.getUserId()).getData();
StringBuilder authorityList = new StringBuilder();
for (int i = 0; i < sysUserAuthorityVoList.size(); i++) {
SysUserAuthorityVo sysUserAuthorityVo = sysUserAuthorityVoList.get(i);
authorityList.append(sysUserAuthorityVo.getSysAuthority().getAuthorityName());
if (i != sysUserAuthorityVoList.size() - 1) {
authorityList.append(",");
}
}
//查无此用户
if(StringUtils.isEmpty(sysUserVo.getUserId())){
sysUserVo.setLoginName("查无此用户");
sysUserVo.setPassword("查无此用户");
}
// 封装用户信息,并返回。参数分别是:用户名,密码,用户权限
return new User(sysUserVo.getLoginName(), sysUserVo.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authorityList.toString()));
}
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user -> {
if (!user.isActivated()) {
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
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
String message;
if (exception instanceof UsernameNotFoundException) {
message = "用户不存在!";
} else if (exception instanceof BadCredentialsException) {
message = "用户名或密码错误!";
} else if (exception instanceof LockedException) {
message = "用户已被锁定!";
} else if (exception instanceof DisabledException) {
message = "用户不可用!";
} else if (exception instanceof AccountExpiredException) {
message = "账户已过期!";
} else if (exception instanceof CredentialsExpiredException) {
message = "用户密码已过期!";
// } else if (exception instanceof ValidateCodeException || exception instanceof FebsCredentialExcetion) {
// message = exception.getMessage();
} else {
message = "认证失败,请联系网站管理员!";
}
// response.setContentType(FebsConstant.JSON_UTF8);
// response.getWriter().write(mapper.writeValueAsString(ResponseBo.error(message)));
}
/**
* 查询用户信息
* 根据数据源的数据库链接进行执行查询用户信息
*
* @param username 用户名
* @return 用户实例
*/
private ApiBootDefaultUserDetails findUser(String username) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
connection = dataSource.getConnection();
ps = connection.prepareStatement(DEFAULT_SELECT_USER_SQL);
ps.setString(1, username);
// 执行查询
resultSet = ps.executeQuery();
// 返回转换后的实体对象
return wrapperOneResult(ApiBootDefaultUserDetails.class, resultSet);
} catch (Exception e) {
throw new UsernameNotFoundException("Username:" + username + ",not found.");
} finally {
closeResultSet(resultSet);
closeStatement(ps);
closeConnection(connection);
}
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("username: {}", username);
AccountEntity accountEntity = null;
try {
accountEntity = accountService.queryByUsername(username);
} catch (Exception e) {
throw new UsernameNotFoundException("sql execute error!");
}
String password = accountEntity.getPassword();
log.info("password: {}", password);
User user = new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
return user;
}
/**
* 实现UserDetailsService中的loadUserByUsername方法,用于加载用户数据
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.queryUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
//用户权限列表
Collection<? extends GrantedAuthority> authorities = userService.queryUserAuthorities(user.getId());
return new AuthUser(
user.getId(),
user.getUsername(),
user.getPassword(),
true,
true,
true,
true,
authorities);
}
private SecurityUser authenticateByUserId(Long userId) {
UserEntity user = userService.findUserById(userId);
if (user == null) {
throw new UsernameNotFoundException("User not found by refresh token");
}
UserCredentialsEntity userCredentials = userService.findUserCredentialsByUserId(user.getId());
if (userCredentials == null) {
throw new UsernameNotFoundException("User credentials not found");
}
if (!userCredentials.isEnabled()) {
throw new DisabledException("User is not active");
}
if (user.getAuthority() == null) {
throw new InsufficientAuthenticationException("User has no authority assigned");
}
UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal);
return securityUser;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isInstanceOf(OpenIdAuthenticationToken.class, authentication, "unsupported authentication type");
Assert.isTrue(!authentication.isAuthenticated(), "already authenticated");
OpenIdAuthenticationToken authToken = (OpenIdAuthenticationToken) authentication;
String userId = toUserId(authToken);
if (userId == null) {
throw new BadCredentialsException("Unknown access token");
}
UserDetails userDetails = userDetailsService.loadUserByUserId(userId);
if (userDetails == null) {
throw new UsernameNotFoundException("Unknown connected account id");
}
preAuthenticationChecks.check(userDetails);
postAuthenticationChecks.check(userDetails);
return this.createSuccessAuthentication(userDetails, authentication, userDetails);
}
private Authentication authenticateByPublicId(UserPrincipal userPrincipal, Long publicId) {
CustomerEntity publicCustomer = customerService.findCustomerById(publicId);
if (publicCustomer == null){
throw new UsernameNotFoundException("Public entity not found: "+ publicId);
}
UserEntity userEntity = new UserEntity();
userEntity.setTenantId(publicCustomer.getTenantId());
userEntity.setCustomerId(publicCustomer.getId());
userEntity.setEmail(publicId.toString());
userEntity.setAuthority(Authority.CUSTOMER_USER);
userEntity.setName("Public");
SecurityUser securityUser = new SecurityUser(userEntity, true, userPrincipal);
return new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
}
@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;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = String.valueOf(authentication.getPrincipal());
log.debug("Authenticating user = '{}', password length = '{}' character(s)",
authentication.getPrincipal(), String.valueOf(authentication.getCredentials()).length());
SystemUser systemUser = systemUserRepo.findByUsername(username);
if (Objects.isNull(systemUser)) {
log.debug("Authentication failed. User '{}' not found", authentication.getPrincipal());
throw new AuthenticationRefusedException(Constants.AUTHENTICATION_FAILURE_MESSAGE);
}
if (systemUser.getAuthProvider() == AuthProvider.LOCAL) {
if (passwordEncoder.matches(String.valueOf(authentication.getCredentials()), systemUser.getPassword())) {
log.debug("User '{}' authenticated successfully", authentication.getPrincipal());
return new UsernamePasswordAuthenticationToken(username, systemUser.getPassword(),
RoleAuthority.asCollection(new RoleAuthority(systemUser.getRole())));
}
}
log.debug("Authentication failed. User '{}' not found", authentication.getPrincipal());
throw new UsernameNotFoundException(Constants.AUTHENTICATION_FAILURE_MESSAGE);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
log.debug("Authenticating user = '{}', password length = '{}' character(s)",
authentication.getPrincipal(), String.valueOf(authentication.getCredentials()).length());
try {
UserDetails userDetails = userDetailsService.loadUserByUsername(String.valueOf(authentication.getPrincipal()));
if (Objects.equals(userDetails.getUsername(), authentication.getPrincipal())
&& Objects.equals(userDetails.getPassword(), authentication.getCredentials())) {
log.debug("User '{}' authenticated successfully", authentication.getPrincipal());
return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(),
userDetails.getAuthorities());
}
} catch (UsernameNotFoundException ignored) {
}
log.debug("Authentication failed. User '{}' not found", authentication.getPrincipal());
throw new UsernameNotFoundException(Constants.AUTHENTICATION_FAILURE_MESSAGE);
}
/**
* 登录返回token
*
* @param user
* @return
*/
@ApiOperation(value = "用户登录", notes = "用户名+密码 name+password 返回token")
@PostMapping("/login")
public Result login(User user) {
if (!formatUtil.checkStringNull(user.getName(), user.getPassword())) {
return Result.create(StatusCode.ERROR, "参数错误");
}
try {
Map map = userService.login(user);
loginService.saveLoginInfo(user);
return Result.create(StatusCode.OK, "登录成功", map);
} catch (UsernameNotFoundException unfe) {
return Result.create(StatusCode.LOGINERROR, "登录失败,用户名或密码错误");
} catch (RuntimeException re) {
return Result.create(StatusCode.LOGINERROR, re.getMessage());
}
}
/**
* 加载用户信息
*
* @param username username
* @param authentication authentication
* @return UserDetails
* @throws AuthenticationException
*/
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException, TenantNotFoundException{
UserDetails loadedUser;
try {
// 加载用户信息
loadedUser = this.userDetailsService.loadUserByIdentifierAndTenantCode(TenantContextHolder.getTenantCode(), authentication.getPrincipal().toString());
} catch (UsernameNotFoundException notFound) {
if (authentication.getCredentials() != null) {
String presentedPassword = authentication.getCredentials().toString();
passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
}
throw notFound;
} catch (Exception tenantNotFound) {
throw new InternalAuthenticationServiceException(tenantNotFound.getMessage(), tenantNotFound);
}
if (loadedUser == null) {
throw new InternalAuthenticationServiceException("get user information failed");
}
return loadedUser;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser sysUser = userService.getByUsername(username);
if (null == sysUser) {
log.warn("用户{}不存在", username);
throw new UsernameNotFoundException(username);
}
List<SysPermission> permissionList = permissionService.findByUserId(sysUser.getId());
List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
if (!CollectionUtils.isEmpty(permissionList)) {
for (SysPermission sysPermission : permissionList) {
authorityList.add(new SimpleGrantedAuthority(sysPermission.getUri()));
}
}
User myUser = new User(sysUser.getUsername(), passwordEncoder.encode(sysUser.getPassword()), authorityList);
log.info("登录成功!用户: {}", JSON.toJSONString(myUser));
return myUser;
}
/**
* 认证过程中 - 根据登录信息获取用户详细信息
*
* @param s 登录用户输入的用户名
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//根据用户输入的用户信息,查询数据库中已注册用户信息
TUser user = userService.findByName(s);
//如果用户不存在直接抛出UsernameNotFoundException异常
if (user == null) throw new UsernameNotFoundException("用户名为" + s + "的用户不存在");
List<TRole> roles = user.getRoleList();
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (TRole role:roles){
List<TPermission> permissions = role.getPermissions();
for (TPermission permission:permissions){
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getUrl());
// 此处将权限信息添加到 GrantedAuthority 对象中,在后面进行权限验证时会使用GrantedAuthority 对象
grantedAuthorities.add(grantedAuthority);
}
}
return new CustomUserDetails(user, grantedAuthorities);
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String message;
if (exception instanceof UsernameNotFoundException) {
message = "用户不存在!";
} else if (exception instanceof BadCredentialsException) {
message = "用户名或密码错误!";
} else if (exception instanceof LockedException) {
message = "用户已被锁定!";
} else if (exception instanceof DisabledException) {
message = "用户不可用!";
} else if (exception instanceof AccountExpiredException) {
message = "账户已过期!";
} else if (exception instanceof CredentialsExpiredException) {
message = "用户密码已过期!";
} else if (exception instanceof InternalAuthenticationServiceException) {
message = "内部错误!";
} else {
message = ResultEnum.AUTHENCATION_ERROR.getValue();
}
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(BaseConstants.JSON_UTF8);
response.getWriter().write(mapper.writeValueAsString(
ResultUtils.error(ResultEnum.AUTHENCATION_ERROR.getKey(), message)));
}
@Override
public Object loadUserBySAML(SAMLCredential samlCredential) throws UsernameNotFoundException {
final String userEmail = samlCredential.getAttributeAsString("email");
logger.debug("samlCredential.email:" + userEmail);
final String userName = userEmail.substring(0, userEmail.indexOf("@"));
KylinUserManager userManager = KylinUserManager.getInstance(KylinConfig.getInstanceFromEnv());
ManagedUser existUser = userManager.get(userName);
// create if not exists
if (existUser == null) {
ManagedUser user = new ManagedUser(userName, NO_EXISTENCE_PASSWORD, true, defaultAuthorities);
userManager.update(user);
}
return userManager.get(userName);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getPrincipal() == null?"NONE_PROVIDED":authentication.getName();
UserDetails user;
try {
user = this.retrieveUser(username, authentication);
} catch (UsernameNotFoundException var6) {
log.debug("User \'" + username + "\' not found");
throw var6;
}
return this.createSuccessAuthentication(authentication, user);
}
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
User user = userRepository.findByName(name);
if (user == null) {
User mobileUser = userRepository.findByMobile(name);
if (mobileUser == null) {
User emailUser= userRepository.findByEmail(name);
if(emailUser==null)
{ throw new UsernameNotFoundException("用户名邮箱手机号不存在!");
}
else{
user=userRepository.findByEmail(name);
}
}
else {
user = userRepository.findByMobile(name);
}
}
/* else if("locked".equals(user.getStatus())) { //被锁定,无法登录
throw new LockedException("用户被锁定");
}*/
return user;
}
@Bean
public UserDetailsService userDetailsService() {
//获取登录用户信息
return username -> {
SmsStaff staff = smsStaffService.selectByUserName(username);//保证了User存在且状态不为0
if (staff != null) {
//拉取权限
List<SmsPermission> permissionList = smsRoleService.getPermissionList(staff.getId());
return new StaffDetails(staff,permissionList);
}
throw new UsernameNotFoundException("用户名或密码错误");
};
}
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
SysUser user = sysUserRepository.findByName(name);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
} else if (!user.getEnabled()) { //被锁定,无法登录
throw new LockedException("用户被锁定");
}
System.out.println(user.getEnabled());
return user;
}
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
User user = userRepository.findByName(name);
if (user == null) {
User mobileUser = userRepository.findByMobile(name);
if (mobileUser == null) {
User emailUser= userRepository.findByEmail(name);
if(emailUser==null)
{ throw new UsernameNotFoundException("用户名邮箱手机号不存在!");
}
else{
user=userRepository.findByEmail(name);
}
}
else {
user = userRepository.findByMobile(name);
}
}
/* else if("locked".equals(user.getStatus())) { //被锁定,无法登录
throw new LockedException("用户被锁定");
}*/
return user;
}
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
User user = userRepository.findByName(name);
if (user == null) {
User mobileUser = userRepository.findByMobile(name);
if (mobileUser == null) {
User emailUser= userRepository.findByEmail(name);
if(emailUser==null)
{ throw new UsernameNotFoundException("用户名邮箱手机号不存在!");
}
else{
user=userRepository.findByEmail(name);
}
}
else {
user = userRepository.findByMobile(name);
}
}
/* else if("locked".equals(user.getStatus())) { //被锁定,无法登录
throw new LockedException("用户被锁定");
}*/
return user;
}
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
SysUser user = sysUserRepository.findByName(name);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
} else if (!user.getEnabled()) { //被锁定,无法登录
throw new LockedException("用户被锁定");
}
System.out.println(user.getEnabled());
return user;
}
@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);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<CustomizedUserDetails> findFirst = inMemoryUserList.stream()
.filter(user -> user.getUsername().equals(username)).findFirst();
if (!findFirst.isPresent()) {
throw new UsernameNotFoundException(String.format("USER_NOT_FOUND '%s'.", username));
}
return findFirst.get();
}