I have one GET endpoint.
It has HTTP Basic Authentication enabled. I want to create a GET request to the given end point.
https://example.com/api GET
User Name :- admin
Password :- admin
My Code :-
$scope.listData = function() {
$http.get('https://example.com/api').then(function(response) {
$scope.items = response.data;
});
}
What is the recommended way to pass the authentication?
Second argument for the GET is the header part. For ex.
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}).then()..;
the recommended method is http-interceptors.
what interceptor do, you can assume its a hook which call on every api request and response, once you write it, it will automatically add token in every api request. below is the url you read the article.
Angular Authentication: Using the Http Client and Http Interceptors
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.
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 new to Angularjs and wondering how to check the token's expire date and time before sending any request.
I googled and found there are concepts like interceptors and decorators in angular but I am a bit confused which one to use and how. Or is there any better way to do it.
What am I doing right now?
I have created a service that has GET, POST functions take url, data and config as parameters and there I am checking the token. I know this is not the right approach.
You can use an interceptor that will configure every $http call. enter link description here
You can write interceptor which will cancel invalid token request before it is actually sent:
return {
'request': function(config) {
if (condition) {
var canceler = $q.defer();
config.timeout = canceler.promise;
canceler.resolve();
}
return config;
}
}
Obviously, you can manipulate config before returning it and (for example) change token.
I have successfully logged in to the API Server using following code in meteorjs
var request = Npm.require('request');
request('http://api-server-link-here',
{
'auth' : {
'user': 'username',
'pass': 'password',
'sendImmediately': false
}
}
, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response);
}
But after this login when i go for using search query using code below. I get Http Status 401 error.
var request = Npm.require('request');
request("http://search-query-link-here",
{
//search query parameters are here
},
function(error,response,body){
console.log(response);
});
Can anybody please give me pointers of why this issue is happening. Or if this is possible that i get a working example here?
One more thing that needs to be told here is that I'm doing login with the help of digest authentication.
Obviously, it's kind of hard to provide you with a working example for an unknown API.
But let's just try to sort it out. Logically, when you send your search query, you are supposed to identify yourself. Most of the public API servers use either tokens (most probably) or session cookies in order to authorize access to a resource. So, whenever you do your second (search) request, you have either provide a token or send a cookie you are getting from the first (login) request.
Long story short, verify which mechanism is being used by the API server.
if it's tokens: check the response body from the login request; most probably there will be an access token you'd send then in the Authorization header of your API calls: headers: {'Authorization': 'Bearer ...'} in your request options;
if it's sessions: make sure you have the cookie jar enabled on login and you it for subsequent requests: https://github.com/mikeal/request#requestjar