angular / angularfire

Angular + Firebase = ❤️
https://firebaseopensource.com/projects/angular/angularfire2
MIT License
7.66k stars 2.19k forks source link

AngularFireAuth.idToken is not valid for REST queries? #2254

Closed matheo closed 3 years ago

matheo commented 4 years ago

I'm being unable to get a Dynamic Link stats via

GET https://firebasedynamiclinks.googleapis.com/v1/SHORT_DYNAMIC_LINK/linkStats?durationDays=DURATION

Authorization: Bearer ID_TOKEN

Version info

Angular: 8.2.14

Firebase: 7.5.0

AngularFire: 5.2.3

How to reproduce these conditions

Steps to set up and reproduce

I'm trying to use the Angular Fire idToken and pass it to the HttpClient via interceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: MyAuthService) {}
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.idToken}`
      }
    });

    return next.handle(request);
  }
}

The header is correctly sent but I'm getting 401

Debug output

Errors in the Network console

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

Expected behavior

Looking at the API Authorization documentation, there's the scope https://www.googleapis.com/auth/firebase and I assume the AngularFire token is already authorized with it, but it's also curious that a response header of the error response is www-authenticate: Bearer realm="https://accounts.google.com/"

jamesdaniels commented 3 years ago

We don't auth with any scopes beyond the bare minimum & the firebase id token is not for communicating to these API. First make sure that scope is in your signInWithRedirect/Popup request, then either listen to the promise results from the signIn call or use the new .credentials observer, the raw OAuth token with those scopes is included in that object.