Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

AntiForgeryValidation attribute seems to conflict with CookieAuthenticationEvents OnRedirectToLogin event handler #1009

@imranbaloch

Description

@imranbaloch

Reposting from https://forums.asp.net/t/2101587.aspx,

From Vincent H,

Hi,

My app is based on the SDK: 1.0.0-preview2-003121 and uses a combination of MVC, Web API and AngularJs (v1)

When making API calls, I want to return a 401 unauthorized when the cookie based session has expired. I have adjusted the "Startup.cs" to include an "OnRedirectToLogin" event handler so that API calls can be intercepted to return 401.

However when the API controller is decorated with the "[ValidateAntiForgeryToken]", the cookie authentication event is never fired and a 400 bad request is returned instead.

Can someone assist me?

Here is my "Startup.cs" > "ConfigureServices" code:

services.AddIdentity<ApplicationUser, ApplicationRole>(config => { config.User.RequireUniqueEmail = true; config.Password.RequiredLength = 8; config.Cookies.ApplicationCookie.CookieSecure = CookieSecurePolicy.SameAsRequest; config.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromMinutes(5); config.Cookies.ApplicationCookie.LoginPath = "/account/login"; config.Cookies.ApplicationCookie.LogoutPath = "/account/logout"; config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents { OnRedirectToLogin = ctx => { if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == (int)HttpStatusCode.OK) { ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.FromResult(ctx.RedirectUri); } else { ctx.Response.Redirect(ctx.RedirectUri); } return Task.FromResult(0); } }; }); 

And this is the "Startup.cs" > "Configure" code for the AntiForgeryValidation support:

app.UseIdentity(); app.Use(next => context => { if (context.Request.Path.Value.ToLower().Equals("/") || context.Request.Path.Value.ToLower().StartsWith("/home")) { var tokens = antiforgery.GetAndStoreTokens(context); context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false }); } return next(context); }); 

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions