loadUserByUsername(String username) 中的 username 参数为空 - spring boot [英] username parameter is empty in loadUserByUsername(String username) - spring boot
问题描述
这是我的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 上看到了很多其他帖子也有同样的问题.他们中的一些人说这是因为它期望 username
和 password
作为 HTTP 标头的一部分而不是 JSON.
But the username
argument always comes as null
. I saw tons of other posts on Stackoverflow with the same problem. Some of them say that it is because it expects the username
and password
as part of HTTP headers rather than a JSON.
但我不认为这是真的,因为 Spring Boot 的默认登录页面只有一个简单的表单,它向 /login
发出 POST
请求.这就是我正在做的事情.
But I don't think that is true because Spring Boot's default login page just has a simple form which does a POST
request to /login
. Which is what I am doing.
我不明白这里的问题.
PS:我已经正确配置了username
和password
键名:
PS: I have configured by username
and password
key names properly:
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");
}
推荐答案
您将 username
和 password
参数作为 JSON 发送(内容类型 application/json
code>),但您必须发送 URL 编码的参数(内容类型 application/x-www-form-urlencoded
),请参阅 Spring 安全参考:
You send username
and password
parameter as JSON (content type application/json
), but you have to send URL-encoded parameters (content type application/x-www-form-urlencoded
), see Spring Security Reference:
4 用户名必须作为名为 username 的 HTTP 参数存在
4 The username must be present as the HTTP parameter named username
5 密码必须作为名为 password 的 HTTP 参数存在
5 The password must be present as the HTTP parameter named password
这篇关于loadUserByUsername(String username) 中的 username 参数为空 - spring boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!