我正在尝试在我的项目中实现jdbcAuthentication
。问题是,当我从浏览器发出请求时它可以工作,但是当我从 postman 发出请求时它不起作用,我的意思是身份验证不会发生,甚至随机凭据也可以工作。
但是,如果我使用 inMemoryAuthentication
它对于浏览器和 Postman 来说都可以正常工作。这是我在 SecurityConfig
中的代码。
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username,password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, role from user_roles where username=?");
// This works --> auth.inMemoryAuthentication().withUser("user").password("pass").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and().csrf().disable();
}
在 postman 中,我发出一个 POST
请求。
在授权
类型中,我选择基本身份验证并输入凭据,然后将其填充到下面的授权 header 中
这些是标题
Content-Type:application/json
X-XSRF-TOKEN:{{X-CSRF-TOKEN}}
Authorization:Basic ajhsjajywshhshshsssss
如果我注释 jdbcAUthentication
部分并取消注释 inMomeryAuthentication
代码,则身份验证可以从 broswer 和 postman 进行。有人可以帮我吗,为什么会发生这种情况?我错过了什么吗?谢谢!!
最佳答案
您正在使用.authenticated()
,这意味着用户已经通过身份验证,并且您希望允许已经通过身份验证的用户(也称为“记住”)。
http.authorizeRequests().anyRequest()
.authenticated().and().httpBasic().and().csrf().disable();
但实际上,您想要做的是第一次进行身份验证,因此为此您需要将其更改为 completelyAuthenticated
http.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and().httpBasic()
.and().csrf().disable();
如果您检查AuthorizedUrl 您将找到的文档:
authenticated(): Specify that URLs are allowed by any authenticated user.
fullyAuthenticated(): Specify that URLs are allowed by users who have authenticated and were not "remembered".
关于java - Spring:当收到来自 Postman 的请求时,BasicHttp 无法与 jdbcAuthentication 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40110094/