分享

MVC 5 Access Claims Identity User Data [MVC 5访问请求身份的用户数据]

 ThinkTank_引擎 2015-12-22

MVC 5 Access Claims Identity User Data

MVC 5访问请求身份的用户数据

问题 (Question)

I am developing an MVC 5 web application using Entity Framework 5 Database First approach. I am using OWIN for the authentication of Users. Below shows my Login method within my Account Controller.

    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = _AccountService.VerifyPassword(model.UserName, model.Password, false);
            if (user != null)
            {
                var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

                identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
                identity.AddClaim(new Claim(ClaimTypes.GivenName, "A Person"));
                identity.AddClaim(new Claim(ClaimTypes.Sid, user.userID)); //OK to store userID here?

                AuthenticationManager.SignIn(new AuthenticationProperties
                {
                    IsPersistent = model.RememberMe
                }, identity);

                return RedirectToAction("Index", "MyDashboard");
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

As you can see I'm creating a ClaimsIdentity and adding several claims to it, then passing it to OWIN using the AuthenticationManager to perform the sign in.

The problem I am having is that I'm not sure how to access the claims in the rest of my application, either in Controllers or in Razor Views.

I had tried the approach listed in this tutorial

http:///2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

For example, I tried this in my Controller code in an attempt to get access to the values passed into the Claims, however, the user.Claims is equal to null

var ctx = HttpContext.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;

Perhaps I am missing something here.

Any help would be greatly appreciated and I apologise if this is a novice question, it's my first experience with OWIN and using Claims Identity.

Thanks.

UPDATE

Based on Darin's answer, I added his code but still I fail to see access to the Claims. Please see screenshot below showing what I see when hovered over identity.Claims.

enter image description here

我正在开发一个MVC 5Web应用程序实体框架5数据库方法。我用的对用户的认证。下面显示了我的登录我的帐户内的控制器的方法。

    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = _AccountService.VerifyPassword(model.UserName, model.Password, false);
            if (user != null)
            {
                var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

                identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
                identity.AddClaim(new Claim(ClaimTypes.GivenName, "A Person"));
                identity.AddClaim(new Claim(ClaimTypes.Sid, user.userID)); //OK to store userID here?

                AuthenticationManager.SignIn(new AuthenticationProperties
                {
                    IsPersistent = model.RememberMe
                }, identity);

                return RedirectToAction("Index", "MyDashboard");
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

你可以看到我创建一个claimsidentity添加一些声称它,然后将它使用认证管理器执行标志。

我的问题是我不知道如何访问我的其他应用程序的要求,无论是在控制器或视图。

我试过的方法,在这篇教程中列出

http:///2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

例如,我想这在我的控制代码以获得传递到要求值,然而,用户要求等于零。

var ctx = HttpContext.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;

也许是我错过了什么。

任何帮助将不胜感激,我道歉,如果这是一个新手的问题,这是我第一次经历恩和使用要求的身份。

感谢

更新

基于达林的回答,我加了他的代码,但我仍然看不到访问请求。请看下面的截图显示了我所看到的,在identity.claims。

在这里输入图像描述

最佳答案 (Best Answer)

Try this:

[Authorize]
public ActionResult SomeAction()
{
    var identity = (ClaimsIdentity)User.Identity;
    IEnumerable<Claim> claims = identity.Claims;
    ...
}

试试这个:

[Authorize]
public ActionResult SomeAction()
{
    var identity = (ClaimsIdentity)User.Identity;
    IEnumerable<Claim> claims = identity.Claims;
    ...
}

答案 (Answer) 2

You can also do this:

//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var claims = identity.Claims;

Update

To provide further explanation as per comments.

If you are creating users within your system as follows:

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

You should automatically have some Claims populated relating to you Identity.

To add customized claims after a user authenticates you can do this as follows:

var user = userManager.Find(userName, password);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));

The claims can be read back out as Darin has answered above or as I have.

The claims are persisted when you call below passing the identity in:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);

This article describes this in more detail and is specific to MVC 5, the other articles I know of are aimed at MVC 4.

http://kevin-junghans./2013/12/using-claims-in-aspnet-identity.html

你也可以这样做:

//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var claims = identity.Claims;

更新

提供进一步的解释,根据的评论。

如果你正在创建的用户在你的系统如下:

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

你应该有一些有关自动填充你的身份。

在用户认证你可以添加自定义的要求如下:

var user = userManager.Find(userName, password);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));

索赔可以回读了达林的回答以上或为我。

的要求是坚持当你调用下面通过身份:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);

本文介绍了在更多的细节和具体的MVC 5,我知道是针对MVC 4的其他文章。

http://kevin-junghans./2013/12/using-claims-in-aspnet-identity.html

答案 (Answer) 3

You can also do this.

IEnumerable<Claim> claims = ClaimsPrincipal.Current.Claims;

你也可以这样做。

IEnumerable<Claim> claims = ClaimsPrincipal.Current.Claims;

答案 (Answer) 4

To further touch on Darin's answer, you can get to your specific claims by using the FindFirst method:

        var identity = (ClaimsIdentity)User.Identity;
        var role = identity.FindFirst(ClaimTypes.Role).Value;

进一步对达林的回答的触摸,你可以得到你的具体要求采用FindFirst方法

        var identity = (ClaimsIdentity)User.Identity;
        var role = identity.FindFirst(ClaimTypes.Role).Value;

答案 (Answer) 5

Request.GetOwinContext().Authentication.User.Claims

However it is better to add the claims inside the "GenerateUserIdentityAsync" method, especially if regenerateIdentity in the Startup.Auth.cs is enabled.

Request.GetOwinContext().Authentication.User.Claims

然而这是更好地添加声称里面的“generateuseridentityasync”的方法,尤其是如果在startup.auth.cs regenerateidentity启用。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多