用户通过身份验证时,Razor 页面授权不加载页面

Razor page authorization not loading page when user is authenticated

我一直在尝试在我的 Razor 3.0 网络应用程序中实施基本身份验证。

我有一个用户通过 SignInAsync() 登录,但是在尝试重定向到需要授权的页面时,该页面未加载。相反,登录页面会重新加载,URL 会更新为附加了“?ReturnUrl=%Page%Path”。

Startup.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文件夹需要授权,允许匿名用户访问登录页面

Login.cshtml.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,它始终 returns 为真,用户拥有创建它们并登录的声明。

我是 Razor 的新手,所以我可能没有正确处理这个问题,感谢任何帮助,谢谢。

订单很重要

app.UseAuthentication();
app.UseAuthorization();