标签: x-xsrf-token

angular4 httpclient csrf不发送x-xsrf-token

在角度文档中,提到angular httpclient将自动XSRF-TOKENX-XSRF-TOKENpost请求的标题中发送cookie的值.文档链接

但它并没有为我发送标题.这是我的代码

Nodejs用于设置cookie的代码

router.get('/set-csrf',function(req,res,next){
    res.setHeader('Set-Cookie', "XSRF-TOKEN=abc;Path=/; HttpOnly; SameSite=Strict");    
    res.send();
  })
Run Code Online (Sandbox Code Playgroud)

我在app.module.ts中使用了httpclient

imports: [
  HttpClientModule
]
Run Code Online (Sandbox Code Playgroud)

**以上代码仅用于调试目的.我没有set-csrf端点.

但是当我发送帖子请求时它不会发送任何标题.我无法调试.

我已经在angular的github存储库中添加了这个问题.HttpXsrfInterceptor检查请求是GET还是HEAD,或者是否以http开头.如果为true,则跳过添加标题.

这是HttpXsrfInterceptor类中的代码

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const lcUrl = req.url.toLowerCase();
    // Skip both non-mutating requests and absolute URLs.
    // Non-mutating requests don't require a token, and absolute URLs require special handling
    // anyway as the cookie set
    // on our origin is not the same as the token expected by another origin. …
Run Code Online (Sandbox Code Playgroud)

cookies csrf-protection x-xsrf-token angular

20
推荐指数
2
解决办法
1万
查看次数

Angular 6不会将X-XSRF-TOKEN标头添加到http请求

我已经阅读关于SO 的文档和所有相关问题,但是Angular的XSRF机制仍然不适合我:我绝不能自动附加X-XSRF-TOKEN标头发出POST请求.

我有一个带登录表单的Angular 6应用程序.

它是Symfony(PHP 7.1)网站的一部分,Angular应用程序页面,当从Symfony提供时,发送正确的Cookie(XSRF-TOKEN):

在此输入图像描述

我的app.module.ts包含正确的模块:

// other imports...
import {HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";

// ...
@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    NgbModule.forRoot(),
    BrowserModule,
    // ...
    HttpClientModule,
    HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-CSRF-TOKEN'
    }),
    // other imports
  ],
  providers: [],
  entryComponents: [WarningDialog],
  bootstrap: [AppComponent]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)

然后,在Service的方法中,我正在进行以下http请求(this.http是一个实例HttpClient):

this.http
    .post<any>('api/login', {'_username': username, '_pass': password})
    .subscribe(/* handler here */);
Run Code Online (Sandbox Code Playgroud)

post请求永远不会发送X-XSRF-TOKEN标头.为什么?

csrf typescript x-xsrf-token angular angular6

16
推荐指数
5
解决办法
2万
查看次数

修复后,Safari 11 X-XSRF-TOKEN未更新

最近,Safari 11在Mac OSX上发布.此更新导致我们的Web应用程序与我们的reuest标头上的XSRF结合使用时出现问题.我将尝试以逻辑方式描述问题.这就是好情况的样子:

  1. 当用户想要登录时,他从服务器接收带有Set-Cookie的响应,该Set-Cookie包含XSRF令牌的值. Eg: Set-Cookie: XSRF-TOKEN=LKNBX4DZhL708KjXNkgXnlxTDCNuhsZG1kTc2SFy498; Path=/; Secure

  2. 页面刷新将执行的下一个调用包含标头中的正确XSRF值.在服务器端,检查值等.来自前端的每个调用都将包含该XSRF令牌.

  3. 如果用户注销并想再次登录,则他的XSRF cookie将被新值覆盖,并且能够使用该令牌登录.

我们的问题情况(在Mac OSX上使用Safari 11,其他浏览器不显示此行为):

  1. 如果没有cookie存在,用户可以正常登录

  2. 但是,如果他想重新登录(在上一个会话之后),则会进行刷新.在第一次调用时,刷新其调用的XSRF令牌不会被新值替换,它们仍然包含来自前一会话的旧XSRF令牌.当我们检查此请求时,我们看到此请求中的cookie包含正确的值,但标头反映了旧令牌.

  3. 使用错误标题的此调用会导致会话在后端关闭,因此用户将被踢出会话.TLDR; 在Safari 11中,标题XSRF-TOKEN在刷新后不会相应地更新cookie值.我们在旧版本和其他浏览器上工作,我们认为这是一个Safar 11错误.

还有其他人遇到过类似的问题吗?在Safari 11中刷新页面后,请求的标头值是否未更新?

编辑:经过测试,我们发现在URL中放置时间戳作为查询参数会强制Safari 11发送正确的请求.似乎缓存了一些请求并忽略了更新的标头.

非常感谢!

safari header setcookie http-headers x-xsrf-token

7
推荐指数
1
解决办法
624
查看次数

Angular 5无法从HttpXsrfTokenExtractor获取XSRF令牌

我正在尝试通过绝对URL向Spring(基本身份验证)安全的Rest API 发出POST请求。
阅读了Angular省略了将X-XSRF-TOKEN自动插入到请求标头中以获取绝对URL的信息后,我尝试实现HttpInterceptor来添加令牌。

在我的原始/ signin POST请求中,我创建了必要的授权:基本标头,以确保Spring对请求进行身份验证。
返回的响应标头包含预期的set-cookie令牌:

Set-Cookie:XSRF-TOKEN=4e4a087b-4184-43de-81b0-e37ef953d755; Path=/

但是,在我的自定义拦截器类中,当我尝试从注入的HttpXsrfTokenExtractor中获取下一个请求的令牌时,它返回null

这是我的拦截器类的代码:

import {Injectable, Inject} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import {HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, 
HttpEvent} from '@angular/common/http';


@Injectable()
export class HttpXsrfInterceptor implements HttpInterceptor {

   constructor(private tokenExtractor: HttpXsrfTokenExtractor) {}

   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

     let requestMethod: string = req.method;
     requestMethod = requestMethod.toLowerCase();

     if (requestMethod && (requestMethod === 'post' || requestMethod === …
Run Code Online (Sandbox Code Playgroud)

csrf spring-security webpack-dev-server x-xsrf-token angular5

7
推荐指数
1
解决办法
3711
查看次数

如何将 CSRF Token 设置为不同的上下文路径

我们基于 Angular 的 web 应用程序与在不同域和上下文路径上运行的企业门户集成。我正在使用基于 Spring Security 的 CSRF 令牌来验证传入的请求。该应用程序在本地运行良好,但是当我将它与门户集成时,所有的 post 调用都失败了 403,因为 Angular 无法读取 XSRF-Token 并将请求标头中的 X-XSRF-Token 设置为 API 调用。经过调查,我发现门户和我们的应用程序的上下文路径不同,因此 spring 将带有路径、过期和域的 XSRF-Token 设置为 Null。当 spring 创建它时,有什么方法可以将 XSRF-Token 设置为特定的 cookie 路径?

注意:我有一个替代解决方案来创建过滤器并从请求标头中读取 cookie,并使用我想要的路径在浏览器上放置一个新的 cookie。我正在寻找配置级别的解决方案。

csrf x-xsrf-token

5
推荐指数
1
解决办法
2592
查看次数

带有 Angular 4 的 .NET CORE API - cookie 令牌和请求令牌已交换

尝试使用 Angular 和 .NET CORE 实现 XSRF 时,我不断收到此消息:“提供的防伪令牌验证失败。cookie 令牌和请求令牌已交换。” 我在 Angular 和 API 中配置了相同的 cookie 和标头名称。谁有想法?

过程

Angular 首次调用此 API 方法以检索 cookie

    [HttpGet("startSession")]
    public async Task<IActionResult> StartSession()
    {
        AntiforgeryTokenSet tokens = this.antiForgery.GetAndStoreTokens(this.HttpContext);

        this.HttpContext.Response.Cookies.Append(this.options.Value.Cookie.Name, tokens.RequestToken, new CookieOptions { HttpOnly = false });

        return this.Ok(
            new
            {
                Success = true
            });
    }
Run Code Online (Sandbox Code Playgroud)

然后 Angular 拦截下一个 POST 请求并稍微覆盖默认的 XSRF 处理,因为我需要它为 HTTPS URL 工作

    // Override default Angular XSRF handling since it won't work for         
    absolute URLs and we have to prefix with "https://" …
Run Code Online (Sandbox Code Playgroud)

asp.net-core x-xsrf-token angular

4
推荐指数
1
解决办法
1122
查看次数

将 POST 发送到自定义休息端点时 XSRF 检查失败

我有一个 ScriptRunner 片段,它显示一个表单对话框。这是代码:

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.transform.BaseScript

import javax.ws.rs.core.MediaType
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

@BaseScript CustomEndpointDelegate delegate

showCloneEazyBIAccounts() { MultivaluedMap queryParams ->

def dialog =
    """<section role="dialog" id="sr-dialog" class="aui-layer aui-dialog2 aui-dialog2-medium" aria-hidden="true" data-aui-remove-on-hide="true">
        <header class="aui-dialog2-header">
            <h2 class="aui-dialog2-header-main">Clone EazyBI Accounts by Model</h2>
            <a class="aui-dialog2-header-close">
                <span class="aui-icon aui-icon-small aui-iconfont-close-dialog">Close</span>
            </a>
        </header>
        <div class="aui-dialog2-content">
            <form class="aui" action="/rest/scriptrunner/latest/custom/cloneJE2Cube" method="post">
                <div class="field-group">
                    <label for="accountNames">Account Names <span class="aui-icon icon-required"></span></label>
                    <input class="text medium-field" type="text"id="accountNames" name="accountNames" placeholder="Cubo 1, Cubo 2...">
                </div>
                <div class="field-group">
                    <label for="projectKeys">Project Keys <span class="aui-icon icon-required"></span></label> …
Run Code Online (Sandbox Code Playgroud)

html forms endpoint jira-plugin x-xsrf-token

4
推荐指数
1
解决办法
1万
查看次数

带有 axios 的 X-XSRF-TOKEN 标头

X-XSRF-TOKEN如果我设置了XSRF-TOKENcookie 服务器端,我是否必须设置任何东西来发送标头?

https://github.com/axios/axios/blob/master/lib/defaults.js#L74 https://github.com/axios/axios/blob/master/dist/axios.js#L1072

它读起来好像我没有,但我没有看到有人出去。

我要补充一点,我已设置withCredentials为 true,因此我确实遇到了 OR 中的第一次检查:

var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ?
            cookies.read(config.xsrfCookieName) :
            undefined;

          if (xsrfValue) {
            requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
Run Code Online (Sandbox Code Playgroud)

所以如果config.xsrfCookieName是默认.....

更新:

所以,我的OPTIONS预检CORS工作和POST现在一样,但没有X-XSRF-TOKEN被发送。

  methods: {
    onSubmit(e) {
      this.axios
        .post(
          e.target.action,
          { data: this.form },
          {
            withCredentials: true,
            xsrfCookieName: "XSRF-TOKEN",
            xsrfHeaderName: "X-XSRF-TOKEN"
          }
        )
        .then(res => {
          console.log(res)
        })
        .catch(err => {
          this.errors.push(err)
        })
    }
  }
Run Code Online (Sandbox Code Playgroud)

谢谢。

csrf axios x-xsrf-token

3
推荐指数
1
解决办法
1万
查看次数

如何在angular4中发送带有响应头的“ X-CSRF-TOKEN”

我目前正在使用Angular4应用程序。现在,我要实现XSRF保护。在Response标头Cookie中,我得到“ XSRF-TOKEN”,并且需要在下一个Request标头Cookie中发送“ X-XSRF-TOKEN”。如Angular官方文档中所述,Angular正在处理此问题。但是就我而言,angular并没有处理它。因此,我创建了以下自定义XsrfInterceptor,以将“ X-XSRF-TOKEN”附加到响应头。

import { NgModule, Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { HttpRequest, HttpHandler, HttpEvent, HttpXsrfTokenExtractor, HttpInterceptor } from "@angular/common/http";

@Injectable()
export class XsrfInterceptor implements HttpInterceptor {

    constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const headerName = 'X-XSRF-TOKEN';
        console.log("xsrf intercepter called");
        let requestToForward = req;
        let token = this.tokenExtractor.getToken() as string;
        console.log(token);
        if (token !== null) {
            requestToForward = req.clone({ setHeaders: {headerName: token } });
        }
        return …
Run Code Online (Sandbox Code Playgroud)

cookies interceptor csrf-protection x-xsrf-token angular

2
推荐指数
1
解决办法
4840
查看次数

Spring 何时发回 XSRF-TOKEN set-cookie 响应标头?

标题很好地总结了这一切。我要求应满足的条件,以便 Spring 决定发回Set-Cookie:XSRF-TOKEN=...响应标头。

我可以看到我的很多请求都收到带有此类标头的响应,而实际上不需要它。例如,当我发送 GET 请求时,即使我已经X-XSRF-TOKEN为请求设置了 ,它也会收到带有该标头集的响应。但是对于具有上述请求标头的 POST 请求,Spring 将阻止发回 set-cookie 标头。所以我想知道应该满足什么条件,Spring 才会决定发回一个。

spring csrf spring-security x-xsrf-token

2
推荐指数
1
解决办法
3209
查看次数