reactjs - 从 React 向 Spring REST 发送授权请求
问题描述
我正在尝试使用使用 spring boot 构建并配置了 spring security 的 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 => {
...
提前致谢
解决方案
您必须像这样在配置方法中提供 login.html 页面。
.formLogin()
.loginPage("/login.html").permitAll();
参考这个链接
希望这能解决你的问题:)
推荐阅读
- css - 如何使 pkgdown 代码块具有深色背景?
- javascript - 如何在 Puppeteer 中尽快获取文档响应并运行 javascript?
- sql - 如何提取double的小数位数
- python - Python Beautifulsoup 网页抓取脚本
- python - 我如何在没有继承的情况下一起使用多个类?
- ruby-on-rails - “可评论”多态关联如何在“用户”模型本身上起作用?
- python - 如何测量为使用 pynput 而按住鼠标单击的时间量?
- c# - XAML 中的 Xamarin.Forms ListView AutoHeight
- php - 如何在mysql数据库中记录这个值?
- chart.js - 如何在混合图表中仅在选定图表上显示数据值?(图表JS)