8

MVC 5 인터넷 응용 프로그램을 개발 중이며 Identity 2.1을 사용 중입니다.MVC 5 - 사용자에게 소유권 주장 추가

사용자가 로그인 한 후 claim을 추가 할 수있는 곳, 내가 username을 알고 있습니까? 여기

내가 무엇을 가지고 :

public void AddClaimToUser(string userName, string type, string value) 
{ 
    var AuthenticationManager = HttpContext.Current.GetOwinContext().Authentication; 
    var Identity = new ClaimsIdentity(userName); 
    Identity.AddClaim(new Claim(type, value)); 
    AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true }); 
} 

그러나, 나는이 메소드를 호출, 나는 사용자의 주장을 확인 후, 추가 claim가 표시되지 않습니다. 사전에

var identity = (ClaimsIdentity)User.Identity; 
IEnumerable<Claim> claims = identity.Claims; 

감사 : 여기

내가 컨트롤러의 주장을 얻기 위해 사용하고있는 코드입니다.

답변

0

AuthenticationResponseGrant을 부여하면 이미 로그인 한 사용자에게 소유권 주장을 추가하는 것으로 충분하지 않습니다. 신원을 확인하고 새 소유권 주장을 추가 한 다음 (이미이 작업을 수행 한 다음) 사용자에게 서명하고 다시 로그인해야합니다. 나는 거의 이것을 다음과 같이 수행한다. this answer

2

우선 IdentityModels.cs 클래스 아래에 add claim을위한 메소드를 만들어야한다. 아래 코드에서 CompanyId에 대한 클레임이 생성되었다.

public class ApplicationUser : IdentityUser 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public bool IsActive { get; set; } 
    public int? CompanyId { get; set; } 


public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
{ 

    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 

    userIdentity.AddClaim(new Claim("CompanyId", (this.CompanyId + "" ?? "0"))); 

    return userIdentity; 
}} 

코드 위에 기입 한 후, 당신은 ... 당신은 그냥 입력하여 컨트롤러에서 생성 된 주장을 얻을 수 있습니다 이후 IdentityConfig.cs에

public static class IdentityExtensions{ 
public static int CompanyId(this IIdentity identity) 
{ 
return Convert.ToInt32(((ClaimsIdentity)identity).FindFirst("CompanyId").Value); 
}} 

을 또 하나의 방법을 쓸 필요가

int companyId = User.Identity.CompanyId();