簡體   English   中英

MVC 6 Cookie身份驗證-從Cookie中獲取用戶詳細信息

[英]MVC 6 Cookie Authentication - Getting User Details From the Cookie

我正在使用使用實體或身份的MVC 6應用程序。 相反,我正在使用Dapper。 我有一個控制器,該控制器接受POST請求並使用Dapper檢查數據庫以查看用戶名/密碼是否匹配。 我要做的只是存儲用戶名以及他們是否已登錄,因此我可以在后續頁面上進行檢查。

我環顧四周,似乎使用基於Cookie的身份驗證應該可以執行我想做的事情。 這是我的Startup.cs文件中的相關代碼:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    LoginPath = "/account/login",
    AuthenticationScheme = "Cookies",
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

這是我的控制器登錄操作中的相關代碼如下所示:

var user = _repo.FindByLogin(model.VendorId, model.Password);
if (user != null) {
 var claims = new List < Claim > {
  new Claim("VendorId", user.VendorId),
  new Claim("Name", "john")
 };

 var id = new ClaimsIdentity(claims, "local", "name", "role");
 await HttpContext.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(id));
 var l = ClaimsIdentity.DefaultNameClaimType;
 return RedirectToAction("Index", "PurchaseOrders");
}

上面的代碼似乎在保存cookie的情況下起作用,但是我不確定如何將用戶信息從cookie中取回(或者甚至如何首先在后續請求中檢索cookie)。 。

在我的腦海中,我正在想象能夠執行以下操作: var user = (User)HttpContext.Request.Cookies.Get(????) ,但是我不確定這是否可行。

您可以使用ClaimsPrincipal.FindFirstValue(xxx)取回用戶數據。

這是我的示例類,可在Controller / Views中使用以獲取當前用戶信息

public class GlobalSettings : IGlobalSettings
    {
        private IHttpContextAccessor _accessor;

        public GlobalSettings(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }    

        public string RefNo
        {
            get
            {
                return GetValue(_accessor.HttpContext.User, "employeeid");
            }
        }

        public string SAMAccount
        {
            get
            {
                return GetValue(_accessor.HttpContext.User, ClaimTypes.WindowsAccountName);
            }
        }

        public string UserName
        {
            get
            {
                return GetValue(_accessor.HttpContext.User, ClaimTypes.Name);
            }
        }

        public string Role
        {
            get
            {
                return GetValue(_accessor.HttpContext.User, ClaimTypes.Role);
            }
        }

        private string GetValue(ClaimsPrincipal principal, string key)
        {
            if (principal == null)
                return string.Empty;

            return principal.FindFirstValue(key);
        }
}

DI之后在控制器中的示例用法:

var currentUser = GlobalSettings.SAMAccount;

請注意,您需要在Startup.cs的ConfigureServices方法中注入HttpContextAccessor

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

暫無
暫無

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

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