Search code examples
htmljsonoauth-2.0requesttoken

How do I handle html response from oauth2 token request?


In my angular 6 application, I’m trying to send a request to get an access token from an oauth2 provider called anilist. I’m doing it like this:

    this.http.get(url, options).subscribe(result =>   
    {
      console.log('result: ', result);
    });

…where http is imported like this:

import { HttpClient } from ‘@angular/common/http';

This results in an error:

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse

This seems to be because the request is returning an html document (most likely the login page) and it obviously can’t parse it as json.

But then my question is: how does one send a request for an oauth2 token and handle the response as an html page?

Thanks.


Solution

  • It is a bit strange that you want to get access token via http get. Maybe that is the problem, are you talking about this site? https://anilist.co/

    https://anilist.gitbook.io/anilist-apiv2-docs/overview/oauth/authorization-code-grant

    1. The user navigates to their site via your oAuth2 signin link
    2. They sign in, add grant, then the browser redirects to your callback url
    3. You change your auth code to access token via http post request. https://anilist.gitbook.io/anilist-apiv2-docs/overview/oauth/authorization-code-grant#converting-authorization-codes-to-access-tokens

    I think you get an html response because

    • You try to get access token via http get - and here you get an unsupported method / 404 / etc error
    • Or you are trying to get your access token from the anilist's login page (anilist.co/api/v2/oauth/authorize) instead of the token endpoint (anilist.co/api/v2/oauth/token)

    Update

    It is the same case, if you are using implicit grant (because you said you are creating an angular app, which can be an SPA - therefore a public client, but in this case the access token is provided in the response) https://anilist.gitbook.io/anilist-apiv2-docs/overview/oauth/implicit-grant