成功登录后被重定向到具有 Cookie 授权的登录页面 - AspNetCore 1.1



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

我的代码如下:

启动.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();
}

控制器.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);
}

控制器.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();
            }
        }
    }

我最终删除了应用程序。使用饼干身份验证和向服务添加 Cookie 设置。配置。更新了下面的代码:

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();
}

最新更新