ASP.Net核心Cookie身份验证重定向到登录

时间:2018-03-12 01:21:23

标签: c# authentication cookies asp.net-core asp.net-core-2.0

我正在尝试使用Cookie设置身份验证,但SignInAsync似乎无效。

我的签名方法至少目前是这样的:

[HttpPost]
public async Task<IActionResult> Login(string username, string password)
{
    if (username != "foo" || password != "bar")
    {
        return View();
    }

    //Sign in
    var claims = new List<Claim>
    {
        new Claim("name", "admin")
    };

    var userIdentity = new ClaimsIdentity(claims, "login");
    ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
    await HttpContext.SignInAsync(principal);

    //Redirect
    return RedirectToAction("home");
}

Home是具有Authorize属性的操作。 如果我提供了正确的用户名和密码,我可以跳过SignInAsync电话,看似没有异常。但是,在重定向时,我最终返回登录页面,因为我还没有登录。

Startup.cs列在下面:

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/admin/login/";
            });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=home}/{action=index}/{id?}");
        });
        app.UseAuthentication();
    }
}

我缺少什么或如何调试/获取有关出错的更多信息?

1 个答案:

答案 0 :(得分:1)

根据Tratcher的评论,请在app.UseAuthentication();之前使用app.UseMvc();