how to pass authtoken via header using angular js - javascript

I am trying to pass my api authtoken via the header. I am new to angular js so i am not able to do that. My code:
$scope.init=function(authtoken,cityname){
$scope.authtoken=authtoken;
$scope.cityname=cityname;
$http({method: 'GET', url: '/api/v1/asas?city='+$scope.cityname+'&auth='+$scope.authtoken}).success(function(data) {
Right now I am passing the authtoken in the api url. But I want to pass the token via the header.

usually you pass auth token in headers. Here is how i did it for one of my apps
angular.module('app', []).run(function($http) {
$http.defaults.headers.common.Authorization = token;
});
this will add auth token to headers by default so that you wont have to include is every time you make a request. If you want to include it in every call then it will be something like this
$http({
method: 'GET',
url: '/api/v1/asas?city='+$scope.cityname,
headers:{
'Authorization': $scope.authtoken
}
}).success(function(data) {
//success response.
}).error(function(error){
//failed response.
});

You can configure on application run
youapp.run(function($http) {
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
});
or pass it throw each request
$http({
url:'url',
headers:{
Authorization : 'Basic YmVlcDpib29w'
}
})
Angular $Http reference

Related

I cannot request an Oauth 2.0 token in javascript

I am making a request for getting an access token with Oauth 2.0, in javascript. The docs of the API use the request module (deprecated), so I am searching for an alternative. I tried with fetch and axios, but none of them seem to be working.
You can read this from the docs.
If i make the request with axios (code) it returns this error,
while if I use fetch (code) this it the result.
At least fetch makes the call successfully, but I have the impression that he cannot pass the auth parameter, because the error is caused beacause of this.
May someone help me? I appreciate it a lot.
You can use fetch or axios instead of request, but they use different options attributes, compared to request.
With axios, it is
const options = {
method: 'POST',
auth: {
username: client.id,
password: client.secret
},
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: 'grant_type=client_credentials&scope=basic'
};
instead.
With fetch, it is
const options = {
method: 'POST',
headers: {
authorization: "Basic " + Buffer.from(client.id + ":" + client.secret).toString("base64"),
'content-type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=client_credentials&scope=basic'
};
You can use axios this way:
axios.interceptors.request.use(function (config) {
// Do something before request is sent
config[Authentiaction] = "Bearer" + token
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
I think this can help.

How to send Token to API in react native

Backend developer send me API like this To test it on poastman
http://app/channel_partner/patients/add?token=59bd1e3711ce73c150b68f3741df4363cf766a0e2fe54dcb5f804a08f3f0d525
But now How can I send token to API in react native I am sending like this but its Not working
let url = URLs.addLeads;
let options = {
method: "POST",
url: url,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
You've tagged this with axios so use the params config option to safely add URL query parameters to your request
const options = {
url: URLs.addLeads,
method: "POST",
params: { token }
};
This will add a token query parameter with a correctly URL-encoded value.
You don't need to change the headers; the Axios defaults already have you covered.

AngularJS Adding a header to the $http.get

I'm trying to add the 'Authorization' header containing a token for future HTTP request. Retrieval of the token seems to be fine however when making a get request it fails with an Unauthorized error message. After checking the request headers Authorization header does not exist in the request block...
window.crUtil = /*window.crUtil ||*/ (function() {
// Angular Services
var $injector = angular.injector(['ng']);
var $http = $injector.get('$http');
// getting the CFF data
function get_data() {
getJWTAWS();
var url = '/AWS/getDATA/555';
console.log('AUTH header before call: ' + $http.defaults.headers.common.Authorization);
$http.get(url,httpHeader).then(function successCallback(response) {
var data = response.data;
var cff = initCff();
alert(data.itemId);
}, function errorCallback(response) {
initCff();
alert("Error while getting data ");
});
}
function getJWTAWS() {
var httpConfig = {
cache: true,
params: {}
};
$http.get('/AWS/token', httpConfig).then(
function(response) {
if (response.data.accessToken) {
// add jwt token to auth header for all requests made by the $http service
$http.defaults.headers.common.Authorization = response.data.tokenType + ' ' + response.data.accessToken;
}
},
function(error) {
alert('jwt token could not be retrieved.');
}
);
}
})();
var result = util.get_data();
console.log ('called search function ' + result);
Function getToken() returns a value but as I'm new on that topic I'm not quite sure if the way I added the token to the headers is proper.
Could you please advise on the proper way to include the headers in the request. I also tried to add it to the get request like
$http.get(URL,httpHeaders)...
but it also didn't work.
I'm not sure I understand your problem completely as you did not provide what you call
httpConfig
If you're struggling to declare the headers, try making the get request like this:
$http({
method: 'GET',
url: YOUR_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': AUTH_STRING_HERE
}
}).then(function (response) { ... });
You can add any headers you like in the headers object there.
Try adding this in your config block and set the token in your rootscope
$httpProvider.interceptors.push({
request: function (config) {
config.headers.Authorization = $rootScope.token;
return config;
}
})

How to store authentication bearer token in browser cookie using AngularJS

I have created a bearer token using ASP.net Identity. In AngularJS I wrote this function to get authorized data.
$scope.GetAuthorizeData = function () {
$http({
method: 'GET',
url: "/api/Values",
headers: { 'authorization': 'bearer <myTokenId>' },
}).success(function (data) {
alert("Authorized :D");
$scope.values = data;
}).error(function () {
alert("Failed :(");
});
};
So I want to store this token into Browser cookies. If this token is present there , then take the token and get the data from IIS server Otherwise redirect to login page to login to get a new token.
Similarly, if user click onto log out button, it should remove the token from browser cookie.
How to do this ? It it possible ? Is it proper way to authenticate and authorize a user ? What to do if there are multiple users token ?
There is a $cookies service available in the AngularJS API using the
ngCookies module. It can be used like below:
function controller($cookies) {
//set cookie
$cookies.put('token', 'myBearerToken');
//get cookie
var token=$cookies.get('token');
//remove token
$cookies.remove('token');
}
controller.$inject=['$cookies'];
For your case it would be:
//inject $cookies into controller
$scope.GetAuthorizeData = function () {
$http({
method: 'GET',
url: "/api/Values",
headers: { 'authorization': 'bearer <myTokenId>' },
})
.success(function (data) {
$cookies.put('token', data);
}).error(function () {
alert("Failed :(");
});
};
You will also have to add the angular-cookies module code. And add it to your angular app: angular.module('myApp', ['ngCookies']);. Docs for Angular Cookies.
I would also like to suggest the usage of a Http interceptor which will set the bearer header for each request, rather than having to manually set it yourself for each request.
//Create a http interceptor factory
function accessTokenHttpInterceptor($cookies) {
return {
//For each request the interceptor will set the bearer token header.
request: function($config) {
//Fetch token from cookie
var token=$cookies.get['token'];
//set authorization header
$config.headers['Authorization'] = 'Bearer '+token;
return $config;
},
response: function(response) {
//if you get a token back in your response you can use
//the response interceptor to update the token in the
//stored in the cookie
if (response.config.headers.yourTokenProperty) {
//fetch token
var token=response.config.headers.yourTokenProperty;
//set token
$cookies.put('token', token);
}
return response;
}
};
}
accessTokenHttpInterceptor.$inject=['$cookies'];
//Register the http interceptor to angular config.
function httpInterceptorRegistry($httpProvider) {
$httpProvider.interceptors.push('accessTokenHttpInterceptor');
}
httpInterceptorRegistry.$inject=['$httpProvider'];
//Assign to module
angular
.module('myApp')
.config(httpInterceptorRegistry)
.factory('accessTokenHttpInterceptor', accessTokenHttpInterceptor)
Having the http interceptor in place you do not need to set the Authorization header for each request.
function service($http) {
this.fetchToken=function() {
//Authorization header will be set before sending request.
return $http
.get("/api/some/endpoint")
.success(function(data) {
console.log(data);
return data;
})
}
}
service.$inject=['$http']
As stated by Boris: there are other ways to solve this. You could also use localStorage to store the token. This can also be used with the http interceptor. Just change the implementation from cookies to localStorage.
function controller($window) {
//set token
$window.localStorage['jwt']="myToken";
//get token
var token=$window.localStorage['jwt'];
}
controller.$inject=['$window'];
I would advise against keeping the data in a cookie, for security purposes you should set the cookies to secure and HttpOnly (not accessible from javascript). If you're not using SSL, I would suggest moving to https.
I would pass the token from the auth endpoint in a json response:
{
tokenData: 'token'
}
You can save the token data in sessionStorage by using the $window service:
$window.sessionStorage.setItem('userInfo-token', 'tokenData');
It will be cleared once the user closes the page, and you can manually remove it by setting it to empty string:
$window.sessionStorage.setItem('userInfo-token', '');
Edit:
Interceptor implementation for catching data, adapted from cbass (not tested, you can inspect the objects for response/request to fiddle with the information):
//Create a http interceptor factory
function accessTokenHttpInterceptor($window) {
return {
//For each request the interceptor will set the bearer token header.
request: function($config) {
//Fetch token from cookie
var token=$window.sessionStorage.getItem('userInfo-token');
//set authorization header
$config.headers['Authorization'] = 'Bearer '+token;
return $config;
},
response: function(response) {
//if you get a token back in your response you can use
//the response interceptor to update the token in the
//stored in the cookie
if (response.config.url === 'api/token' && response.config.data.tokenData) {
//fetch token
var token=response.config.data.tokenData;
//set token
$window.sessionStorage.setItem('userInfo-token', token);
}
return response;
}
};
}
accessTokenHttpInterceptor.$inject=['$window'];

How can handle session state in angularJS with json api auth

I want to create a new post from mobile app using wp-rest api, in order to do this I have to logged in with a form; well, the authentication with json api auth works well I submit username and password and I enter; but, when I try to create a new post with wp-rest api I have this error :"You don't have permission to do this." It seems that I'm not logged in but I'm !!!
my code is this :
var data={"title":"Hello World!","content_raw":"Content","excerpt_raw":"Excerpt"};
$scope.register = function() {
$http({
method: 'POST',
url: 'http://url.com/provawp/wp-json/wp/v2/posts',
data: data,
headers: {'Content-Type': 'application/json'}
})
.success(function(data, status, headers, config) {
alert("Città aggiunta correttamente!");
})
.error(function(data, status, headers, config) {
}).
catch(function (error) {
alert("Erroreee!");
console.log("error : " + JSON.stringify(error) );
});
}
If you are using web tokens. You can put your token inside your http header by creating http interceptors
and also you use like this:
$http({
method: 'POST',
url: 'http://url.com/provawp/wp-json/wp/v2/posts',
data: data,
headers: {
'Content-Type': 'application/json',
'Authorization' : 'bearer Dfdsf54sdff#dfsdsfFF'
}
})
you contact you back end developer for this situation:
bearer and any other
Dfdsf54sdff#dfsdsfFF your Authorization token

Categories