Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

What is the correct implementation of middleware that validates a custom XSRF-TOKEN?

$
0
0

I had no luck getting asp `antiforgery` token working in my [angular app][1]. I am using `JWT` and I found thispost which suggests a workaround to avoid CSRF attacks. so I included `xsrfToken` in my `JWT` which get stored in a secured cookie and upon login I store the same `xsrfToken` given value in `localStorage`. now I want to compare both values at each `HttpRequest` and invalidate the request in case those values don't match. I wrote the following middleware, My first time to write one, and it is not working correctly, I can't figure out what I am doing wrong.

I checked my header and my `JWT` cookie and both contain `xsrfToken` value.

this is my implementation,

public class ValidateXSRFToken
{
private readonly RequestDelegate next;
public ValidateXSRFToken(RequestDelegate next)
{
this.next = next;
}
public Task Invoke(HttpContext context, TokenValidatedContext tokenContext)
{
string requestedXSRFHeader = context.Request.Headers["X-XSRF-TOKEN"];
var userPrincipal = tokenContext.Principal;
var XSRFClaimValue = userPrincipal.Claims.Where(c => c.Type == "xsrfToken").Single().Value;
if (requestedXSRFHeader != XSRFClaimValue)
{
throw new Exception("Invalid token");
}
return next(context);
}

}

and in my startup `configure` method I initialize it,

app.UseMiddleware<ValidateXSRFToken>();


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>