net*_*ser 20 cookies csrf-protection x-xsrf-token angular
在角度文档中,提到angular httpclient将自动XSRF-TOKEN在X-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,则跳过添加标题.
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.
if (req.method === 'GET' || req.method === 'HEAD' || lcUrl.startsWith('http://') ||
lcUrl.startsWith('https://')) {
return next.handle(req);
}
const token = this.tokenService.getToken();
// Be careful not to overwrite an existing header of the same name.
if (token !== null && !req.headers.has(this.headerName)) {
req = req.clone({headers: req.headers.set(this.headerName, token)});
}
return next.handle(req);
}
Run Code Online (Sandbox Code Playgroud)
我不确定为什么他们跳过了http/s部分.这是我在github中的问题
Mir*_*nas 47
你在寻找什么HttpClientXsrfModule.
请在此处阅读更多相关信息:https://angular.io/api/common/http/HttpClientXsrfModule.
你的用法应该是这样的:
imports: [
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'My-Xsrf-Cookie', // this is optional
headerName: 'My-Xsrf-Header' // this is optional
})
]
Run Code Online (Sandbox Code Playgroud)
此外,如果您的代码通过绝对URL定位API,则默认的CSRF拦截器不会开箱即用.相反,你必须实现自己的拦截器,它不会忽略绝对路径.
@Injectable()
export class HttpXsrfInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(headerName, token) });
}
return next.handle(req);
}
}
Run Code Online (Sandbox Code Playgroud)
最后将其添加到您的提供商:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpXsrfInterceptor, multi: true }
]
Run Code Online (Sandbox Code Playgroud)
我想正确的方法是withOptions.我使用withConfig并得到错误Property 'withConfig' does not exist on type 'typeof HttpClientXsrfModule'.这是文档中的输入问题.您需要使用"withOptions"HttpClientXsrfModule.withOptions({
cookieName: 'My-Xsrf-Cookie',
headerName: 'My-Xsrf-Header',
})
| 归档时间: |
|
| 查看次数: |
12305 次 |
| 最近记录: |