簡體   English   中英

用戶通過身份驗證后,Razor 頁面授權未加載頁面

[英]Razor page authorization not loading page when user is authenticated

我一直在嘗試在我的 Razor 3.0 Web 應用程序中實現基本身份驗證。

, however when trying to redirect to a page that requires Authorization, the page does not load.我有一個用戶通過登錄,但是當嘗試重定向到需要授權的頁面時,該頁面不會加載。 " appended.相反,登錄頁面會重新加載,並且 URL 會更新並附加“ ”。

啟動文件

 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 文件夾設置為需要授權,並允許匿名用戶訪問登錄頁面。

登錄.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);
    }

在這里,我設置了一個始終返回 true 的虛擬 API,用戶擁有一個 Claim 創建它們並登錄它們。

  • 我已經嘗試通過調試,我可以看到 User.Identity.IsAuthenticated 被正確設置為 true
  • 當我從 Admin 文件夾中刪除 Authorization 時,頁面會正確重定向
  • 登錄后正在注冊對用戶的聲明

我是 Razor 的新手,所以我可能會錯誤地處理這個問題,感謝任何幫助,謝謝。

訂單事項

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM