I am trying to port my auth file to Core 2.0 and am having a problem using my own authentication scheme. My service setup at startup is as follows:
var authenticationBuilder = services.AddAuthentication(options => { options.AddScheme("myauth", builder => { builder.HandlerType = typeof(CookieAuthenticationHandler); }); }) .AddCookie();
My controller login code is as follows:
var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.Name) }; var props = new AuthenticationProperties { IsPersistent = persistCookie, ExpiresUtc = DateTime.UtcNow.AddYears(1) }; var id = new ClaimsIdentity(claims); await HttpContext.SignInAsync("myauth", new ClaimsPrincipal(id), props);
But when I am in the controller or action filter, I have only one identity, and it is not authenticated:
var identity = context.HttpContext.User.Identities.SingleOrDefault(x => x.AuthenticationType == "myauth");
Navigating these changes was difficult, but I assume that I am doing .AddScheme incorrectly. Any suggestions?
EDIT: Here (essentially) is a clean application that outputs not two sets of identifiers in User.Identies:
namespace WebApplication1.Controllers { public class Testy : Controller { public IActionResult Index() { var i = HttpContext.User.Identities; return Content("index"); } public async Task<IActionResult> In1() { var claims = new List<Claim> { new Claim(ClaimTypes.Name, "In1 name") }; var props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddYears(1) }; var id = new ClaimsIdentity(claims); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id), props); return Content("In1"); } public async Task<IActionResult> In2() { var claims = new List<Claim> { new Claim(ClaimTypes.Name, "a2 name") }; var props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddYears(1) }; var id = new ClaimsIdentity(claims); await HttpContext.SignInAsync("a2", new ClaimsPrincipal(id), props); return Content("In2"); } public async Task<IActionResult> Out1() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Content("Out1"); } public async Task<IActionResult> Out2() { await HttpContext.SignOutAsync("a2"); return Content("Out2"); } } }
And launch:
namespace WebApplication1 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie("a2"); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }