Getting multiple Antiforgery tokens in the cookie.
Is this a Bug or Feature request?:
Bug.
Steps to reproduce (preferably a link to a GitHub repo with a repro project):
I use JWT Tokens authentication and have the following code in my Startup.cs.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
}
app.UseAuthentication();
app.UseMiddleware<AntiForgeryMiddleware>("XSRF-TOKEN");
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseJwtTokenMiddleware();
app.UseSpaStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
spa.UseSpaPrerendering(options =>
{
options.BootModulePath = $"{spa.Options.SourcePath}/dist/server/main.js";
options.BootModuleBuilder = env.IsDevelopment()
? new AngularCliBuilder(npmScript: "build:ssr")
: null;
options.ExcludeUrls = new[] { "/sockjs-node" };
});
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
app.UseMiddleware<AntiForgeryMiddleware>("XSRF-TOKEN");
}
}
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseAntiforgeryTokenMiddleware(this IApplicationBuilder builder, string requestTokenCookieName)
{
return builder.UseMiddleware<AntiForgeryMiddleware>(requestTokenCookieName);
}
}
public class AntiForgeryMiddleware
{
private readonly RequestDelegate next;
private readonly string requestTokenCookieName;
private readonly string[] httpVerbs = new string[] { "GET", "HEAD", "OPTIONS", "TRACE" };
public AntiForgeryMiddleware(RequestDelegate next, string requestTokenCookieName)
{
this.next = next;
this.requestTokenCookieName = requestTokenCookieName;
}
public async Task Invoke(HttpContext context, IAntiforgery antiforgery)
{
if (httpVerbs.Contains(context.Request.Method, StringComparer.OrdinalIgnoreCase))
{
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append(requestTokenCookieName, tokens.RequestToken, new CookieOptions()
{
HttpOnly = false
});
}
await next.Invoke(context);
}
Description of the problem:
I am getting 2 antiforgery tokens in my cookie: "XSRF-TOKEN", and ".AspNetCore.Antiforgery.OnvOIX6Mzn8", with different values. It may be the reason (though I'm not sure) why I'm getting the following error: "AntiforgeryValidationException: The provided anti forgery token was meant for a different claims-based user than the current user"
Version of Microsoft.AspNetCore.Mvc or Microsoft.AspNetCore.App or Microsoft.AspNetCore.All:
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="2.1.0" />
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="2.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0" PrivateAssets="All" />
Thanks for contacting us, @jonasarcangel. @javiercn can you please look into this? Thanks! /cc @Tratcher
Thanks for contacting us. @jonasarcangel can you provide more details on what you are trying to accomplish here? (Why do you plug in the anti forgery middleware and the code for the action/page you are invoking)
Hi. We're closing this issue as no response or updates have been provided in a timely manner and we have been unable to reproduce it. If you have more details and are encountering this issue please add a new reply and re-open the issue.
Hi. Sorry for the late reply.
I have a Prerendered SPA in Angular, and I am converting the ASP.Net Identity Razor pages to Angular. I need to have the Antiforgery Token passed through API requests instead of inserting them in the Razor page.
/cc @javiercn
@jonasarcangel I don't think the scenario you are trying to implement is something we support in Identity out of the box. My general recommendation would be that you switch from using cookies in identity to use JWT and that you use JWT Bearer on your API endpoints for the Identity APIs.
Does that make sense?
You shouldn't need to use the antiforgery middleware either in your app. Most likely what's happening is that you are using both, Antiforgery on MVC and the Antiforgery middleware. My recommendation is that you avoid antiforgery at all if possible if all you are building is a SPA.
My recommendation is that you avoid antiforgery at all if possible if all you are building is a SPA.
And use bearer tokens instead, you mean, right?
@brockallen Yep.
Thank you.
If that's the case then I'll leave it at that.
I'll do further research/test if my app is exploitable using CSRF.
On Tue, Aug 14, 2018 at 10:33 AM, Javier Calvarro Nelson < [email protected]> wrote:
@brockallen https://github.com/brockallen Yep.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/aspnet/Mvc/issues/8082#issuecomment-412712590, or mute the thread https://github.com/notifications/unsubscribe-auth/ARtmV-UE66PgstImhu6_ykY-HIfdiWjrks5uQhrdgaJpZM4VPlzU .
Closing this issue as there's no more action to be taken here.