MVC 5 访问声明身份用户数据 [英] MVC 5 Access Claims Identity User Data

查看:35
本文介绍了MVC 5 访问声明身份用户数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Entity Framework 5 Database First 方法开发 MVC 5 Web 应用程序.我正在使用 OWIN 进行用户身份验证.下面显示了我在我的帐户控制器中的登录方法.

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

如您所见,我正在创建一个 ClaimsIdentity 并向其添加多个声明,然后使用 AuthenticationManager 将其传递给 OWIN 以执行登录.

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.

我遇到的问题是我不确定如何访问应用程序其余部分中的声明,无论是在控制器中还是在 Razor 视图中.

我已经尝试过本教程中列出的方法

I had tried the approach listed in this tutorial

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

例如,我在我的控制器代码中尝试了这个,试图访问传递给 Claims 的值,但是,user.Claims 等于 null

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.

更新

根据 Darin 的回答,我添加了他的代码,但仍然看不到对 Claims 的访问.请参阅下面的屏幕截图,显示我将鼠标悬停在 identity.Claims 上时所看到的内容.

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.

推荐答案

试试这个:

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

这篇关于MVC 5 访问声明身份用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆