I am trying to set my auth token recieved from the response after user registration into Ember Data request header.
Here is my application.js code
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'merchant',
host: 'http://192.168.1.173:3000',
headers: function() {
return {
"token":localStorage.token,
};
}.property("localStorage.token","token")
});
I am trying to set the header after receiving success response from my register user API call.
var register=this.store.createRecord('registermerchant',data);
register.save().then(function(response){
console.log(response.success);
if(response.get('success')){
self.set('token',response.get('token'));
self.transitionToRoute('merchanthome')
}
and
tokenChanged: function() {
localStorage.token=this.get('token');
console.log(localStorage.token);
}.observes('token'),
I am able to see the updated localStorage.token value however this value for some reason does not get set to the reqest header token key.
The token is not getting updated to the header , it is only after doing a page refresh that the new updated token is being sent to the server.
Any thoughts on what I could be doing wrong,any tips would be greatly appreciated.
Thanks
localStorage is not an observable Ember object, so your property("localStorage.token") will only be evaluated once. Instead make it volatile to re-evaluate the property every time:
headers: function() {
return {
"token":localStorage.token,
};
}.property().volatile()
Related
I am using fetch in my react project to fetch data from an API which is authenticated using a token and my login end-point in the postman return the token in authorization header, you can see
and this's my login funtion in reactjs project
async login(dataLogin) {
const response = await fetch(`${API_URL}/login`, {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: dataLogin
});
const data = await response
console.log(response.headers);
console.log(response.headers.Authorization);
console.log(response.headers.get('Authorization'));
return data;}
you can see that response.headers.authorization return undefined and
response.headers.get('Authorization') return null.
and you can see in my browsers' Network panel
please anyone know how to get the authorization token from the headers?
When you are trying to login using API, then you should receive data i.e. Authorization token or anything else in the response of call.
Check what is the response you're getting when you called an API, it should probably be like
response.data
First you need to check the same in Postman.
To access value of response header server must return header name in Access-Control-Expose-Headers header. Without it Authorization is inaccessible in browser.
response.headers.get('Authorization')
Edit:
Since you are getting null, consider that:
The Authorization header is usually, but not always, sent after the
user agent first attempts to request a protected resource without
credentials.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
Therefore, instead of using postman, in order to see the response header, use the browsers' Network panel.
I have a js client (vuejs) and a backend using DRF both in local.
I use this package to generate the token : https://github.com/davesque/django-rest-framework-simplejwt
I use this package https://www.npmjs.com/package/axios-auth-refresh to handle refresh token logic.
The main goal is to intercept a request when it return a 401 response, perform a refresh token request and then resolve the orginal request with the new token.
It works when the original request is a GET request but not when it is a POST request.
When using a POST request :
The orgin request fall in 401 when the token expire then the interceptor occur but the server respond with 405 method not allowed:
-https://imgur.com/C1tchvb
the method from the request from the interceptor does not match the method in the code shown above (line 3 & 4) : as you can see the server receive the payload from the origin request as method of the request :
-https://imgur.com/nlAknMi
I found this post : App Script sends 405 response when trying to send a POST request
i try to change the headers as advised but it did not work
How is the payload from the orginal resquest becoming the method of the interceptor when the origin request is a Post request with a payload ?
Here the code from the javascript client :
const refreshAuthLogic = failedRequest => axios(
{
method: 'post',
url: 'auth/refresh',
data: { refresh: store.state.token.refresh }
}).then(tokenRefreshResponse => {
store.dispatch('refreshToken', tokenRefreshResponse.data)
return Promise.resolve()
})
const instance = axios.create({
baseURL: '/api/'
})
instance.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${store.state.token.access}`
return config
})
createAuthRefreshInterceptor(instance, refreshAuthLogic)
EDIT
I manage to get it work but i don't really understand:
the problem is related to DJANGO/ DRF and not axios
it seems that when a POST request is done and fail ( here with 401) the server keeped the data.
Here the part i can't explain :
when the request of the interceptor (to refresh token) hit the server, it messes with the data of previous request.
I had to add a middleware in django to clear the body when the request fails with 401 and it worked for me. But it is not a proper solution i guess.
Unfortunately the lib is loosely mantained and it's flawed in some aspects.
Eg: concurrent requests are not correctly queued when the request is sent with and invalid token but the response arrives when a new token is already issued.
As is, if you look at the lib source, you'll find in the very first lines:
/** #type {Object} */
const defaults = {
/** #type {Number[]} */
statusCodes: [
401 // Unauthorized
]
};
This means that only 401 code is managed and the statusCodes are not exported so them remains private.
If you want to continue to use this library you can fork it in order to change what does not fit with your stack or simply copy the source, edit it and use it as a local service.
I want to send an api key for every request I make:
function MyService($http) {
var req = {
method: 'GET',
url: 'https://api.giphy.com/v1/stickers/trending',
headers: {
'api_key':'123'
}
}
return $http(req);
}
but the problem is that all requests are OPTIONS (not GET) and is not sending the api_key. Is that the right way to send headers? thanks
Editing because it was marked as duplicate:
This is not a CORS issue. The error I´m getting is 401. That means authentication failed because the endpoint is not receiving the request header with the api_key.
What you did is totally fine, but if the api_key is always different, so you have to provide the api_key value dynamically in order to be added to the request.
If it is always the same, you have a really better way to do that: through interceptors. And you will set that only one time. Again, this method is if you have to set up some parameter which is always the same, so actually it is for doing standard operations over HTTP requests.
First, you need to define your Interceptor:
myApp.service('MyRequestsInterceptor', [function() {
this.request = function(config) {
config.headers.api_key = 'My Default API KEY';
return config;
};
}]);
And then simply add your interceptor to AngularJS $httpProvided:
myApp.config([ '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('MyRequestsInterceptor');
} ]);
Hi I am in developing Angularjs web application. I am using API's to get data. On login successful i will get some data in cookie(response header). In very next subsequent http calls i need to send that back cookies data to apis. Below is the snapshot of response header.
Below is my sample $http call.
var req = {
method: 'POST',
url: savepersonaldetailsurl,
headers: {
RequestedPlatform: "Web",
RequestedLanguage: cookiePreferredLanguage
},
data: {
LoginId: LoginID
}
$http(req).then(function (response) {
//do something here
}, function (error) {
toastr.error($filter('translate')('Error Occured'));
});
On each http call i want to send cookie in header. May i know how this can be done in angularjs? Any help would be appreciated. Thank you.
One of the features of Cookies is that they're sent to the server with each request. Make sure that the domain the request is being made to is the same domain that set it or a sub domain.
The cookie is usually stored by the browser, and then the cookie is
sent with requests made to the same server inside a Cookie HTTP header
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
First store the value which comes from response in localstorage then secondly you can make a common global functions which set the value to localstorage and get the value and call that function on every request.
for example:-
headers: {
'Content-Type': 'application/json',
'Authorization': authfunction.getToken('AuthToken');
}
In this example i set the value in local storage named AuthToken and while passing it we get and set it.
I am trying to send a header which each HTTP for a ngResource (auth token in this case)
This somewhats works :
app.factory('User', ['$resource','$window',
function($resource,$window,liftHost, liftBasePath) {
return $resource('/api/users/:id',{},{
get: {
method: 'GET',
headers: {'token': $window.sessionStorage.token}
}
});
}]);
The problem with this code, is that after the first call, each GET request will have the same header value. It does not get re-evaluated. So if a users logs out, and then log backs in, this will change the value of $window.sessionStorage.token, but the request will be sent using the previous value of the token.
I have created a small plunker with $httpBackend mocks to illustrate it.
see : http://plnkr.co/edit/xYZM6wlDJ6CH2BPHLZAC?p=preview
Here is a Plunker with this working
I introduced a TokenService that is injected into the User and Session services. This is a bit cleaner than depending on the $window service. Also, I made the token an object rather than a primitive string. This allows the token to be passed around by reference rather than value.
app.factory('Token', [
function() {
return {
value: "a"
}
}
]);