[英]Getting exception when requesting XSRF-TOKEN using Spring RestTemplate
I'm trying to call a service which has CSRF enabled and all it's endpoints are configured to request authentication header from the user.我正在尝试调用启用了 CSRF 的服务,并且它的所有端点都配置为向用户请求身份验证标头。
I'm using Spring RestTemplate as follows:我正在使用 Spring RestTemplate,如下所示:
ResponseEntity<String> responseEntity = getRestTemplate().exchange(
"localhost:9090/",
"HEAD",
entity,
String.class);
return responseEntity.getBody();
However, I'm not able to read the Headers from the response as I'm getting HTTP 401
error.但是,由于出现
HTTP 401
错误,我无法从响应中读取标头。
My workaround is to read the token from the exception that RestTemplate throws HttpClientErrorException
.我的解决方法是从 RestTemplate 抛出的异常中读取令牌
HttpClientErrorException
。 Like this:像这样:
exception.getResponseHeaders().get("Set-Cookie");
for (String header : headers) {
if (header.startsWith("XSRF-TOKEN")) {
token = header.split("=")[1];
break;
}
}
Is there any way to get XSRF-TOKEN token with out relying on reading it from the exception?有没有办法在不依赖从异常中读取它的情况下获取 XSRF-TOKEN 令牌?
You are not getting an exception when accessing with GET method.使用 GET 方法访问时不会出现异常。 Hence, I would create a get endpoint for retrieving the token and then use it for next POST calls.
因此,我会创建一个获取令牌的端点,然后将其用于下一次 POST 调用。
Hope that approach makes sense.希望这种方法有意义。
the csrf only blocks requests of type post, put, delete... that is, the get is free, therefore in order to obtain the token, first you have to make a request to a get method and extract the token from there that you would use to the next requests. csrf 只阻止 post、put、delete 类型的请求......也就是说,get 是免费的,因此为了获得令牌,首先你必须向 get 方法发出请求并从那里提取令牌,你将用于下一个请求。 in case the token is not generated, add this to the configure of your security configuration:
如果未生成令牌,请将其添加到您的安全配置的配置中:
http.csrf (). csrfTokenRepository (CookieCrsfTokenRepository.withHttpOnlyFalse) .any () ........
XSRF-TOKEN
following spring specification is marker for header by default.遵循 spring 规范的
XSRF-TOKEN
默认是标头的标记。 So you should try get it in this way:所以你应该尝试以这种方式获取它:
List tokenList = responseEntity.getHeaders().get("XSRF-TOKEN");
This collection consist of single element as usual, so first element should be your token.该集合像往常一样由单个元素组成,因此第一个元素应该是您的标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.