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

The following examples show how to use org.springframework.security.core.userdetails.UsernameNotFoundException. 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: SmsUserDetailsServiceImpl.java    From cola with MIT License 7 votes vote down vote up
@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();

}
 
Example #2
Source File: OpenIdAuthenticationProvider.java    From cola with MIT License 6 votes vote down vote up
@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);
}
 
Example #3
Source File: CustomUserDetailsAuthenticationProvider.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
  * 加载用户信息
  *
  * @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;
 }
 
Example #4
Source File: UserController.java    From Blog with Apache License 2.0 6 votes vote down vote up
/**
 * 登录返回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());
    }

}
 
Example #5
Source File: UserSecurityService.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@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;

}
 
Example #6
Source File: UserDetailsServiceImpl.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
@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);
}
 
Example #7
Source File: UserConfig.java    From base-admin with MIT License 6 votes vote down vote up
@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()));
}
 
Example #8
Source File: DomainUserDetailsService.java    From flair-engine with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #9
Source File: CustomAuthenticationFailureHandler.java    From syhthems-platform with MIT License 6 votes vote down vote up
@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)));
}
 
Example #10
Source File: ApiBootDefaultStoreDelegate.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 查询用户信息
 * 根据数据源的数据库链接进行执行查询用户信息
 *
 * @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);
    }
}
 
Example #11
Source File: AccountDetailsService.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #12
Source File: MyUserDetailsService.java    From spring-security with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: FallbackAuthenticationProvider.java    From radman with MIT License 6 votes vote down vote up
@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);
}
 
Example #14
Source File: UserDetailsServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 实现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);
}
 
Example #15
Source File: LocalAuthenticationProvider.java    From radman with MIT License 6 votes vote down vote up
@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);
}
 
Example #16
Source File: CustomUserDetailsService.java    From spring-security with Apache License 2.0 6 votes vote down vote up
/**
 * 认证过程中 - 根据登录信息获取用户详细信息
 *
 * @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);
}
 
Example #17
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 #18
Source File: FebsAuthenticationFailureHandler.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
@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)));
    }
 
Example #19
Source File: RefreshTokenAuthenticationProvider.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #20
Source File: RestAuthenticationProvider.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
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());
    }
 
Example #21
Source File: SecurityConfig.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Bean
public UserDetailsService userDetailsService() {
    //获取登录用户信息
    return username -> {
        UmsAdmin admin = adminService.getAdminByUsername(username);
        if (admin != null) {
            List<UmsPermission> permissionList = adminService.getPermissionList(admin.getId());
            return new AdminUserDetails(admin,permissionList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    };
}
 
Example #22
Source File: SophiaUserDetailService.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    if(StringUtils.isBlank(username)){
        throw new CommonException("登录名不能为空");
    }
    ApiResponse apiResponse = userClient.getUserByUserName(username);
    if (!SophiaHttpStatus.SUCCESS.getCode().equals(apiResponse.getCode())){
        throw new CommonException(apiResponse.getMessage());
    }
    User user = JSONObject.parseObject(JSONObject.toJSONString(apiResponse.getData(), true),User.class);
    if (user == null) {
        throw new CommonException("登录名不存在");
    } else if (BizConstants.USER_STATUS_EXPIRED.equals(user.getStatus())) {
        throw new CommonException("用户已过期");
    } else if (BizConstants.USER_STATUS_LOCKED.equals(user.getStatus())) {
        throw new CommonException("用户已锁定");
    } else if (BizConstants.USER_STATUS_UNUSED.equals(user.getStatus())) {
        throw new CommonException("用户已禁用");
    }
    ApiResponse response = authorityClient.getAuthorityByUserId(user.getId());
    List<PermissionVo> authList = JSON.parseArray(JSON.toJSONString(response.getData(), true), PermissionVo.class);
    List<GrantedAuthority> lists = new ArrayList<>();
    if(authList != null && authList.size()>0){
        for (PermissionVo auth : authList) {
            if (StringUtils.isNotBlank(auth.getCode())) {
                lists.add(new SimpleGrantedAuthority(auth.getCode()));
            }
        }
    }
    LoginUser loginUser = new LoginUser(username,user.getPassword(),user.getNickname(),user.getStatus(), lists);
    loginUser.setId(user.getId());
    loginUser.setDeptId(user.getDeptId());
    loginUser.setCompId(user.getCompId());
    return loginUser;
}
 
Example #23
Source File: SingleUserDetailsManagerImpl.java    From radman with MIT License 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    if (Objects.nonNull(userDetails) && Objects.equals(userDetails.getUsername(), username)) {
        return userDetails;
    }
    throw new UsernameNotFoundException(Constants.AUTHENTICATION_FAILURE_MESSAGE);
}
 
Example #24
Source File: KylinUserService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public KylinUserService(List<User> users) throws IOException {
    pwdEncoder = new BCryptPasswordEncoder();
    synchronized (KylinUserService.class) {
        KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
        if (!StringUtils.equals("testing", kylinConfig.getSecurityProfile())) {
            return;
        }
        List<ManagedUser> all = listUsers();
        configUsers = users;
        // old security.xml config user pwd sync to user metadata
        if (!configUsers.isEmpty()) {
            for (User cuser : configUsers) {
                try {
                    String username = cuser.getUsername();
                    ManagedUser userDetail = (ManagedUser) loadUserByUsername(username);
                    if (userDetail != null && new KylinVersion(userDetail.getVersion()).major < KylinVersion
                            .getCurrentVersion().major) {
                        updateUser(new ManagedUser(cuser.getUsername(), cuser.getPassword(), false,
                                cuser.getAuthorities()));
                    }
                } catch (UsernameNotFoundException e) {
                    // add new security user in security.xml if it is not in metadata
                    createUser(new ManagedUser(cuser.getUsername(), cuser.getPassword(), false,
                            cuser.getAuthorities()));
                }
            }
        }
        // add default user info in metadata
        if (all.isEmpty() && configUsers.isEmpty()) {
            createUser(new ManagedUser(ADMIN, pwdEncoder.encode(ADMIN_DEFAULT), true, Constant.ROLE_ADMIN,
                    Constant.GROUP_ALL_USERS));
            createUser(new ManagedUser(ANALYST, pwdEncoder.encode(ANALYST), true, Constant.GROUP_ALL_USERS));
            createUser(new ManagedUser(MODELER, pwdEncoder.encode(MODELER), true, Constant.GROUP_ALL_USERS));
        }
    }

}
 
Example #25
Source File: UserDetailsServiceImpl.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String s) throws
        UsernameNotFoundException {
    System.out.println("经过UserDetailsServiceImpl");
    //构建角色集合,项目中此处应该是根据用户名查询用户的角色列表
    List<GrantedAuthority> grantedAuthors = new ArrayList<>();
    grantedAuthors.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    return new User(s, "$2a$10$61ogZY7EXsMDWeVGQpDq3OBF1.phaUu7.xrwLyWFTOu8woE08zMIW",
            grantedAuthors);
}
 
Example #26
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 #27
Source File: MobileAuthenticationFilter.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals(HttpMethod.POST.name()))
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    // 获取手机登录的参数
    String mobile = obtainMobile(request);
    if (mobile == null) {
        mobile = "";
    }
    mobile = mobile.trim();
    // 封装成token
    MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile);
    // 封装其它基本信息
    setMobileUserDetails(request, mobileAuthenticationToken);
    setDetails(request, mobileAuthenticationToken);
    Authentication authResult = null;
    try {
        // 认证
        authResult = this.getAuthenticationManager().authenticate(mobileAuthenticationToken);
        logger.debug("Authentication success: " + authResult);
        // 认证成功
        eventPublisher.publishAuthenticationSuccess(authResult);
        SecurityContextHolder.getContext().setAuthentication(authResult);
    } catch (Exception failed) {
        SecurityContextHolder.clearContext();
        logger.debug("Authentication request failed: " + failed);
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
        try {
            authenticationEntryPoint.commence(request, response, new UsernameNotFoundException(failed.getMessage(), failed));
        } catch (Exception e) {
            logger.error("authenticationEntryPoint handle error:{}", failed);
        }
    }
    return authResult;
}
 
Example #28
Source File: UserDetailsServiceImpl.java    From cloud-template with MIT License 5 votes vote down vote up
/**
 * 构造包含用户信息的UserDetails对象。本项目仅提供用户信息,其他数据模拟
 * 应该包括:用户信息、角色信息、权限信息,这些数据都应该从数据库中查询。
 *
 * @param result
 * @return
 */
private UserDetails getUserDetails(Result<SysUser> result) {
    if (result == null || result.getData() == null) {
        throw new UsernameNotFoundException("用户不存在");
    }
    SysUser user = result.getData();

    // 模拟构造包含用户角色列表的`List<GrantedAuthority>`对象
    List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("ADMIN");

    return new SctUser(user.getId(), user.getUsername(), user.getPassword(), true, true, true, true, authorityList);
}
 
Example #29
Source File: SecurityConfig.java    From macrozheng with Apache License 2.0 5 votes vote down vote up
@Bean
public UserDetailsService userDetailsService() {
    //获取登录用户信息
    return new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            UmsMember member = memberService.getByUsername(username);
            if(member!=null){
                return new MemberDetails(member);
            }
            throw new UsernameNotFoundException("用户名或密码错误");
        }
    };
}
 
Example #30
Source File: CustomUserDetailsServiceImpl.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
   * 根据社交账号查询
*
* @param tenantCode tenantCode
   * @param social     social
   * @param mobileUser mobileUser
   * @return UserDetails
   * @author tangyi
   * @date 2019/06/22 21:08
   */
  @Override
  public UserDetails loadUserBySocialAndTenantCode(String tenantCode, String social, MobileUser mobileUser) throws UsernameNotFoundException {
      long start = System.currentTimeMillis();
      ResponseBean<UserVo> userVoResponseBean = userServiceClient.findUserByIdentifier(social, IdentityType.PHONE_NUMBER.getValue(), tenantCode);
      if (!ResponseUtil.isSuccess(userVoResponseBean))
          throw new ServiceException(GET_USER_INFO_FAIL + userVoResponseBean.getMsg());
      UserVo userVo = userVoResponseBean.getData();
      // 第一次登录
      if (userVo == null) {
          UserDto userDto = new UserDto();
          // 用户的基本信息
          if (mobileUser != null)
              BeanUtils.copyProperties(mobileUser, userDto);
          userDto.setIdentifier(social);
          userDto.setCredential(social);
          userDto.setIdentityType(IdentityType.PHONE_NUMBER.getValue());
          userDto.setLoginTime(DateUtils.asDate(LocalDateTime.now()));
          // 注册账号
          ResponseBean<Boolean> response = userServiceClient.registerUser(userDto);
          if (!ResponseUtil.isSuccess(response))
              throw new ServiceException("register failed: " + response.getMsg());
          // 重新获取用户信息
          userVoResponseBean = userServiceClient.findUserByIdentifier(social, IdentityType.PHONE_NUMBER.getValue(), tenantCode);
          if (!ResponseUtil.isSuccess(userVoResponseBean))
              throw new ServiceException(GET_USER_INFO_FAIL + userVoResponseBean.getMsg());
          userVo = userVoResponseBean.getData();
      }
      return new CustomUserDetails(userVo.getIdentifier(), userVo.getCredential(), CommonConstant.STATUS_NORMAL.equals(userVo.getStatus()), getAuthority(userVo), userVo.getTenantCode(), userVo.getId(), start, LoginTypeEnum.SMS);
  }