Proper way to get current User ID in Entity Framework Core

后端 未结 4 918
灰色年华
灰色年华 2021-02-07 01:56

There are a bunch of different answers floating around here for the different RC\'s of ASP.NET Core on how to get the ID of the currently logged in user. I wanted to ask the def

4条回答
  •  清歌不尽
    2021-02-07 02:56

    The one-liner below is a more concise version of the other answers above.

    var user = User.FindFirst(ClaimTypes.NameIdentifier).Value;
    

    To explain a little further, I wanted to use the most basic form of authentication without any tables in the database so I chose this one - Using Cookie Authentication without ASP.NET Core Identity from the Core documentation.

    To get this working, the first step is to add the services in Startup.cs

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
            options.LoginPath = new PathString("/Account/Login/");
            options.LogoutPath = new PathString("/Account/Logoff/");
            options.AccessDeniedPath = new PathString("/Account/AccessDenied/");
            options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });
    
    services.ConfigureApplicationCookie(identityOptionsCookies =>
    {
        // See https://andrewlock.net/automatically-validating-anti-forgery-tokens-in-asp-net-core-with-the-autovalidateantiforgerytokenattribute/
        identityOptionsCookies.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
    });
    

    Then in the AccountController on the post back having entered a valid user id and password, the simplest Claims based authentication is to just add the login id as a Claim, e.g.

    var claims = new List { new Claim(ClaimTypes.NameIdentifier, loginViewModel.Guid, ClaimValueTypes.String, issuer), };

                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
                var principal = new ClaimsPrincipal(claimsIdentity);
    
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal,
                    new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(_cookieTimeoutInMinutes),
                        IsPersistent = true,
                        AllowRefresh = false
                    });
    

    Once the Sign In completes you can retrieve the user id as described in the one liner above. See the answer from Milos Mrdovic above for the more detailed steps.

    var user = User.FindFirst(ClaimTypes.NameIdentifier).Value;
    

    See Claims-Based Authorization for further information.

提交回复
热议问题