无法添加和获取自定义声明值 [英] Unable to add and fetch custom claims values

查看:112
本文介绍了无法添加和获取自定义声明值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用身份为2.0的mvc 5.我想在应用程序上使用自定义声明值,但得到空值.我究竟做错了什么?

I am using mvc 5 with identity 2.0. I want use custom claim values over the application but I get null values. What am I doing wrong?

更新代码

帐户控制器中的登录代码

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

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

另一个控制器

我在这里尝试获取该声明值,但显示为空

Here I am trying to fetch that claim values but it shows null

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

res为空

res is null

推荐答案

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

First you need to convert identity to claims identity and then try to get claim using identity type

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

这篇关于无法添加和获取自定义声明值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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