我正在尝试使用spring security csrf针对我的Web服务发出HttpPost。

首先,我试图通过GET请求恢复XSRF令牌,像这样

public static CookieManager xcsrfToken() throws IOException{
    String token;
    URL url = new URL(urlBase);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    CookieManager cookieManager = new CookieManager();
    con.connect();

    List<String> cookieHeader = con.getHeaderFields().get("Set-Cookie");

    if (cookieHeader != null) {
        for (String cookie : cookieHeader) {
            cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
        }
    }
    System.out.println(con.getHeaderFields());
    con.disconnect();

    return cookieManager;
}


这就是我从con.getHeaderFields()获得的内容

{null=[HTTP/1.1 200 OK], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Content-Language=[pt-BR], Content-Length=[973], Content-Type=[text/html;charset=ISO-8859-1], Date=[Wed, 19 Aug 2015 10:40:18 GMT], Expires=[0], Pragma=[no-cache], Server=[Apache-Coyote/1.1], Set-Cookie=[JSESSIONID=6C9326FBEEA14752068720006F2B5EAA; Path=/webapi/; HttpOnly, XSRF-TOKEN=07cbed7f-834e-4146-8537-0a6b5669f223; Path=/], X-Android-Received-Millis=[1439980819720], X-Android-Response-Source=[NETWORK 200], X-Android-Sent-Millis=[1439980819693], X-Content-Type-Options=[nosniff], X-Frame-Options=[DENY], X-XSS-Protection=[1; mode=block]}


XSRF-TOKEN在我的cookie中,好!
如果我打印然后
System.out.println(cookieManager.getCookieStore()。getCookies());
我懂了

[JSESSIONID=5B1D3E2D3E7B3E1E6572A3839BFF3741, XSRF-TOKEN=4d4048bd-f21c-48c6-895e-5f67523ad963]


现在,我试图像这样对服务器发出POST

public static HttpURLConnection makeRequest(String metodo, String uri, String requestBody) throws IOException{
    URL url = new URL(urlBase + uri);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");

    con.setDoInput(true);
    con.setDoOutput(!metodo.equals("GET"));
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Cookie", TextUtils.join("," , xcsrfToken().getCookieStore().getCookies()));

    con.connect();

    InputStream is = con.getErrorStream();
    System.out.println(IOUtils.toString(is, "UTF-8"));

    System.out.println(con.getHeaderFields());

    return con;
}


但是标题没有饼干就回来了

 {null=[HTTP/1.1 403 Forbidden], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Content-Language=[en], Content-Length=[1149], Content-Type=[text/html;charset=utf-8], Date=[Wed, 19 Aug 2015 10:42:18 GMT], Expires=[0], Pragma=[no-cache], Server=[Apache-Coyote/1.1], X-Android-Received-Millis=[1439980939827], X-Android-Response-Source=[NETWORK 403], X-Android-Sent-Millis=[1439980939811], X-Content-Type-Options=[nosniff], X-Frame-Options=[DENY], X-XSS-Protection=[1; mode=block]}


它说没有CSRF有效令牌

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.


在我的Web服务中,由于angularJs,令牌已配置为重命名为XSRF-TOKEN。



public static void getTokens() throws IOException{
    URL url = new URL(urlBase);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.connect();
    cookieManager = new CookieManager();

    List<String> cookieHeader = con.getHeaderFields().get("Set-Cookie");

    if (cookieHeader != null) {
        for (String cookie : cookieHeader) {
            String[] tokens = TextUtils.split(cookie, "=");
            if (tokens[0].equals("JSESSIONID"))
                cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
            if (tokens[0].equals("XSRF-TOKEN")) {
                String[] tokenValue = TextUtils.split(tokens[1],";");
                xsrfTOKEN = tokenValue[0];
            }
        }
    }

    con.disconnect();
}


然后,将其附加到HttpUrlConnection

con.setRequestProperty("X-XSRF-TOKEN", xsrfTOKEN);

最佳答案

以我的经验,我们需要将令牌作为请求标头提交。 Spring希望其名称默认为X-CSRF-TOKEN。但是使用AngularJS的人通常在Spring Security配置中将其更改为X-XSRF-TOKEN

但是看看您的代码,我不知道您是否正在发送该标头。

如果有帮助,请参考我的一个项目(使用RestAssured)的摘录:

if (xsrfToken != null && !ctx.getRequestMethod().equals(Method.GET))
    requestSpec.header("X-XSRF-TOKEN", xsrfToken);

关于android - Android HttpUrlConnection无法发布-错误403,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32093340/

10-12 04:47