Anti-forgery validation with asp dotnet core and angular

Posted by Anuraj on Saturday, August 4, 2018 Reading time :1 minute

ASP.NET Core Angular

This post is about enabling Anti-forgery validation in single page applications using ASP.NET Core and Angular. The anti-forgery token can be used to help protect your application against cross-site request forgery. In earlier versions of ASP.NET, you had to explicitly decorate a controller or an action method to enable Anti-forgery, in ASP.NET Core Web API all the unsafe methods(PUT, POST) anti-forgery validation is enabled by default.

POST Request without Anti-forgery Token

AngularJS uses a convention to address CSRF. If the server sends a cookie with the name XSRF-TOKEN, the AngularJS $http service adds the cookie value to a header when it sends a request to the server. This process is automatic. The header doesn’t need to be set explicitly. The header name is X-XSRF-TOKEN. The server should detect this header and validate its contents.

So first you need to enable server to detect XSRF-TOKEN from Angular application as the anti-forgery token value, you can do this by modifying Startup class, ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
    services.AddDbContext<BooksApiDbContext>(options => options.UseInMemoryDatabase("BooksDb"));
    services.AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}

Now your ASP.NET Core app knows about the token which is sent along with Request as header. Next you need to set a cookie, with the token value, so that it can process the request. You can do this using adding a middleware delegate like this.

app.Use(next => context =>
{
    if (context.Request.Path.Value.IndexOf("/api", StringComparison.OrdinalIgnoreCase) != -1)
    {
        var tokens = antiforgery.GetAndStoreTokens(context);
        context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
            new CookieOptions() { HttpOnly = false });
    }

    return next(context);
});

So when a request hit ASP.NET Core Web API, server will read the Angular XSRF-TOKEN token and create and set the cookie.

Cookies created by ASP.NET Core Web API

Next any request from Angular, you will be able to see the X-XSRF-TOKEN.

Angular sending X-XSRF-TOKEN header

Happy Programming :)


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



Translate
Subscribe
BMC logoBuy me a coffee


Copyright © 2018 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub