簡體   English   中英

User.Identity.Name 在 PasswordSignInAsync MVC .Net Core 3.0 之后始終為 null 並聲明計數為 0

[英]User.Identity.Name always null and claims count 0 after PasswordSignInAsync MVC .Net Core 3.0

我有一個無法使用 ASP.NET MVC Core 3.0 解決的問題。 登錄后,結果成功並成功返回到我想要登錄的頁面,當我檢查cookies或session時,我可以看到API成功添加了它們。 但是當我嘗試獲取 User.Identity.Name 時,它​​始終為 null,並且 isAuthenticated 始終等於 false。 這就像 app.UseAuthentication() 不讀取 cookie 或會話。

我的啟動.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<AnisubsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("AnisubsDBConnection")));

        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<AnisubsDbContext>()
            .AddDefaultTokenProviders();
        services.AddMvc();
        services.AddControllersWithViews();


        services.AddAuthentication(options =>
        {
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
            .AddFacebook(facebookOptions =>
            {
                facebookOptions.AppId = "353222242210621";
                facebookOptions.AppSecret = "XXXX";
                facebookOptions.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/Login/Callback");
            })
            .AddGoogle(googleOptions =>
            {
                googleOptions.ClientId = "1093176997632-ug4j2h7m9f1nl9rg8nucecpf9np0isro.apps.googleusercontent.com";
                googleOptions.ClientSecret = "XXXX";
                googleOptions.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/Login/Callback");
            })
            .AddTwitter(twitterOptions =>
            {
                twitterOptions.ConsumerKey = "lZ2ugpLuKpDOlmdSuyw1hVJLU";
                twitterOptions.ConsumerSecret = "XXXX";
                twitterOptions.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/Login/Callback");
            })
            .AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId = "22f501ab-70c9-4054-8f33-2b35af3a64ba";
                microsoftOptions.ClientSecret = "XXXX";
                microsoftOptions.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/Login/Callback");
            })
            .AddCookie();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseStaticFiles();

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseHttpsRedirection();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

登錄控制器.cs

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel loginViewModel)
    {
        if (ModelState.IsValid)
        {
            var user = await userManager.FindByEmailAsync(loginViewModel.Email);
            if (user != null)
            {
                var result = await signInManager.PasswordSignInAsync(user.UserName, loginViewModel.Password, loginViewModel.RememberMe, false);
                if (result.Succeeded)
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
        }
        return View(loginViewModel);
    }

重定向到主頁后的會話在此處輸入圖片說明

Razor 頁面共享 _navbarlayout.cshtml(_layout.cshtml 內的部分視圖)

@using Microsoft.AspNetCore.Identity

@inject SignInManager<IdentityUser> signInManager;


<nav class="navbar fixed-top">


    <a class="navbar-logo" href="Dashboard.Default.html">
        <span class="logo d-none d-xs-block"></span>
        <span class="logo-mobile d-block d-xs-none"></span>
    </a>

    <div class="navbar-right">
        <div class="header-icons d-inline-block align-middle">
        <div class="user d-inline-block">
            <button class="btn btn-empty p-0" type="button" data-toggle="dropdown" aria-haspopup="true"
                    aria-expanded="false">
                @if (signInManager.IsSignedIn(User))
                {
                    <span class="name">@User.Identity.Name</span>
                }
                else
                {
                    <span class="name">Not Registered</span>
                }

                <span>
                    <img alt="Profile Picture" src="img/profile-pic-l.jpg" />
                </span>
            </button>

            <div class="dropdown-menu dropdown-menu-right mt-3">
                @if (signInManager.IsSignedIn(User))
                {
                    <a class="dropdown-item" href="#">Account</a>
                    <a class="dropdown-item" href="#">Features</a>
                    <a class="dropdown-item" href="#">History</a>
                    <a class="dropdown-item" href="#">Support</a>
                    <a class="dropdown-item" asp-action="logout" asp-controller="account">Sign out</a>
                }
                else
                {
                    <a class="dropdown-item" asp-action="login" asp-controller="account">Login</a>
                    <a class="dropdown-item" asp-action="register" asp-controller="account">Register</a>
                }
            </div>
        </div>
    </div>
</nav>

從上面的剃刀代碼中,signInManager.IsSignedIn(User) 始終為 false,User.identity 聲稱始終計數為零。

更改了如下啟動中間件的順序,問題還是一樣

app.UseStaticFiles();
            app.UseHttpsRedirection();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            }); 

下面是一個 GIF 圖片,顯示當 quickwatch 用戶在此處輸入圖片說明

ASP.NET Core Identity 創建一個 cookie(在屏幕截圖中顯示為.AspNetCore.Identity.Application ),它在成功調用PasswordSignInAsync后設置。 Startup.ConfigureServicesAddIdentity的調用設置了這一點:它注冊一個名為Identity.Application的身份驗證方案,並將其設置為應用程序的默認身份驗證方案。

現在,考慮到這一點,從問題中獲取以下代碼:

 services.AddAuthentication(options => { options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; })

如上所述,對AddAuthentication調用將默認身份驗證方案覆蓋CookieAuthenticationDefaults.AuthenticationScheme 這最終會導致PasswordSignInAsync使用Identity.Application方案正確登錄用戶,但應用程序在嘗試加載當前用戶時使用的是Cookies方案。 自然,這意味着用戶永遠不會被加載。

就解決方案而言,只需從AddAuthentication刪除回調:

services.AddAuthentication()
    .AddFacebook(facebookOptions =>
    {
        // ...
    })
    .AddGoogle(googleOptions =>
    {
        // ...
    })
    .AddTwitter(twitterOptions =>
    {
        // ...
    })
    .AddMicrosoftAccount(microsoftOptions =>
    {
        // ...
    });

我還刪除了對AddCookie的調用,這是多余的。 這會添加Cookies身份驗證方案,但您的應用程序正在使用Identity.Application ,如前所述。

嘗試更改“startup.cs”中中間件的順序。 所以,你應該用app.UseHttpsRedirection()之前app.UseAuthentication()是這樣的:

    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

暫無
暫無

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

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