Neozenweb
Neozenweb

Reputation: 19

Fetch API using JWT authorization

My EdX API access request has been approved. As per the documentation, I have generated the client id and client secret on the admin website. Using fetch, I have got the token from the https://api.edx.org/oauth2/v1/access_token URL by passing the client id and client secret. The token is a valid one I can see in my console. But when I pass this token as below, I get a 403 (Forbidden) error:

fetch("https://api.edx.org/catalog/v1/catalogs", {
  method:"GET",
  headers: {
    "Authorization": "JWT " + token,
    "Access-Control-Allow-Origin": "http://localhost:3000"
  }
})
.then( r => r.json() )
.then( res => console.log("SUCCESS " + res.count) )
.catch( err => console.log("ERROR  " + err) );

I have tried all the variations of the request like credentials:true, all the "Allow-control" headers etc, but this error persists. Upon using the dev tools on Chrome, the "Network" tab shows a completely different Fetch is used which is:

fetch("https://api.edx.org/catalog/v1/catalogs", {
  "credentials":"omit",
  "referrer":"http://localhost:3000/",
  "referrerPolicy":"no-referrer-when-downgrade",
  "body":null,
  "method":"GET",
  "mode":"cors"
});

The equivalent curl works at the command line and through Insomnia, and gets the data perfectly.

Upvotes: 1

Views: 5410

Answers (1)

Lee Goddard
Lee Goddard

Reputation: 11183

Without knowing the ins and outs of the specific system to which you are connecting, I cannot be authoritative, but most systems seem to use not JWT but Bearer as the prefix to the authorization bearer token in the Authorization header:

const res = await fetch("https://api.edx.org/catalog/v1/catalogs", {
  headers: {
    "Authorization": "JWT " + token
  }
});
const json = await res.json();

Upvotes: 0

Related Questions