【问题标题】:Protecting against CSRF attacks in Aurelia在 Aurelia 中防御 CSRF 攻击
【发布时间】:2015-10-02 16:07:37
【问题描述】:

在 Aurelia 中,似乎还没有任何对 CSRF 保护的支持,这与 AngularJS 的 XSRF-TOKEN 标头相反,AngularJS 框架会在所有 XHR 请求上自动设置。

我应该如何保护 Aurelia 应用免受 CSRF 攻击?我应该基于OWASP CSRF Prevention Cheat Sheet 推出自己的支持,还是已经有任何替代 Aurelia 的方法?

【问题讨论】:

  • 使用 modsecurity。它是 apache 或 nginx 的一个模块,或者可以充当反向代理。它内置了反 CSRF。或者使用 cloudflare 之类的东西

标签: javascript security csrf csrf-protection aurelia


【解决方案1】:

使用 Aurelia 的 HTTP interceptors(请参阅 examples in the docs),您应该可以相当轻松地自己完成此操作。在每次请求之前,您都可以发送您的令牌。这可以通过传统的aurelia-http-client 和新的标准aurelia-fetch-client 来完成。

您的代码可能如下所示:

export class MyRestAPI {
    static inject () { return [HttpClient]; } // This could easily be fetch-client

    constructor (http) {
        this.http = http.configure(x => {
            x.withBaseUrl(myBaseUrl);
            x.useStandardConfiguration();
            x.withInterceptor({
                request: function (request) {
                    request.headers.set('XSRF-TOKEN', myAwesomeToken);
                    return request;
                }
            });
        });
    }

    ...

}

在每次请求时,都会发送您的令牌。您必须在服务器端处理验证。您可以轻松设置代码,以便您的初始请求可以获取令牌,或者您可以将令牌作为身份验证有效负载的一部分传回,或者如果您愿意,您甚至可以将令牌存储在浏览器的本地存储中并使用它方式。

您甚至可以更进一步,实现 JWT 身份验证。如果您使用的是 node.js,我有一个小的 blog post,它描述了我如何在 Express 中实现 JWT。 Github 上有一个名为 aurelia-auth 的插件来处理 JWT,还有一个 blog post on its implementation on the Aurelia blog as well

【讨论】:

    【解决方案2】:

    这是一个示例拦截器,它从响应标头中读取令牌(如果存在)并在每个需要它的请求上自动设置它。

    import {Interceptor, HttpResponseMessage, RequestMessage} from "aurelia-http-client";
    
    class CsrfHeaderInterceptor implements Interceptor {
      private static readonly TOKEN_HEADER = 'X-CSRF-Token';
    
      private latestCsrfToken: string;
    
      response(response: HttpResponseMessage): HttpResponseMessage {
        if (response.headers.has(CsrfHeaderInterceptor.TOKEN_HEADER)) {
          this.latestCsrfToken = response.headers.get(CsrfHeaderInterceptor.TOKEN_HEADER);
        }
        return response;
      }
    
      request(request: RequestMessage): RequestMessage {
        if (this.latestCsrfToken) {
          if (['POST', 'PUT', 'PATCH'].indexOf(request.method) >= 0) {
            request.headers.add(CsrfHeaderInterceptor.TOKEN_HEADER, this.latestCsrfToken);
          }
        }
        return request;
      }
    }
    

    您在 http/fetch 客户端中注册它,例如:

    httpClient.configure((config) => {
      config
        .withBaseUrl("/api/") // adjust to your needs
        .withHeader('Accept', 'application/json') // adjust to your needs
        .withHeader('X-Requested-With', 'XMLHttpRequest') // adjust to your needs
        .withInterceptor(new CsrfHeaderInterceptor());
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 2013-06-05
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      相关资源
      最近更新 更多