我一直在尝试在Razor 3.0 web应用程序中实现基本身份验证。
我有一个用户通过SignInAsync((登录,但当尝试重定向到需要授权的页面时,该页面不会加载。取而代之的是重新加载登录页面?ReturnUrl=%Page%路径"附件。
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages(options =>
{
options.Conventions.AuthorizeFolder("/Admin");
options.Conventions.AllowAnonymousToPage("/Login");
options.Conventions.AddPageRoute("/Login", "");
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
在这里,我将Admin文件夹设置为需要授权,并允许匿名用户访问登录页面。
登录.cs.html.cs
[BindProperty]
public UserModel UserLogin { get; set; }
public async Task<IActionResult> OnPost()
{
try
{
if (ModelState.IsValid)
{
var loginInfo = apiConnector.Get();
if (loginInfo)
{
await this.SignInUser(UserLogin.Username, false);
return this.RedirectToPage("/Admin/FormOverview");
}
}
}
catch(Exception e)
{
Console.Write(e);
}
return this.Page();
}
private async Task SignInUser(string username, bool isPersistant)
{
try
{
var claims = new List<Claim>() {
new Claim(ClaimTypes.Name, username)
};
var claimIdentities = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var claimPrincipal = new ClaimsPrincipal(claimIdentities);
var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
IsPersistent = true,
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimPrincipal, authProperties);
}
在这里,我设置了一个伪API,它总是返回true,用户有一个Claim创建了它们并将它们登录
- 我已经尝试过调试,我可以看到User.Identity.IsAuthenticated被正确地设置为true
- 当我从"管理"文件夹中删除"授权"时,页面将正确重定向
- 登录后正在注册用户上的声明
我是Razor的新手,所以我可能处理得不正确,感谢您的帮助,谢谢。
订单事项
app.UseAuthentication();
app.UseAuthorization();