I'm banging my head on a wall with this - I'm relatively new to working with APIs and have yet to do anything that requires authentication.
I'm stuck with sending a POST request to the API. The endpoint for creating a piece of content is:
/entity/node
I can send a successful POST request if I send the following:
headers: {
"Authorization": "Basic YWRtaW46MTIzcXdl", //admin:123qwe
},
The problem I am having is with Authorization. I'm specifying Basic and then an encoded string here, which is my admin login. So when hardcoded, I can post.
My question - when the user logs in correctly, I need the headers to be set so that all future post requests work. How can I do this in AngularJS?
I have tried passing a dynamically generated code:
"Authorization": "Basic " + auth,
where auth is a base64 encoded user:pass, but this does not work. My thinking is that this value needs to be stored somewhere for retrieval whenever a POST request is made. But how?
Call this once you have a token:
$httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
if (authToken !== null) {
var headers = headersGetter();
angular.extend(headers, 'Authorization: basic ' + authToken);
}
return data;
});
EDIT: Have not tested it, but it should be something like:
myApp.provider('authService', function() {
var authToken = null;
this.$get = ['$httpProvider', function($httpProvider) {
return {
configure: configure,
setAuthToken: setAuthToken
}
};
function configure() {
$httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
if (authToken !== null) {
var headers = headersGetter();
angular.extend(headers, 'Authorization: basic ' + authToken);
}
return data;
});
}
function setAuthToken(token) {
authToken = token;
}
});
and then inject authService
to your app config and call authService.configure()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With