angulartypescriptauth0auth0-lock

Auth0 Angular - 401 when trying to get/update the profile with auth0.client


I am using Auth0 alongside an Angular application. I am hitting the Management API of Auth0 to update the profile metadata with the following methods which I got from Auth0 documentation:

  public getProfile(cb): void {
    if (!this._accessToken) {
      throw new Error('Access Token must exist to fetch profile');
    }

    const self = this;
    this.auth0.client.userInfo(this._accessToken, (err, profile) => {
      if (profile) {
        self.userProfile = profile;
      }
      cb(err, profile);
    });
  }

  public updateProfile(profileChanges : ProfileUpdate): Observable<any>  {
    console.log(this.userProfile);
    var url = 'https://APP.auth0.com/api/v2/users/' + this.userProfile.sub;
    var data = {
      user_metadata: {
        firstName: profileChanges.firstName,
        lastName: profileChanges.lastName,
        telephone: profileChanges.telephone
      }
    };

    return this.http.patch(url, data);
  }

Since I will have some additional custom logic firing inside of the JwtInterceptor, I wrote a custom one like so instead of using the HttpClient from Auth0 extensions:

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      let currentUser = this.authenticationService.currentUserValue;
      if (currentUser) {
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${currentUser.token}`
          }
        });
      }
      return next.handle(request);
    }
}

This ends up with 401 against the Management API every time I try to get or post a profile update. The authentication and authorization mechanisms however work without issue and I can log in and log out just fine. I was trying to switch around the tokens to idTokens instead and making sure that I don't miss any permissions inside of Auth0 dashboard but I don't see anything. Any idea what it might be?


Solution

  • From your description I assume that you're trying to call the Auth0 Management API with the same access token that you use for your own backend/API. That won't work due to wrong token audience and scopes. The Management API needs to be called with a token explicitly issued for that.

    Note though that usually the end user would not call that management API himself, but that would be a call from your backend to the Management API, where your backend would fetch the access token for it via Client Credentials Grant (M2M / Machine to Machine).

    An SPA (Single Page Application) has no way to store the client credentials securely to execute such a client credentials grant.

    See

    https://auth0.com/docs/api/management/v2/tokens

    enter image description here