![](/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.