【问题标题】:username parameter is empty in loadUserByUsername(String username) - spring bootloadUserByUsername(String username)中的用户名参数为空 - spring boot
【发布时间】:2017-10-14 04:23:23
【问题描述】:

这是我的UserDetailService

public class StockUserDetailService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
    private static final Logger logger = Logger.getLogger(StockUserDetailService.class);
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.debug("entering loadByUserName");
        // MongoDatabase database = mongoClient.getDatabase("springsecurity");
        User user = userRepository.findOne(username);
        logger.debug("this is teh user ibzect ="+user);
        if (user == null) {
            logger.info("----------------------------------------------user name is "+username);
            throw new UsernameNotFoundException("NAT FOUND");
        }
        return user;
    }
}

但是username 参数总是以null 出现。我在 Stackoverflow 上看到很多其他有同样问题的帖子。他们中的一些人说这是因为它期望 usernamepassword 作为 HTTP 标头而不是 JSON 的一部分。

但我认为这不是真的,因为 Spring Boot 的默认登录页面只有一个简单的表单,它向 /login 发出 POST 请求。这就是我正在做的事情。

我不明白这里的问题。

PS:我已经正确配置了usernamepassword键名:

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/signup**").permitAll()
            .antMatchers("/login/**").permitAll()
            .antMatchers("/logout/**").permitAll()
            .and()
        .authorizeRequests()
            .antMatchers("/admin/**").hasAuthority("ADMIN")
            .and()
        .formLogin()
            .usernameParameter("username").
            .passwordParameter("password");
}

【问题讨论】:

  • 我很久以前就知道了,但是除了通过 application/x-www-form-urlencoded 发送之外,您能分享一下解决方案吗

标签: spring-boot login spring-security


【解决方案1】:

在您的数据库中usernameUser 实体的id? 因为如果没有,并且您只有一个名为 username 的字段,那么您必须在 UserRepository 中编写一个魔术方法,即
User findByUsername(String username); 并在您的StockUserDetailService 中使用它来从数据库中检索用户。 findOne() 方法需要 id 作为参数,在您的情况下,它与 id 没有任何关系。

【讨论】:

  • 用户名用“@Id”注释。问题不在于数据库找到它。 “用户名”本身是空的。
  • 问题可能出在您的configuremethod 的链顺序上。请尝试以下顺序:http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll() .and() .csrf() .disable();
  • 试过了。用户名仍然为空
【解决方案2】:

您将usernamepassword 参数作为JSON 发送(内容类型application/json),但您必须发送URL 编码参数(内容类型application/x-www-form-urlencoded),请参阅Spring Security Reference

4 用户名必须作为名为 username 的 HTTP 参数出现

5密码必须以名为password的HTTP参数的形式出现

【讨论】:

  • 这是我的确切问题,使用 json 在邮递员上运行 post 请求
猜你喜欢
  • 2012-07-08
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
  • 2017-11-02
  • 1970-01-01
相关资源
最近更新 更多