Spring WebSecurityConfigurerAdapter permitAll()不允许来自c#客户端的REST POST请求?

时间:2017-06-19 20:45:53

标签: c# spring-boot

我在WebSecurityConfigurerAdapter中进行了此设置,以允许我的客户端应用程序将POST请求发送到" / commands /"服务器上的路径:

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/commands/**").permitAll()
            .antMatchers("/files/**").authenticated()
            .and().
            formLogin();
    }

GET请求很好,但是在此设置之后,POST请求似乎需要csrf。如果我不登录,我会得到以下结果:

{
    "timestamp": 1497904660159,
    "status": 403,
    "error": "Forbidden",
    "message": "Could not verify the provided CSRF token because your session was not found.",
    "path": "/commands/add"
}

如果我使用C#客户端代码登录并附加登录请求中的cookie,我将收到以下错误:

{
    "timestamp":1497897646380,
    "status":403,
    "error":"Forbidden",
    "message":"Could not verify the provided CSRF token because your session was not found.",
    "path":"/commands/add"
}

我发布的C#代码客户端如下所示:

public String SendJsonCommandByPost(String url, string data)
{
    try
    {
        WebRequest req = HttpWebRequest.Create(url);
        req.Proxy = null;
        req.Method = "POST";
        req.Timeout = TIMEOUT;
        ((HttpWebRequest)req).CookieContainer = myCookieContainer;
        PrintCookies(myCookieContainer);
        req.Headers.Add("X-CSRF-TOKEN", _csrftoken);
        req.ContentType = "application/json";
        ((HttpWebRequest)req).UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
        byte[] postdata = Encoding.UTF8.GetBytes(data);
        req.ContentLength = postdata.Length;
        Stream stream = req.GetRequestStream();
        stream.Write(postdata, 0, postdata.Length);
        stream.Flush();
        stream.Close();
        string source;

        Console.WriteLine(req.Headers);
        using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
        {
            using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
            {
                source = reader.ReadToEnd();
            }

            req.GetResponse().Close();
            return source;
        }
    }
    catch (Exception exp)
    {
        Console.WriteLine(exp);
        if (exp is WebException)
        {
            var webexp = (WebException)exp;
            Console.WriteLine(webexp.Response.Headers);
            TextReader reader = new StreamReader(webexp.Response.GetResponseStream());
            Console.WriteLine(reader.ReadToEnd());
        }
        return null;
    }
}

我可以知道可能导致此类问题的原因吗?谢谢!

1 个答案:

答案 0 :(得分:-1)

添加此行。

http.csrf()禁用();

默认情况下,csrf已启用,因此您的帖子请求会被阻止。试试这个。它对我有用