我正在try 将我的身份验证内容迁移到Core 2.0,但在使用我自己的身份验证方案时遇到了问题.我在startup中的服务设置如下所示:
var authenticationBuilder = services.AddAuthentication(options =>
{
options.AddScheme("myauth", builder =>
{
builder.HandlerType = typeof(CookieAuthenticationHandler);
});
})
.AddCookie();
我在控制器中的登录代码如下所示:
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);
但当我在控制器或动作过滤器中时,我只有一个身份,而不是经过身份验证的身份:
var identity = context.HttpContext.User.Identities.SingleOrDefault(x => x.AuthenticationType == "myauth");
应对这些变化一直很困难,但我猜我正在这样做.我错了.有什么建议吗?
编辑:这里(本质上)有一个干净的应用程序,不会在用户身上产生两组身份.身份:
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");
}
}
}
和启动:
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?}");
});
}
}
}