Access Claim values in controller in MVC 5

后端 未结 2 1957
我寻月下人不归
我寻月下人不归 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();
    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();
    

提交回复
热议问题