![](/img/trans.png)
[英]How to implement OWIN authentication for logged-in user credential in MVC6?
[英]How to get the logged user with an OWIN authentication?
我的AccountController 中的登錄代碼
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, user.Name+" "+user.Surname));
claims.Add(new Claim(ClaimTypes.Role, role.Code));
var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, claimIdenties);
在我的PrivateController 中,我想訪問經過身份驗證的用戶的 ID,我正在搜索 ID 字段或類似的內容,但是
如何使用 OWIN 身份驗證獲取登錄用戶?
編輯
Request.GetOwinContext().Authentication.User.Identity
使我可以訪問以下屬性:
如何設置像“Claim.ID”這樣的 ID 並檢索它?
第二次編輯
這篇文章https://stackoverflow.com/a/24893167/4470880解決了我的問題。
從Microsoft.AspNet.Identity.Core
NuGet 包https://www.nuget.org/packages/Microsoft.AspNet.Identity.Core/ ,在Microsoft.AspNet.Identity
命名空間中,有獲取用戶 ID 的擴展方法和名稱——請參閱MSDN IdentityExtensions 類 (Microsoft.AspNet.Identity)
用法是這樣的(來自控制器):
string userId = this.HttpContext.User.Identity.GetUserId();
你也可以這樣寫:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;
public class BaseController : Controller
{
protected ApplicationUser CurrentUser
{
get { return System.Web.HttpContext.Current.GetOwinContext()
.GetUserManager<ApplicationUserManager>()
.FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
}
}
//...
}
所以你寫了一個繼承自Controller
的BaseController
。
然后,您的所有控制器都將從BaseController
; 所以你可以在所有控制器中使用CurrentUser.Id
試試這個替代方案:
var user = HttpContext.GetOwinContext().Authentication.User;
獲取user
:
string name = HttpContext.GetOwinContext().Authentication.User.Identity.Name;
希望這可以幫助...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.