jr.
jr.

Reputation: 4675

When firebase functions are proxied from webapp, how to authenticate the current user?

I have a firebase application which has a url proxied to a function using the "rewrites" feature in the firebase.json file. A request to https://myapp.com/hello will get routed to the 'helloWorld' function.

"rewrites": [
      {
    "source": "/hello",
    "function": "helloWorld"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]

Is it possible to determine the authenticated user of the request? Since the request is based on the same URI scheme as the application I would think this would be possible but all I see is the connect.sid cookie and that isn't the authorization token.

Upvotes: 0

Views: 25

Answers (1)

jr.
jr.

Reputation: 4675

I've figured this out, you need to manually set the __session cookie with the token of the currently logged in user.

Here is how I do it in an AuthService in an angular firebase application.

 this.firebaseAuth.authState.subscribe( currentUser => {
      this.authenticatedUser = currentUser;
      if (currentUser === null) {
        this.cookieService.delete("__session");
      } else {
        currentUser.getIdToken().then(token =>
          cookieService.set('__session', token)
        );
      }
    });

Then in your function you can do this:

admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
  console.log('ID Token correctly decoded', decodedIdToken);
  req.user = decodedIdToken;
}

Where idToken is the value from the __session cookie.

Upvotes: 1

Related Questions