How to assign bearer token to authorization header in javaScript - javascript

I'm trying to make a GET request from the instructure-canvas API that requires a bearer token. I'm able to do so via both Postman and a curl command they provided me with:
curl -H "Authorization: Bearer <ACCESS-TOKEN>" "https://canvas.instructure.com/api/v1/courses"
Both these methods work and I am returned with the proper json data. However, I was wondering if there exists a way of doing this same operation in JavaScript (with or without additional libraries/frameworks). Apologies if this is trivial, I am very new to working with API's.

If you're making the request from the browser, you can use the Fetch API. It'll look a little something like this:
const url = ""; // API URL
const token = ""; // API Token
const method = "GET"; // Request method, change for what's needed
fetch(url, {
method,
headers: {
"Authorization": `Bearer ${token}` // This is the important part, the auth header
}
}).then(res => res.json().then(console.log)).catch(console.error); // Do better handling here
Depending on the server setup, you may need additional headers. Also keep an eye on the console for errors relating to CORs, as once again they will differer depending on how the server has been configured.

Related

What config does in the axios.get?

Can someone help me understand why it should have the config for this? What was headers or authorization does? Why should I put it as a second parameter?
dispatch({ type: 'FETCH_REQUEST' });
let config = {
headers: { authorization: `Bearer ${userInfo.token}` },
};
//Fetching the data from the backend
const { data } = await axios.get(`/api/orders/${orderId}`, config);
The header is essentially the header of the HTTP request. You need it for special config like authentication key, XSSR token, and other special config which you can read more in that link. The authorization is a authorization token. This is usually the JWT token that you got from the server when you've finished the authentication process. You can read more on the JWT authentication process here. Once you got the authorization token in your header of your request and send it to your server, your server will read in this token, deserialize it to get the data and determine if your HTTP request are valid and return the data. If your token is not valid, the server will throw an 403 (Unauthorize) error.
axios() has a whole number of ways you can specify the request you want.
For example, you can specify just a config object:
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
Where the config object contains the method, url and other necessary options.
For all other types of requests, the config object is optional and is only needed if you need to specify some argument other than the URL or the data to send.
For example, with axios.get(), you can use either axios.get(someUrl) or axios.get(someUrl, config). The config object can contain all the options listed here in the doc. Among those options are custom headers, data to append to the URL (for a GET request), options for timeout, sending of credentials, basic auth, progress callbacks, etc....
All these options in the config object are optional. You only need to specify the ones that your particular request requires.
In the code example you show in your question:
let config = {
headers: { authorization: `Bearer ${userInfo.token}` },
};
//Fetching the data from the backend
const { data } = await axios.get(`/api/orders/${orderId}`, config);
This is specifying a custom header for the request that contains an authorization token that is presumably required by the server for this particular type of request so that in the headers of the http request, it will add something like this:
Authorization: Bearer someTokenValueHere
You can read about the authorization header here.

How to use the bearer code in Twitter API requests?

I can not retrieve data from twitter even after generating a Bearer code. An example of a request is:
var url = "https://api.twitter.com/1.1/statuses/show.json?id=1125750390664892417";
var bearer = 'Bearer '+ 'myBearer code';
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'Content-Type': 'application/json'}
}).then((anyResponse) => {
console.log(anyResponse);
}) .catch(error => console.log('Something bad happened ' + error.message)
);
I do not understand what could be possibly wrong, but It always fails. I have obtained the bearer code following this page (https://developer.twitter.com/en/docs/basics/authentication/guides/bearer-tokens). But I did not encode any of my keys (as I have read here it was necessary, but the twitter page doesnt say so). Does somebody have an idea what could possibly go wrong with my request ???
Thanks!
For me, it finally worked in Postman when I used the bearer code without the base64 encryption. However, It goes against the docu and the nice python coded commented by a user above.
I still did not implement in my JS code, but since it is working is Postman, I can imagine that any XHR request with the same credentials should also work. Thanks for the help!

Not able to set request headers to my ajax request

I'm trying to make an ajax call to service, my service api expects a Request Header for Authorization to give the response
Here is my JS code
var settings = {
url: "http://localhost:8080/codebluet-war/service/codeblue/facility",
method: "GET",
headers: {
"Authorization": "oauthtoken"",
}
}
$.ajax(settings).done(function (response) {
console.log(response)
});
I have added the Authorization headers in my code but still I'm getting 401 unauthorized request error.is there any other thing that I need to add in my settings?
If you are using OAuth 2.0 you should prefix the token value with Bearer word:
headers: {
"Authorization": "Bearer yourTokenValue",
}
With OAuth 1.0, it's a little bit more complicated since you need to send a set of parameters instead of a single token. Therefore, you may want to consider using a jQuery compatible OAuth library for this purpose.

Spotify API - Retrieving Valid Access Token in Google Apps Scripts

Here is the documentation for the Spotify API (I'm using the Implicit Grant Flow): https://beta.developer.spotify.com/documentation/general/guides/authorization-guide/#implicit-grant-flow
I'm trying to write a script in Google Sheets. I'm focussing on the basic setup, but I cannot seem to get the access token working.
SOLVED:
I'm currently receiving the following error (it seems like my
parameters for my fetch method aren't set properly):
"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"
SOLUTION:
The grant_type must be listed as a payload according to the Google
Scripts method UrlFetchApp.fetch (see updated code below)
--
SOLVED:
As you can see below I'm using the 'get' method when trying to get the
token (despite the documentation specifying 'post') because the post
method consistently returns a 405 error. I think this is the step I'm
screwing up on. I'm assuming that I'm not supposed to be using the
csrf_token as the access token.
SOLUTION:
https://accounts.spotify.com/token should have been
https://accounts.spotify.com/api/token
Updated working code below:
var fetchParams = {
'method':'post',
'payload':{'grant_type':'client_credentials'},
'headers':{'Authorization':authorization},
'muteHttpExceptions':true
}
var replaceResponse = UrlFetchApp.fetch('https://accounts.spotify.com/api/token', fetchParams);
var regExp = /access_token(.*?):/;
var contentText = replaceResponse.getContentText();
var access_token = contentText.slice(contentText.search('access_token')+15,contentText.search(',')-1);
var requestOptions = {
'headers':{'Authorization':'Bearer '+access_token},
'muteHttpExceptions':true
}
var finalResponse = UrlFetchApp.fetch('https://api.spotify.com/v1/tracks/4dhARBZ8YLvm8oRDnCIeXr', requestOptions);
I modified your script for retrieving access token by following curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token of the document. Can you please try this modified script?
var authorization = "Basic "+ Utilities.base64Encode('<client_id>:<client_secret>');
var fetchParams = {
method: 'post', // Modified
payload: {'grant_type': 'client_credentials'}, // Modified
headers: {'Authorization': authorization},
muteHttpExceptions: true
}
var replaceResponse = UrlFetchApp.fetch("https://accounts.spotify.com/api/token", fetchParams); // Modified
Logger.log(replaceResponse.getContentText())
Reference :
Client Credentials Flow
If the response message was changed, please tell me.

How to retrieve a Bearer Token from an Authorization Header in JavaScript (Angular 2/4)?

In JavaScript I have a method which authenticates to my server via an http post request successfully.
The response data from my server is sending a JWT in an Authorization header like so:
Authorization: Bearer mytoken12345abc
I can retrieve the authorization header successfully from my servers response data like so for example:
let authheader = response.headers.get('Authorization');
But how do I parse this? Is "Bearer" a key? so something like:
let token = authheader.Bearer
which obviously is not correct. What can I try next?
In other words, is the following the best approach?
let token = response.headers.get('Authorization');
let parsedToken = token.slice(7);
According to the jwt.io docu,
Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema.
Therefore using the JWT in the Authorization header is supposed to be used by the client, not the server for the initial response.
The correct way is to get the token as part of the response body. We use a
{ jwt: TOKEN }
type scheme for that.
Then you can easily access it via your response.json().
You can access the header value directly using response.headers.get(...) but then you will have to split, substr or regex-match to get the actual token.
When you get token from server set it in storage of browser session/local like below
sessionStorage.setItem('token', authheader);
Whenever you call the services to server set Authorization token in header it's a secure way like below
import { Http, Headers, RequestOptions, Response } from '#angular/http';
getUser(){
let headers = new Headers({ 'Authorization': 'Bearer ' + sessionStorage.getItem('token') });
let options = new RequestOptions({ headers: headers });
// get users from api
return this.http.get('http://localhost:9000/api/user', options)
.map((response: Response) => response.json());
}

Categories

Resources