Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Authentication (JWT) with .NET Core

Tags:

I'm developing a simple API that handles Authentication made by Firebase - to be used later with Android clients.

So in Firebase console I enabled Facebook and Google sign-in methods and created a sample html page that I can use it to test the login method - this next function is called by a button:

function loginFacebook() {         var provider = new firebase.auth.FacebookAuthProvider();         var token = "";         firebase.auth().signInWithPopup(provider).then(function (result) {             var token = result.credential.accessToken;             var user = result.user;             alert("login OK");             user.getToken().then(function (t) {                 token = t;                 loginAPI();             });         }).catch(function (error) {             var errorCode = error.code;             var errorMessage = error.message;             alert(errorCode + " - " + errorMessage);         });     } 

next I use the token and send it to my API with a simple ajax call from jQuery here:

function loginAPI() {     $.ajax({         url: "http://localhost:58041/v1/Users/",         dataType: 'json',         type: 'GET',         beforeSend: function (xhr) {             xhr.setRequestHeader("Accept", "application/json");             xhr.setRequestHeader("Content-Type", "application/json");             xhr.setRequestHeader("Authorization", "Bearer " + token);         },         error: function (ex) {             console.log(ex.status + " - " + ex.statusText);         },         success: function (data) {             console.log(data);             return data;         }     }); } 

Next stop: the API backend - written with .NET Core.

Under the Startup I've configured the JwtBearer Auth (package Microsoft.AspNetCore.Authentication.JwtBearer):

app.UseJwtBearerAuthentication(new JwtBearerOptions {     AutomaticAuthenticate = true,     IncludeErrorDetails = true,     Authority = "https://securetoken.google.com/PROJECT-ID",     TokenValidationParameters = new TokenValidationParameters     {           ValidateIssuer = true,         ValidIssuer = "https://securetoken.google.com/PROJECT-ID",         ValidateAudience = true,         ValidAudience = "PROJECT-ID",         ValidateLifetime = true,     }, }); 

And here is the Controller code - with the [Authorize] attribute:

[Authorize] [Route("v1/[controller]")] public class UsersController : Controller {     private readonly ILogger _logger;     private readonly UserService _userService;      public UsersController(ILogger<UsersController> logger, UserService userService)     {         _logger = logger;         _userService = userService;     }      [HttpGet]     public async Task<IList<User>> Get()     {         return await _userService.GetAll();     } } 

The API response is 200 OK (HttpContext.User.Identity.IsAuthenticated is true inside the Controller), but I think it shouldn't. My problem is that I'm not entirely sure that this is secure.

How this is checking the signature part of the JWT token? I saw a lot of code samples mentioning x509 or RS256 algorithm, where do they fit with this? Shouldn't be checking against some kind of certificate or private key with the IssuerSigningKey or TokenDecryptionKey from the TokenValidationParameters class? What I'm missing?

Relevant sources of knowledge about the issue:

  • https://blog.markvincze.com/secure-an-asp-net-core-api-with-firebase/
  • SPA - Firebase and .Net WebApi 2 authentication
  • https://stormpath.com/blog/token-authentication-asp-net-core
  • https://jwt.io/
  • https://firebase.google.com/docs/auth/admin/verify-id-tokens
like image 658
Izzy Rodriguez Avatar asked Feb 20 '17 05:02

Izzy Rodriguez


People also ask

Does Firebase Auth use JWT?

Firebase gives you complete control over authentication by allowing you to authenticate users or devices using secure JSON Web Tokens (JWTs). You generate these tokens on your server, pass them back to a client device, and then use them to authenticate via the signInWithCustomToken() method.

What is JWT authentication in ASP NET core?

JWT authentication is a standard way for protecting APIs - it's adept at verifying the data that's transmitted over the wire between APIs and the clients that consume the APIs. You can even safely pass claims between the communicating parties as well.


1 Answers

Firebase uses the RSA256 asymmetric key cryptosystem, which means it has a public and a private key. Signing a token happens with the private key, while verifying a token happens with the public key.

The following diagram illustrates how the token signing happens.

enter image description here

During signing in and accessing a secure endpoint, the following steps are involved.

  1. When our application starts up (and then later also periodically) the JwtBearerMiddleware calls https://securetoken.google.com/my-firebase-project/.well-known/openid-configuration, where it can access the current public keys of Google. It's important that when we're using a public key asymmetric cryptosystem, the public key is not kept as a secret, but it is published in plain sight.
  2. A client signs in using their credential through Firebase (these are the client's own credentials, they have nothing to do with the key used to sign the token).
  3. If the signin was successful, then Firebase constructs a JWT token for the client. A crucial part of this token is that it's signed using the private key of the key pair. In contrast to the public key, the private key is never exposed publicly, it is kept as a secret inside Google's infrastructure.
  4. The client receives the JWT token.
  5. The client calls a secure endpoint on our Api, and puts the token in the Authorization header. At this point the JwtBearerMiddleware in the pipeline checks this token, and verifies if it's valid (if it was signed with Google's private key). The important thing to realize here is that in order to do the verification, our Api does not need to have access to the private key. Only the public key is necessary to do that. After verification, the middleware populates HttpContext.User, and HttpContext.User.Identity.IsAuthenticated accordingly.

You can find an even simpler description of this concept on the RSA Wikipedia page, and some more information about Firebase + ASP.NET in my blog post.

like image 71
Mark Vincze Avatar answered Oct 18 '22 00:10

Mark Vincze