5

(ASP.NET 아이덴티티 2.1) 다음과 같이 내가 주장을 설정 : 내가 발행 내 클라이언트에서ASP.NET 웹 API 메서드 내에서 클레임 내용을 어떻게 찾을 수 있습니까? 내 코드에서

public static AuthenticationProperties CreateProperties(
     string userName, 
     ClaimsIdentity oAuthIdentity, 
     string firstName, 
     string lastName, 
     int organization) 
    { 

     IDictionary<string, string> data = new Dictionary<string, string> 
      { 
       { "userName", userName}, 
       { "firstName", firstName}, 
       { "lastName", lastName}, 
       { "organization", organization.ToString()}, 
       { "roles",string.Join(":",oAuthIdentity.Claims.Where(c=> c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray())} 

      }; 
     return new AuthenticationProperties(data); 
    } 

:

여기
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 
     var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); 
     ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); 
     if (user == null) 
     { 
      context.SetError("invalid_grant", "The user name or password is incorrect."); 
      return; 
     } 
     ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, 
      OAuthDefaults.AuthenticationType); 
     ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, 
      CookieAuthenticationDefaults.AuthenticationType); 
     AuthenticationProperties properties = CreateProperties(
      user.UserName, 
      oAuthIdentity, 
      user.FirstName, 
      user.LastName, 
      user.Organization); 
     AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); 
     context.Validated(ticket); 
     context.Request.Context.Authentication.SignIn(cookiesIdentity); 
    } 

다음 추가 역할에 대한 주장 CreateProperites 방법 토큰에 대한 요청을 다음과 같이 수신하십시오 :

this.$http({ 
     method: 'POST', 
     url: '/Token', 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded', 
     }, 
     data: 'grant_type=password&username=' + encodeURIComponent(userName) + '&password=' + encodeURIComponent(password), 
    }) 
     .success((data: any, status, headers, cfg) => { 
      self.data.roles = data.roles; 

self.data.roles가 역할로 올바르게 채워지는 것을 볼 수 있습니다. 이제 서버에서 롤의 내용을 확인하고 싶습니다. 누군가 이렇게 할 수있는 방법을 말해줌으로써 도움을받을 수 있습니까?

[HttpGet] 
    [Route("Retrieve")] 
    public async Task<IHttpActionResult> Retrieve() 
    { 

     var x = User; 

x는

System.Security.Claims.ClaimsPrinciple and 
System.Security.Claims.ClaimsIdentity 

의 값을 가져옵니다하지만 X에서 내가 주장 자체에 대한 정보를 찾을 수 없습니다 : 나는이 방법으로 다음을 수행 할 수 있습니다 알고 있습니다. 내가 제안 이전에 SO 게시하려고했다

참고 :

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

     // The following line returns null 
     var roles = identity.Claims.Where(r => r.Type == "roles").FirstOrDefault(); 

하지만 여전히 주장의 내부 내가 역할 주장과 관련 한 정보를 찾을 수 없습니다. 나는 그것이 클라이언트에게 도착할 때 거기에 있어야한다는 것을 안다.

"역할"클레임을 구체적으로 찾고 있습니다. 시스템에서 생성 된 클레임이 아닙니다. 그러나 내가 자신을 추가하려고 시도한 것은 역할의 연결 목록을 포함하고 있습니다.

답변

5

시도해 보셨습니까?

var roleClaims = identity.Claims.Where(c => c.Type == ClaimTypes.Role);

UPDATE 모든

첫째, 당신은 주장을 추가하지 않습니다. 일부 데이터를 AuthenticationTicket의 속성 사전에 추가하고 있습니다. 이 데이터는 쉼표로 분리 된 역할을하며, 이름을 지정하기 위해 선택한 키는 "역할"입니다. 그래서, 이것은 주장이 아닙니다.

나를 위해 작동하지 않는다고 말할 때, 나는 당신이 사전에 넣은 쉼표로 분리 된 값을 찾고 싶다고 믿는다. 이 경우 컨트롤러의 User에서 검색 할 수 없습니다. 베어러 토큰을 보낼 때 무기명 토큰 인증 미들웨어는 토큰을 읽고 토큰에서 ClaimsIdentity을 가져오고 컨텍스트에서 설정하여 User을 읽을 수있게합니다.

AuthenticationTicket에 넣은 것은 미들웨어 (실제로는 처리기) 용입니다. 따라서 AuthenticationTicket에서 데이터를 가져 오려면 베어러 미들웨어에서 직접 AuthenticateAsync으로 전화해야합니다. var result = await AuthenticationManager.AuthenticateAsync(OAuthDefaults.AuthenticationType);을 수행하면 ClaimsIdentity이 아닌 전체 티켓을 받게됩니다. result을 보면 쉼표로 구분 된 역할을 할 수 있지만 베어러 미들웨어는 이미 한 번만 수행했으며 다시 호출하는 것은 이해할 수 있습니다.

지금까지 사용자 지정 클레임을 추가하려면 oAuthIdentityGrantResourceOwnerCredentials에 추가해야합니다. 이처럼 그것을 할 경우

public override async Task GrantResourceOwnerCredentials(
          OAuthGrantResourceOwnerCredentialsContext context) 
{ 
    // snip 
    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, 
      OAuthDefaults.AuthenticationType); 
    oAuthIdentity.AddClaim(new Claim("urn:roles", "a,b,c"); 
} 

, 당신은 User에서 읽을 수 있습니다. CookieAuthenticationDefaults.AuthenticationType

상기 볼

:

var myRoleClaims = identity.Claims.Where(c => c.Type == "urn:roles");

+0

이 나를 위해 작동하지 않습니다를 추가했다. 나는 ClaimTypes.Role으로 추가 된 것을 추가하지 않고 자신의 소유권 주장의 내용을 찾고 싶습니다. 감사. –

+0

귀하의 조언에 감사드립니다. 나는 거기에 더 많은 예제가 있었으면 좋겠다. 나는 다른 웹 링크를 보면서 많은 시간을 보냈지 만 최근에는 아무것도 찾지 못했고 기술이 너무 빨리 변하기 때문에 계속 유지하기가 어렵다. –

1

내가 문제가 잘못된 authenticationType에서 찾고있는 생각, User.Identity는 쿠키와 '활성'authenticationType에 매핑 claimIdentity를 자신의 역할과 연관 시키려면 IAuthenticationManager.Authenticate (OAuthDefaults.AuthenticationType)를 호출해야합니다. 그러면 여러분이 기대하는 roleClaims가 표시 될 것입니다.

편집 : 예

var result = await AuthenticationManager.AuthenticateAsync(OAuthDefaults.AuthenticationType); 
    // do something with result.Identity 
+0

내가 이것을 부를 필요가있는 곳의 예를 들려 주시겠습니까? 이걸 컨트롤러에 넣어야합니까? 나에게 3-4 줄의 코드 예제를 줄 수 있다면 시도해 볼 수 있습니다. 고맙습니다. –

+1

물론, 컨트롤러에서 이와 같은 작업을 수행하여 클레임 ID를 알아낼 수 있어야합니다. –

+0

데이터베이스로 이동합니까? 브라우저에 "역할"클레임을 보내고 매번 서버로 돌아가서 데이터베이스에서 가져 오지 못하게 할 수 있었으면 좋겠습니까? –