无法添加和获取自定义声明值

25

我正在使用带有 Identity 2.0 的 mvc 5。我想在应用程序中使用自定义声明值,但是我得到了空值。我做错了什么?

更新的代码

在账户控制器中的登录代码

if (!string.IsNullOrEmpty(model.UserName) && !string.IsNullOrEmpty(model.Password))
            {
                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                var result = SignInManager.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: false);


                //Generate verification token
                Dictionary<string, string> acceccToken = null;
                if (SignInStatus.Success == 0)
                {
                    var userDeatails = FindUser(model.UserName, model.Password).Result;
                    if (userDeatails != null)
                        acceccToken = GetTokenDictionary(model.UserName, model.Password, userDeatails.Id);
                }
                if (model.RememberMe)
                {
                    HttpCookie userid = new HttpCookie("rembemberTrue", "1");
                    userid.Expires.AddDays(1);
                    Response.Cookies.Add(userid);
                }
                else
                {

                    HttpCookie userid = new HttpCookie("rembemberTrue", "0");
                    userid.Expires.AddDays(1);
                    Response.Cookies.Add(userid);

                }
                #region custom claims


                var claims = new Claim[]
                           {
                    new Claim("urn:Custom:MasterUniqueId", Convert.ToString(Guid.NewGuid()))
                                };
                ClaimsIdentity identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                IAuthenticationManager authenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
                authenticationManager.SignIn(identity);

启动身份验证(Startup.Auth.cs)

 public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                },
                SlidingExpiration = true,
                ExpireTimeSpan = TimeSpan.FromMinutes(60)
            });

另一个控制器

在这里,我试图获取那些声明的值,但它显示为空(null)。

var identity = (ClaimsIdentity)User.Identity;
var res= identity.FindFirst("urn:Custom:MasterUniqueId");

res 为空


您能展示一下您所使用的完整登录代码吗?这段代码所在的方法是否为异步方法?此外,在您的启动文件中,是否缺少app.UseCookieAuthentication(...)的代码? - Brendan Green
@BrendanGreen,我已经更新了我的问题,请看一下。 - Neeraj Sharma
你能看到 User.Identity.IsAuthenticatedUser.Identity.Name 的输出吗? - Matti Price
这里有一个示例:链接 - tmg
如果你能获取到User.Identity,那么你的方法是正确的。此外,你可以将User.Identity.Claims转换为ClaimsIdentity并获取请求密钥。 - Vishal Sharma
3个回答

1

1
在您的账户控制器中,要获取有效的authenticationManager,您应该使用Request.GetOwinContext().Authentication。我担心System.Web.HttpContext.Current.GetOwinContext().Authentication会使您得到一个新的authenticationManager,而不是当前的Owin上下文。

1

首先,您需要将标识转换为声明标识,然后尝试使用标识类型获取声明。

(HttpContext.Current?.User?.Identity as ClaimsIdentity)?.Claims?.FirstOrDefault(x => x.Type == "urn:Custom:MasterUniqueId")?.Value

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接