I am not able to add bearer token in $resource service header for token based authentication. I used following code
Factory
return $resource(appSettings.serverPath + "/api/product/:id", null, {
'get': {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + currentUser.getProfile().token
}
}
Also i tried below code as per some research in app.run
$http.defaults.headers.common.Authorization = 'Bearer ' + currentUser.getProfile().token;
But both options do not add this header in my request and i can see request in chrome without this headers and hence got unauthorized response. I am using angular 1.5.9. Any clue on this.
Assuming currentUser is a service and currentUser.getProfile() is a synchronous API:
app.factory("myRestAPI", function(currentUser) {
return $resource(appSettings.serverPath + "/api/product/:id", null, {
'get': {
method: 'GET',
headers: {
//REPLACE expression
//'Authorization': 'Bearer ' + currentUser.getProfile().token
//WITH a function
'Authorization':
function() {
return 'Bearer ' + currentUser.getProfile().token;
}
}
}
);
});
By using a function instead of an expression, the Authorization header will be computed on every call.
From the Docs:1
headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
Related
I am trying to set the header in an Axios PUT request with my Auth token, but when I view the call on the server (running my UI app from localhost) the header is null. I've used this same pattern with Axios and GET, POST, and DELETE calls without issue. Is there anything different with respect to a PUT call and the header?
Below is the code:
return axios.put(BASE_URI + '/submissions/' + submissionId + '/submit',
{
headers: {
'Authorization': 'Bearer ' + this.accessToken,
}
})
In order to add headers in POST or PUT, you need a third argument which will contain headers keys
axios.put(url, data, config)
return axios.put(BASE_URI + '/submissions/' + submissionId + '/submit',
{}, // post/put body
{
headers: {
'Authorization': 'Bearer ' + this.accessToken,
}
})
I created a Django RESTful API with JWT as authentication method, but unable to pass the token as headers using angularJS.
I think there is no error on my API, since I used the token I acquired by this script and tested it in Postman:
my JWT token authentication script is here:
// Uses http.get() to load data from a single API endpoint
list() {
return this.http.get('api/', this.getHttpOptions());
}
// helper function to build the HTTP headers
getHttpOptions() {
return {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
})
};
}
I tried using http.get() here. Thanks in advance!
the error will be like:
401 (Unauthorized)
Try this:
list() {
return this.http.get('api/', { this.getHttpOptions() });
}
getHttpOptions() {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
});
return headers;
}
Same issue on JWT for CakePHP3, and follow header slove it, may it is helpful.
this.http.get('api/', { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token,
'Authenticationtoken': 'JWT ' + this._userService.token
}) });
Thanks guys,
I found the problem is about CORS, My solutions are here, there are two approaches to solve this problem, one is add 'Access-Control-Allow-Origin': '*' to your http request, sometimes you need add more. Another answer is add CORS_ORIGIN_WHITELIST = 'localhost:4200', in your backend.
https://www.youtube.com/watch?v=OIbndrrUYiY
I am opening the url without authentication using below code,
$window.open(downloadUrl);
I want to use below authorization
Authorization': 'Bearer ' + '123hrwertjwtjwjrtr',
i have used below code but it is not working,
var params =
{
'Authorization': 'Bearer ' + '123hrwertjwtjwjrtr',
'Content-type': 'application/x-www-form-urlencoded',
};
var downloadUrl = somedummyurl;
var url = [downloadUrl, $.param(params)].join('?');
$window.open(url);
Can anyone suggest how to add bearer token while calling the api url.
In api am using httpget method and used authorize tag..
I'm trying to wrangle the auth-0 angular plugin for JWTs and I'm stuck in a spot where I've setup the jwtInterceptor to push a JWT token into the headers of every single request made.
Here is my code:
// Send JWT with every request
jwtInterceptorProvider.tokenGetter = ['config', function(config) {
var user = JSON.parse(localStorage.getItem('ngStorage-user'));
var token = user.token;
return token;
}];
$httpProvider.interceptors.push('jwtInterceptor');
The problem is that there are a few instances where I need to make a call where I DON'T send the token in the headers of the request, such as getting the initial JWT token on registration. As of right now, with my code, if there is no JWT set, it results in an error.
One of other thought I had was to just edit each call to send the token in the headers manually, however I can't seem to get the request to work with ngResource:
function getCourseCatalog(token) {
return Registrar.checkToken($localStorage.user.token).then(function(data) {
return $resource($rootScope.APIBaseURL + 'catalog',{
query: {
method: 'GET',
isArray: true,
headers: {
Authorization: 'Bearer ' + $localStorage.user.token
}
}
});
});
}
^ With this function, the call never gets made and I'm pretty sure this is exactly how you're supposed to setup the $resource call. Is there something I'm missing? This particular call is hitting an endpoint that gets an array of objects.
It turns out that the function was missing a parameter, but additionally, I needed to still run the query() function on $resource in order to actually make the call. The new function looks like this:
function getCourseCatalog(token) {
return Registrar.checkToken($localStorage.user.token).then(function(data) {
return $resource($rootScope.APIBaseURL + 'catalog',{},{
query: {
method: 'GET',
isArray: true,
headers: {
Authorization: 'Bearer ' + $localStorage.user.token
}
}
}).query();
});
}
In my angular app the global $http headers are defined for every request, like this:
function useBasicAuth(username, hash) {
var encoded = btoa(username + ':' + hash);
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
}
How to disable sending this information, when for example the user logs out, and the authentication is no longer required?
What I found as a working solution was to redeclare the $http.defaults.headers.common Object so it won't contain the headers.
Example:
function useBasicAuth(username, hash) {
var encoded = btoa(username + ':' + hash);
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
}
This, however won't delete the cached credentials from the browser. To overcome this, I've made a simple - and not asynch call to generate a bad request on purpose.
This is the function for this in my accountServices factory:
function checkAuth(username, hash) {
var encoded = btoa(username + ':' + hash);
var result = false;
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Basic ' + encoded);
},
url: "user/current",
statusCode: {
401: function () {
result = false;
},
200: function (response) {
result = response;
}
},
async: false
});
return result;
}
To log the user out, I call this function:
function useBasicWithoutAuth() {
accountServices.checkAuth('logout','logout');
$http.defaults.headers.common = {Accept: "application/json, text/plain, */*"};
}
So what this does, is it first sends a request to a protected URL, with a fake and non-existant user, so it's basically the same, as if the prompt would appear to you, and you'd click cancel.
After this has been done, there's no cached data in the browser, we can simply remove the headers from Angular, so it won't send any Authorization information, where it's not needed.