在Aurelia中,似乎还没有任何对CSRF保护的支持,而AngularJS的XSRF-TOKEN头是由AngularJS框架在所有XHR请求上自动设置的。
我应该如何保护Aurelia应用程序免受CSRF攻击?我是否应该基于OWASP CSRF Prevention Cheat Sheet推出我自己的支持,或者已经有其他的替代方案了?
发布于 2015-10-20 08:16:37
通过使用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。
发布于 2016-11-07 05:57:51
下面是一个示例拦截器,它从响应头读取令牌(如果它存在),并在每个需要它的请求上自动设置它。
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());
});https://stackoverflow.com/questions/31399539
复制相似问题