【问题标题】:React, SpringBoot and CSRFReact、SpringBoot 和 CSRF
【发布时间】:2020-02-20 02:56:58
【问题描述】:

我正在使用 Spring Boot 安全性:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

我已禁用 CSRF:

@Slf4j
@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.csrf().disable();

    }
}

使用npm start,我在我的 React 应用程序中运行以下代码:

         axios
            .post(this.state.targetUrl+'/mpbpm/triggerProcess', {
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS'
                }
            })

结果是:

Failed to load http://localhost:8080/mpbpm/triggerProcess: Response for preflight has invalid HTTP status code 401.

为什么失败了?我正在尝试学习 React,我有试图从服务器检索值的虚拟代码。最简单的方法是什么?

【问题讨论】:

    标签: reactjs spring spring-security axios csrf


    【解决方案1】:

    这里:

             axios
                .post(this.state.targetUrl+'/mpbpm/triggerProcess', {
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                        'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS'
                    }
                })
    

    您正在添加自定义标头并发送触发预检请求的跨域提取。服务器没有为这种流量做好准备,一切都会导致错误。删除那些标题。

    【讨论】:

    • 感谢您的回复。我已将其更改为:axios.post(this.state.targetUrl+'/mpbpm/triggerProcess') 现在错误为:Failed to load http://localhost:8080/mpbpm/triggerProcess: Redirect from 'http://localhost:8080/mpbpm/triggerProcess' to 'http://localhost:8080/login' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3002' is therefore not allowed access.
    • 这是一个 CORS 问题,我通过将 @CrossOrigin 添加到我的端点并删除 Spring Security 依赖项来解决该问题。将您的答案标记为正确,因为它解决了最初的问题。再次感谢
    猜你喜欢
    • 2019-06-18
    • 2018-04-30
    • 2020-04-11
    • 2020-09-21
    • 2018-11-17
    • 2018-02-06
    • 1970-01-01
    • 2019-03-02
    • 2022-12-15
    相关资源
    最近更新 更多