I'm working on an angular 2
app using a ASP.Net MVC
backend. For this, the index.cshtml
has included @Html.AntiForgeryToken();
so i get back a hidden input element with the Token as its value. In my frontend i can grab this token and use it for my requests. So far so good.
Now since user information is used to generate the token in the backend, i have to switch out the token on some occassions. The problem is described here in this question.
Now since i don't want to do a full page reload in my app i have to use a workaround. For this i created a partial view in the backend which just hands out this input using @Html.AntiForgeryToken();
as ActionResult
with a simple method like this:
public ActionResult GetAntiForgery()
{
return PartialView("~/Views/Home/AntiForgery.cshtml");
}
After login / logout i call this function from my frontend and replace the value of my existing AntiForgery input element
like this:
getAntiForgery(url:string) {
return this._http.get(url)
.map((response:any) => {
let originalXsrfElement = <HTMLInputElement>document.querySelector('[name=__RequestVerificationToken]');
let body = response._body;
if(body) {
let helperElem = document.createElement('div');
helperElem.innerHTML = body;
let helperInputElem = <HTMLInputElement>helperElem.firstChild;
originalXsrfElement.value = helperInputElem.value;
}
return response;
});
}
I can't even tell you what bugs me the most. I hate to make an extra request (but lets not dive into this here) but way more terrible for me is that i have to request something, get an html string back and have to extract the token string out of it.
If i were the backend guy, i would kill the frontend guy (me..) for even thinking about creating an extra partial view, creating an extra method and always doing two requests on login/logout instead of one.
Is there a better way? For example i would like to call a method which just hands out a JSON
with the proper token instead of an HTML snippet
. Even better, on existing JsonResult
methods in the backend, i would like to add the new CSRF Token
as a property.
I'm not a backend architect so there might be some stuff wrong in general how i do this, but my backend colleagues don't mind what i'm doing there so it shouldn't be so far off.
Any hints are appreciated.