登录 Asp.NET 核心 2
Login in Asp.NET Core 2
关于如何正确登录 Asp.NET Core V2 的问题。我正在使用 ASP.NET 身份。
我的 OnPostAsync() 方法如下。我的代码成功获取用户名和密码,调用登录管理器,并成功返回 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 razor 页面。 PageModel 的内容如下。问题是使用 [Authorize] 属性会导致页面无法加载并重定向到登录页面,如果满足 [Authorize] 属性的条件,这正是我所期望的。未满足授权条件。对此进行深入研究似乎表明 HttpContext.User 中似乎没有 much/any 内容。我假设我需要调用 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();
}
}
您需要在 UseMvc
之前调用UseAuthentication
。所有中间件都作为管道的一部分运行,因此在您的情况下,身份验证中间件不会在您期望的时候被调用。
查看 docs 以获得对中间件管道的详细描述。
注意:您不需要调用 services.AddScoped<SignInManager<ApplicationUser>>();
,因为这将由 AddIdentity
处理。
关于如何正确登录 Asp.NET Core V2 的问题。我正在使用 ASP.NET 身份。
我的 OnPostAsync() 方法如下。我的代码成功获取用户名和密码,调用登录管理器,并成功返回 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 razor 页面。 PageModel 的内容如下。问题是使用 [Authorize] 属性会导致页面无法加载并重定向到登录页面,如果满足 [Authorize] 属性的条件,这正是我所期望的。未满足授权条件。对此进行深入研究似乎表明 HttpContext.User 中似乎没有 much/any 内容。我假设我需要调用 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();
}
}
您需要在 UseMvc
之前调用UseAuthentication
。所有中间件都作为管道的一部分运行,因此在您的情况下,身份验证中间件不会在您期望的时候被调用。
查看 docs 以获得对中间件管道的详细描述。
注意:您不需要调用 services.AddScoped<SignInManager<ApplicationUser>>();
,因为这将由 AddIdentity
处理。