Access Claim values in controller in MVC 5

后端 未结 2 1956
我寻月下人不归
我寻月下人不归 2020-12-07 22:33

I have used OWIN authentication in my application.

Login Action

var claims = new List();
claims.Add(new Claim(ClaimTyp         


        
相关标签:
2条回答
  • 2020-12-07 22:50

    You need to set your Thread.CurrentPrincipal after login i.e.

    var claims = new List<Claim>();
    claims.Add(new Claim(ClaimTypes.Name, result.UserFirstName));            
    claims.Add(new Claim(ClaimTypes.Sid, result.UserID.ToString()));
    var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
    var claimsPrincipal = new ClaimsPrincipal(identity);
    // Set current principal
    Thread.CurrentPrincipal = claimsPrincipal;
    

    Then the following will retrieve the values.

    //Get the current claims principal
    var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
    
    // Get the claims values
    var name = identity.Claims.Where(c => c.Type == ClaimTypes.Name)
                       .Select(c => c.Value).SingleOrDefault();
    var sid = identity.Claims.Where(c => c.Type == ClaimTypes.Sid)
                       .Select(c => c.Value).SingleOrDefault();
    
    0 讨论(0)
  • 2020-12-07 23:08

    Here is another example, with custom claim types as well:

    Login:

    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, user.Name, ClaimValueTypes.String),
        new Claim(ClaimTypes.Email, user.Email ?? string.Empty, ClaimValueTypes.Email),
        new Claim(ClaimTypes.PrimarySid, user.Id.ToString(), ClaimValueTypes.Integer),
        new Claim(CustomClaimTypes.SalesId, user.SalesId.ToString(), ClaimValueTypes.Integer)
    };
    
    var claimsIdentity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(claimsIdentity);
    

    Custom claims:

    public static class CustomClaimTypes
    {
        public const string SalesId = "SalesId";
    }
    

    Extension methods:

    public static class IdentityExtensions
    {
        public static int GetSalesId(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(CustomClaimTypes.SalesId);
    
            if (claim == null)
                return 0;
    
            return int.Parse(claim.Value);
        }
    
        public static string GetName(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(ClaimTypes.Name);
    
            return claim?.Value ?? string.Empty;
        }
    }
    

    Can then be accessed like this:

    User.Identity.GetSalesId();
    User.Identity.GetName();
    
    0 讨论(0)
提交回复
热议问题