Error: 400 Bad request.
I have no razor pages like layout.cshtml, angular app is running seprate and .net core api running seperate. having an issue with anti forgery tokens.
followed below instructions none of the worked. Anti forgery with token API and angular
How to validate AntiForgeryToken issued from one Application on different Application in .NetCore API? https://www.dotnetcurry.com/aspnet/1343/aspnet-core-csrf-antiforgery-token .net Core 2.0 web api 400 error using Validateantiforgerytoken
tried:
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
app.Use(async (context, next) =>
{
string path = context.Request.Path.Value;
if (path != null && path.ToLower().Contains("/api"))
{
// XSRF-TOKEN used by angular in the $http if provided
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN",
tokens.RequestToken, new CookieOptions
{
HttpOnly = false,
Secure = false
}
); ;
}
await next();
});
The above links shows only the angular app running inside layout.cshtml. In the angular request added XSRF token
@Injectable()
export class XsrfInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {}
private actions: string[] = ["POST", "PUT", "DELETE"];
private forbiddenActions: string[] = ["HEAD", "OPTIONS"];
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = this.tokenExtractor.getToken();
let permitted = this.findByActionName(request.method, this.actions);
let forbidden = this.findByActionName(request.method, this.forbiddenActions);;
if (permitted !== undefined && forbidden === undefined && token !== null) {
request = request.clone({ setHeaders: { "X-XSRF-TOKEN": token } });
}
return next.handle(request);
}
private findByActionName(name: string, actions: string[]): string {
return actions.find(action => action.toLocaleLowerCase() === name.toLocaleLowerCase());
}
}
Request Header