2016-10-10 1 views
0

우리는 Android 응용 프로그램이 기존 Auth 시스템을 활용하여 Firebase 데이터베이스에 액세스 할 수 있도록 사용자 지정 인증을 설정하려고합니다..NET의 Firebase 사용자 지정 인증에서 "사용자 지정 토큰 형식이 잘못되었습니다."

모바일 응용 프로그램은 .NET WebAPI 끝점에 대해 인증합니다. Firebase 인증 토큰을 사용하여 Firebase SDK에서 인증 할 수 있습니다.

문서에 따르면 매우 간단하다고 생각했습니다. Nuget의 FirebaseTokenGenerator 패키지를 사용하여 Firebase 콘솔> 프로젝트> 관리> 데이터베이스> 데이터베이스 비밀에있는 비밀에서이 토큰을 생성합니다.

com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The custom token format is incorrect. Please check the documentation. 
at com.google.android.gms.internal.zzafd.zzes(Unknown Source) 
at com.google.android.gms.internal.zzafa$zzg.zza(Unknown Source) 
at com.google.android.gms.internal.zzafl.zzet(Unknown Source) 
at com.google.android.gms.internal.zzafl$zza.onFailure(Unknown Source) 
at com.google.android.gms.internal.zzafg$zza.onTransact(Unknown Source) 

문서를 통해 찾고는 문제가 무엇인지 명확하지 않기 때문에 더욱 저를 혼동하고있다 : 우리가 여기에 생성 된 토큰을 사용하는 경우이 예외 다시 안드로이드 SDK에서 제공 참조 그러나

. 많은 후보 솔루션이있는 것 같지만 어느 것이 옳은 것인지 파악할 수 없습니다. 다음은 문서에 대한 이야기를 몇 가지 것들 :

  • 이 서비스 계정을 만들기 JWT의 JSON 파일을 다운로드, 포함은 닷넷 WebApi 프로젝트에서 어떤 방법을 사용하여 그 FirebaseTokenGenerator
  • 사용하여 3와 비밀에서 토큰을 생성하기 위해 파티 용 JWT 라이브러리를 작성하십시오.

이 두 가지 전략은 동일한 것으로 보이지만 어쨌든 관련성이없는 것처럼 보입니다.

잘못된 암호를 사용하고 있습니까? 올바른 토큰을 생성하려면 WebAPI 프로젝트에 대한 추가 설정이 필요합니까?

public string GetSignedFirebaseAuthToken(Agent agent, DateTime expires) 
{ 
    var tokenGenerator = new Firebase.TokenGenerator(BusinessLogicResources.FirebaseSecret); 
    var authPayload = new Dictionary<string, object>() 
    { 
     { "uid", agent.AgentId.ToString() }, 
     { "UserName", agent.FullName }, 
     { "AgencyId", agent.AgencyId }, 
     { "AgencyName", agent.AgencyName } 
    }; 
    return tokenGenerator.CreateToken(authPayload, new Firebase.TokenOptions(expires:expires)); 
} 

업데이트 : 이 나는 ​​민트 내 중포 기지 토큰을 사용하고 새로운 코드가

는 참고로,이 내 토큰을 생성하는 방법이다.

public string GetSignedFirebaseAuthToken(Agent agent, DateTime expires) 
    { 
     // I set the expiry time to 3600 because this is the maximum number of seconds 
     // allowed according the the Firebase documenation. 
     var expiryTime = 3600; 
     // This claims object contains some additional information that Telenotes would 
     // like to track for each user of Firebase. This is used for reporting and 
     // security rules in Firebase. 
     var claims = new Dictionary<string, object>() 
     { 
      { "UserName", agent.FullName }, 
      { "AgencyId", agent.AgencyId.ToString() }, 
      { "AgencyName", agent.AgencyName } 
     }; 
     // In order for the cryptography algorithms to be happy, I need to put our 
     // keys into stream objects. 
     var memoryStream = new MemoryStream(); 
     var streamWriter = new StreamWriter(memoryStream); 
     streamWriter.Write(BusinessLogicResources.FirebaseSecret.Replace(@"\n", "\n")); 
     streamWriter.Flush(); 
     memoryStream.Position = 0; 
     var streamReader = new StreamReader(memoryStream); 
     // BouncyCastle takes care of the cryptography stuff, so we'll hand our 
     // secret over to BouncyCastle to read and encode. 
     var bouncyCastleReader = new PemReader(streamReader); 
     var rsaParams = (RsaPrivateCrtKeyParameters) bouncyCastleReader.ReadObject(); 
     // Now that the secret is packed up all nicely in rsaParams, I need to 
     // put together the rest of the payload that Firebase needs in my auth token. 
     var tokenPayload = new Dictionary<string, object>() 
     { 
      { "claims", claims }, 
      { "uid", agent.AgentId }, 
      { "iat", (DateTime.Now).SecondsSinceEpoch() }, 
      { "exp", (DateTime.Now).AddSeconds(expiryTime).SecondsSinceEpoch() }, 
      { "aud", BusinessLogicResources.FirebasePayloadAud }, 
      { "iss", BusinessLogicResources.FirebasePayloadISS }, 
      { "sub", BusinessLogicResources.FirebasePayloadSUB }, 
      { "alg", "RS256" } 
     }; 

     // Lastly, we need to put it all together using JOSE JWT (see https://github.com/dvsekhvalnov/jose-jwt) 
     // and BouncyCastle encoding magic. 
     var rsaKey = DotNetUtilities.ToRSA(rsaParams); 
     return JWT.Encode(tokenPayload, rsaKey, JwsAlgorithm.RS256); 
    } 
+0

.NET을 사용하고 있으므로 [타사 JWT 라이브러리를 사용하여 사용자 지정 토큰 만들기] (https://firebase.google.com/docs/auth/server/create-custom-tokens)를 찾고 있습니다. # create_custom_tokens_using_a_third-party_jwt_library). 이 설명서의 다른 섹션은 지원되는 SDK 용 섹션입니다. BusinessLogicResources.FirebasePayload * 값은 무엇입니까? 서비스 계정 이메일, 신원 ​​URL 등이 정확히 일치하는지 어떻게 확인 했습니까? 확인을 돕기 위해 난독 화 방식으로 값을 공유 할 수 있습니까? – Kato

+0

또한 agent.AgentId의 값은 무엇입니까? 오류는 어디에 생성됩니까? 클라이언트에서 인증을 요청하려고 할 때? 여기서 사용하는 토큰이 여기서 출력 한 것과 일치하는지 어떻게 확인 했습니까? 여기에있는 기본 접근법은 .NET을 이해하는 한 올바른 것으로 보입니다. – Kato

+0

오류는 클라이언트, Android 애플리케이션에서 생성됩니다. 우리는 여기에 출력되는 토큰이 클라이언트를 통해 유선으로 올바르게 전달되는지 확인했습니다. – aaronlangford31

답변

1

키 몇 가지 이해하기 :

이슈 # 내 프로젝트의 일환으로 FirebaseTokenGenerator 2.0.0를 사용했다 1

. the GitHub project을 체크 아웃하면,이 패키지가 Firebase 3.x.x와 호환되지 않는다고 분명하게 명시되어 있습니다.

따라서 .NET에서 기존 인증 시스템을 사용하려는 경우 타사를 사용하여 Firebase 토큰을 결합해야합니다. 이를 수행하는 좋은 예가 this post에 나와 있습니다.

BouncyCastle 또는 JOSE JWT (Firebase 암호의 토큰을 인코딩하는 데 도움이되는 라이브러리)가 마음에 들지 않으면 Google에서 here을 제공하는 사양을 검토하고이 모든 기능을 사용할 수있는 다른 방법을 찾아 볼 수 있습니다 체계.

2

올바른 토큰이 위에서 언급 한 과정에서 사용하는 문제 번호는 데이터베이스 비밀이 아니다. Firebase 팀은 서비스 계정으로 서버를 설정하기를 원합니다. 이를 수행하는 방법에 대한 자세한 내용은 here입니다.

이 과정에서 JSON 문서를 다운로드해야합니다. 이 JSON 문서에는 "private_key_id"라는 속성이 있습니다. 약간 펑키 ("-----BEGIN PRIVATE KEY-----\n...")로 보이지만 위에서 언급 한 키 생성 과정에서이 모든 것이 필요합니다. 따라서 문자열 해석이나 그와 같은 어떤 것도 필요 없습니다. 해당 문서의 다른 값이 필요하지만 이미 제공된 링크에 이러한 세부 정보가 표시됩니다.

영원히 이런 식으로되지 않을 것 같아서 좋은 라이브러리가 앞으로 몇 달 안에 나올 것이므로이 과정을 더 간단하게 만들 것입니다.

관련 문제