如何通过OWIN身份验证获取登录用户?

时间:2018-06-20 10:43:53

标签: c# asp.net-mvc owin

我的 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字段或类似的内容,但是

enter image description here

如何通过OWIN身份验证获取登录用户?

修改

Request.GetOwinContext().Authentication.User.Identity

可以访问以下属性:

  • AuthenticationType
  • 已通过身份验证
  • 名称//Claim.Name

如何设置“ Claim.ID”之类的ID并进行检索?

第二次修改

这篇帖子https://stackoverflow.com/a/24893167/4470880解决了我的问题。

3 个答案:

答案 0 :(得分:1)

Microsoft.AspNet.Identity.Core名称空间的Microsoft.AspNet.Identity NuGet软件包https://www.nuget.org/packages/Microsoft.AspNet.Identity.Core/中,有扩展方法来获取用户的ID和名称-请参见MSDN IdentityExtensions Class (Microsoft.AspNet.Identity)

用法是这样的(来自控制器):

string userId = this.HttpContext.User.Identity.GetUserId();

答案 1 :(得分:1)

您也可以这样写:

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()); 
            }
    }

    //...
}

因此,您编写了一个BaseController继承的Controller
然后,您的所有控制器将从BaseController继承;因此您可以在所有控制器中使用CurrentUser.Id

答案 2 :(得分:1)

尝试以下替代方法:

var user = HttpContext.GetOwinContext().Authentication.User;


获取user的名称:

string name = HttpContext.GetOwinContext().Authentication.User.Identity.Name;

希望这对您有帮助...