asp.net mvc - Firebase 3: creating a custom authentication token using .net and c# -


i'm trying implement firebase 3 authentication mechanism using custom tokens (as described @ https:// firebase.google.com/docs/auth/server/create-custom-tokens).

my server asp.net mvc application.

so according instructions (https://firebase.google.com/docs/server/setup) i've created service account firebase application , generated key in '.p12' format.

after according instructions here (https://firebase.google.com/docs/auth/server/create-custom-tokens#create_custom_tokens_using_a_third-party_jwt_library) tried generate custom token , sign using key received on previous step. token generation used systemidentitymodel.tokens.jwt library microsoft, code looks following:

var = datetime.utcnow; var tokenhandler = new jwtsecuritytokenhandler(); var key = new x509asymmetricsecuritykey(new x509certificate2(p12path, p12pwd)); var signincredentials = new signingcredentials(key, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "http://www.w3.org/2001/04/xmlenc#rsa-sha256"); int32 nowinunixtimestamp = (int32)(now.subtract(new datetime(1970, 1, 1))).totalseconds;  var token = tokenhandler.createtoken(             issuer: serviceaccountemail,             audience: "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.identitytoolkit",                             signingcredentials: signincredentials,             subject: new claimsidentity(new claim[]                     {                     new claim("sub", serviceaccountemail),                     new claim("iat", nowinunixtimestamp.tostring()),                     new claim("exp", (nowinunixtimestamp + (60*60)).tostring()),                     new claim("uid", uid)                     })             );  var tokenstring = tokenhandler.writetoken(token); 

then tried sign in user in react native application using firebase javascript sdk, following code:

//omitting initialization code firebase.auth().signinwithcustomtoken(firebasejwt).catch(function(error) {             console.log('error authenticating firebase user. code: ' + error.code + ' message: ' + error.message);                     }); 

but got error firebase saying:

error authenticating firebase user. code: auth/invalid-custom-token message: custom token format incorrect. please check documentation.

experimenting adding different claims token expiration control didn't either.

also tried generate tokens "dvsekhvalnov/jose-jwt" library can't working "rs256" algorithm.

so question:

any suggestion on doing wrong?

this pure .net solution works me, using org.bouncycastle (https://www.nuget.org/packages/bouncycastle/) , jose.jwt (https://www.nuget.org/packages/jose-jwt/) libraries.

i followed these steps:

  • in firebase console click 'cog' icon top left, next project name, , click 'permissions'.
  • at iam , admin page, click 'service accounts' on left
  • click 'create service account' @ top, enter 'service account name', select 'project->editor' in role selection, tick 'furnish new private key' checkbox , select json
  • click 'create' , download service account json file , keep safe.
  • open service account json file in suitable text editor , put values following code:

    // private_key service account json file public static string firebaseprivatekey=@"-----begin private key-----\nmiie...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n-----end private key-----\n";  // same public static string firebasepayloadaud="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.identitytoolkit";  // client_email service account json file public static string firebasepayloadiss="serviceaccountname@projectname.iam.gserviceaccount.com"; public static string firebasepayloadsub="serviceaccountname@projectname.iam.gserviceaccount.com";  // token 'exp' - max 3600 seconds - see https://firebase.google.com/docs/auth/server/create-custom-tokens public static int firebasetokenexpirysecs=3600;  private static rsaprivatecrtkeyparameters _rsaparams; private static object _rsaparamslocker=new object();  void main() {     // example custom claims     var uid="myuserid";     var claims=new dictionary<string, object> {         {"premium_account", true}     };     console.writeline(encodetoken(uid, claims)); }  public static string encodetoken(string uid, dictionary<string, object> claims) {     // rsaprivatecrtkeyparameters if haven't determined them     if (_rsaparams == null) {         lock (_rsaparamslocker) {             if (_rsaparams == null) {                 streamreader sr = new streamreader(generatestreamfromstring(firebaseprivatekey.replace(@"\n","\n")));                 var pr = new org.bouncycastle.openssl.pemreader(sr);                 _rsaparams = (rsaprivatecrtkeyparameters)pr.readobject();             }         }     }      var payload = new dictionary<string, object> {         {"claims", claims}         ,{"uid", uid}         ,{"iat", secondssinceepoch(datetime.utcnow)}         ,{"exp", secondssinceepoch(datetime.utcnow.addseconds(firebasetokenexpirysecs))}         ,{"aud", firebasepayloadaud}         ,{"iss", firebasepayloadiss}         ,{"sub", firebasepayloadsub}     };      return jose.jwt.encode(payload, org.bouncycastle.security.dotnetutilities.torsa(_rsaparams), jwsalgorithm.rs256); }  private static long secondssinceepoch(datetime dt) {     timespan t = dt - new datetime(1970, 1, 1);     return (long)t.totalseconds; }  private static stream generatestreamfromstring(string s) {     memorystream stream = new memorystream();     streamwriter writer = new streamwriter(stream);     writer.write(s);     writer.flush();     stream.position = 0;     return stream; } 

to working in iis needed change application's pool identity , set "load user profile" setting true.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -