从React向Spring REST发送授权请求



我正试图用一个用spring引导构建并配置了spring安全性的rest api来验证react应用程序。

目前,即使有正确的用户凭据,我也会遇到302错误。

"/login"是请求后身份验证信息的正确默认URL吗
此外,我是否只需要在标题中添加一个csrf令牌,并在发布请求正文中添加用户名/密码?

安全配置如下所示:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(this.userDetailsService)
.passwordEncoder(User.PASSWORD_ENCODER);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
final CookieCsrfTokenRepository tokenRepository = new CookieCsrfTokenRepository();
http
.authorizeRequests()
.antMatchers("/")
.permitAll()
.antMatchers("/api/**").authenticated()
.and()
.formLogin()
.permitAll()
.and()
.httpBasic()
.and()
.logout()
.logoutSuccessUrl("/")
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

我的帖子是这样的:

...
const data = { 
userName: this.state.userName,
password: this.state.password
};
fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'X-XSRF-TOKEN': cookies.get("XSRF-TOKEN")},
body: JSON.stringify(data),
}).then(response => {
...

提前感谢

您必须在这样的configure方法中提供login.html页面。

.formLogin()
.loginPage("/login.html").permitAll();

参考此链接

希望这能解决你的问题:(

最新更新