成功登录后重定向到使用Cookie授权登录页面 - AspNetCore 1.1

时间:2018-01-26 16:36:00

标签: c# asp.net-mvc cookies asp.net-identity asp.net-authorization

我正在学习C#/ .NET,我正在尝试启用cookie授权。我已经阅读了文档并试图实现他们的方法,但却无法让它发挥作用。每次成功登录并启用Authorization属性后,我都会根据Startup.cs中的设置重定向回登录页面。提前感谢您的任何帮助或建议。

我的代码如下:

Startup.cs

 public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddSession();
    services.AddDbContext<UserDashContext>(options => options.UseNpgsql(Configuration["DBInfo:ConnectionString"]));
    services.AddIdentity<User, IdentityRole>()
        .AddEntityFrameworkStores<UserDashContext>()
        .AddDefaultTokenProviders();
    services.Configure<IdentityOptions>(options =>
    {
        options.Password.RequireDigit = false;
        options.Password.RequiredLength = 8;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = false;
        options.Password.RequireLowercase = false;
        options.User.RequireUniqueEmail = true;
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    InitializeRoles(app.ApplicationServices).Wait();
    loggerFactory.AddConsole();
    app.UseCookieAuthentication(new CookieAuthenticationOptions()
    {
        AuthenticationScheme = "Cookies",
        LoginPath = "/signin",
        AccessDeniedPath = new PathString("/notAllowedRoute"),
        AutomaticAuthenticate = false,
        AutomaticChallenge = true
    });
    app.UseIdentity();
    app.UseDeveloperExceptionPage();
    app.UseStaticFiles();
    app.UseSession();
    app.UseMvc();
}

Controller.cs - 登录方法

public async Task<IActionResult> Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        User LoggingIn = _context.users.Where(u => u.Email == model.Email).SingleOrDefault();
        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, set lockoutOnFailure: true
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
        if (result.Succeeded)
        {
            return RedirectToAction("Index", "User");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            TempData["PWError"] = "Invalid login attempt.";
            return View(model);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

具有授权的Controller.cs

namespace UserDashboard.Controllers
    {
        [Authorize(ActiveAuthenticationSchemes = AuthScheme)]
        public class UserController : Controller
        {
            private const string AuthScheme = 
            CookieAuthenticationDefaults.AuthenticationScheme;
            UserDashContext _context;
            private readonly UserManager<User> _userManager;
            private readonly SignInManager<User> _signInManager;
            public UserController(UserDashContext context, UserManager<User> 
                userManager,
                SignInManager<User> signInManager)
            {
                _context = context;
                _userManager = userManager;
                _signInManager = signInManager;
            }

            [HttpGet]
            [Route("dashboard")]
            public IActionResult Index()
            {
            return View();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我最终删除了app.UseCookieAuthentication并将cookie设置添加到services.Configure。更新了以下代码:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddSession();
    services.AddDbContext<UserDashContext>(options => options.UseNpgsql(Configuration["DBInfo:ConnectionString"]));
    services.AddIdentity<User, IdentityRole>()
        .AddEntityFrameworkStores<UserDashContext>()
        .AddDefaultTokenProviders();
    services.Configure<IdentityOptions>(options =>
    {
        options.Password.RequireDigit = false;
        options.Password.RequiredLength = 8;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = false;
        options.Password.RequireLowercase = false;
        // Lockout settings
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
        options.Lockout.MaxFailedAccessAttempts = 10;

        // Cookie settings
        options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(150);
        options.Cookies.ApplicationCookie.LoginPath = "/signin";
        options.Cookies.ApplicationCookie.LogoutPath = "/logout";

        options.User.RequireUniqueEmail = true;
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    InitializeRoles(app.ApplicationServices).Wait();
    loggerFactory.AddConsole();
    // app.UseCookieAuthentication(new CookieAuthenticationOptions()
    // {
    //     AuthenticationScheme = "Cookies",
    //     LoginPath = "/signin",
    //     AccessDeniedPath = new PathString("/notAllowedRoute"),
    //     AutomaticAuthenticate = false,
    //     AutomaticChallenge = true
    // });
    app.UseIdentity();
    app.UseDeveloperExceptionPage();
    app.UseStaticFiles();
    app.UseSession();
    app.UseMvc();
}