登录Asp.NET Core 2

时间:2017-10-23 19:20:38

标签: asp.net-core asp.net-core-2.0 asp.net-core-identity

有关如何正确登录Asp.NET Core V2的问题。我正在使用ASP.NET身份。

我的OnPostAsync()方法如下。我的代码成功获取用户名和pwd,调用signin manager,并成功返回true。我认为正确的登录方式是调用SigninPasswordAsync。一个成功的结果又回来了。

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        var userName = Request.Form["UserName"];
        var pwd = Request.Form["Password"];
        var appUser = new ApplicationUser() { UserName = userName };
        var signin = await _signInManager.PasswordSignInAsync(userName, pwd, true, false);
        if (signin.Succeeded)
        {
            return RedirectToPage("/Account/LoggedIn");
        }
        else
        {
            return RedirectToPage("/Account/Login");
        }
    }

因此,一旦重定向发生,它就会重定向到LoggedIn剃刀页面。 PageModel的内容如下。问题是使用[Authorize]属性会导致页面无法加载并重定向到Login页面,如果满足[Authorize]属性的条件,这就是我所期望的。授权条件未得到满足。深入研究这似乎表明HttpContext.User似乎没有太多/任何内容。我假设我需要调用除SigninPasswordAsync方法之外的东西或使用不同的属性。思考?我还需要做点什么吗?我已经迷失了在这一点上做什么,所以任何想法都会受到赞赏。感谢。

[Authorize]
public class LoggedInModel : PageModel
{
    public void OnGet()
    {
        var use = HttpContext.User;
    }
}

****更新****************************

我在Startup.cs文件中添加以下内容:

    public static IConfigurationRoot Configuration { get; set; }
    // 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)
    {
        var builder = new ConfigurationBuilder()
       .SetBasePath(System.IO.Directory.GetCurrentDirectory())
       .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
        services.AddDbContext<PooperAppDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<PooperAppDbContext>()
            .AddDefaultTokenProviders();

        services.AddScoped<SignInManager<ApplicationUser>>();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = false;
            options.Password.RequiredUniqueChars = 6;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.Lockout.AllowedForNewUsers = true;

            // User settings
            options.User.RequireUniqueEmail = true;

        });

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.Cookie.Expiration = TimeSpan.FromDays(150);
            options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
            options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
            options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
            options.SlidingExpiration = true;
        });

        services.AddMvc().AddRazorPagesOptions(options =>
        {
            //options.Conventions.AuthorizeFolder("/MembersOnly");
            options.Conventions.AuthorizePage("/Account/Logout");
            options.Conventions.AuthorizePage("/Account/LoggedIn", "PooperBasic, PooperPayer"); // with policy
            //options.Conventions.AllowAnonymousToPage("/Pages/Admin/Login"); // excluded page

            //options.Conventions.AllowAnonymousToFolder("/Public"); // just for completeness
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
        });
    }

    // 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();
        }
        else
        {
            var options = new RewriteOptions()
                .AddRedirectToHttps();
        }
        app.UseMvc();
        app.UseAuthentication();
    }
}

1 个答案:

答案 0 :(得分:3)

您需要在 UseAuthentication之前致电UseMvc 。所有中间件都作为管道的一部分运行,因此在您的情况下,您预期不会调用身份验证中间件。

有关中间件管道的详细描述,请查看docs

注意:您不应该需要致电services.AddScoped<SignInManager<ApplicationUser>>();,因为这将由AddIdentity内容处理。