I am trying to send token in the header but it is not working, what is the way of sending token in the header? Or what is the problem in my code?
return $q(function(resolve , reject){
var token = StorageService.getToken();
if(!token)
console.log('no token')
var resource = $resource(usersAPI.profile,null,
{
query: {
method: 'GET',
header: {
'Authorization': 'Bearer ' + token
}
}
})
var profile = resource.query(function(result){
console.log(result)
},function(err){
console.log('error',err)
})
resolve(profile)
})
Related
I have download text file request from backend. I need to download the file by posting get request given in service.js but the problem is I am getting %7d %7d in blank when I am downloading the file. Need assistance.I even tried with ng-href, still no luck
HTML:
<button class="btn btn-info" ng-click="downloadAllExhibitors();">
Download</button>
JS:
$scope.downloadAllExhibitors = function () {
$scope.newFile = service.downloadExhibitor();
}
Service.js
var url =' http://localhost/1290/';
function downloadExhibitor() {
var token = 129821sahh;
var auth = "Token" + ' ' + token;
var config = {
headers: {
'Content-Type': 'application/json',
'Authorization': auth
}
}
return $http.get(url + 'entity/campaigns/download_exhibitors/', config);
}
The problem with your code lies in
$scope.newFile = service.downloadExhibitor(); Since $http.get is async and returns a promise, you can always define callbacks to handle the success/error response from server.
So, by the time your server returns the response you have no actions defined to handle it. Your service can be re-written as :-
var url =' http://localhost/1290/';
function downloadExhibitor() {
var token = 129821sahh;
var auth = "Token" + ' ' + token;
var config = {
headers: {
'Content-Type': 'application/json',
'Authorization': auth
}
}
return $http.get(url + 'entity/campaigns/download_exhibitors/', config)
.then(successHandler, errorHandler);
}
function successHandler(response){
/* we've got file's data from server */
return response.data;
}
function errorHandler(error){
/* we've got error response from server */
throw new Error('ERROR ' + error);
}
and eventually the service invocation
$scope.newFile = "";
service.downloadExhibitor()
.then(function(data){
$scope.newFile = data;
}, function(error){
console.log(error);
});
This is my angular configuration for appending keycloak token with every HTTP request.
module.factory('authInterceptor', function($q, Auth) {
return {
request: function (config) {
var deferred = $q.defer();
if (Auth.authz.token) {
Auth.authz.updateToken(5).success(function() {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + Auth.authz.token;
deferred.resolve(config);
}).error(function() {
deferred.reject('Failed to refresh token');
});
}
return deferred.promise;
}
};
});
module.config(["$httpProvider", function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}]);
This is the request I sending to the backend. It seems the request not adding keycloak token, so I'm getting 403 forbidden error.
var formData = new FormData(file);
formData.append('file', file);
return $http({
method: 'POST',
url: API_BASE + '/uploadEmployeeDetails/excelUpload',
headers: {
'Content-Type': undefined
},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
});
Backend security config
Since you are able to send the token to the back-end as you can see from the network tab of the browser.
The issue is in the api side on handling the csrf token
If the csrf token is enabled by default you should disable it.
Here is the code with your help, to disable it
http.csrf().disable();
http.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
.authorizeRequests().antMatchers("/**")
.hasAnyRole("ORG_ADMIN", "EMPLOYEE", "PARENT", "STUDENT")
.anyRequest().permitAll();
I am newbie of angularJS. I want to add header in my http request but i am not understanding how? so far i've written this code.
Original code without header:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http.post(url, dataObj);
}
Now i am adding header to it, the code becomes like this:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http({headers: {
'Authorization': token
}}).post(url, dataObj);
}
By adding header, i am getting this error:
angular.js:14525 Error: [$http:badreq] Http request configuration url
must be a string or a $sce trusted object. Received: undefined
You're using the wrong syntax. Take a look at the angular documentation for $http here.
Your code should look like this:
$http({
method: 'POST',
url: __apiRoot + "/users/" + user.id,
data: JSON.stringify(user)
headers: {
'Authorization': token
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
This is my code but i am getting unauthorised(401) error,i have used CORS filter on server side but still i am not able to hit the API
var authdata = Base64.encode("username:password");
var data={};
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;',
'Authorization' : 'Basic'+ authdata,
'Accept':'application/json'
}
};
function fetchAllUsers(){
ViewRecord.fetchAllUsers(REST_SERVICE_URI,data,config)
.then(
function(d) {
self.users = d;
},
function(errResponse){
console.error('Error while fetching Users');
}
);
}
There needs to be a space after Basic in the authorization header.
// Bad
'Authorization' : 'Basic'+ authdata,
// Good
'Authorization' : 'Basic '+ authdata,
I am want to connect api with mvc site using oauth authentication.
for this, i need to send access token through http request as below.
addPostComment: function addPostComment(postid, UserId, comment, accessToken) {
var request = $http({
method: "post",
url: apiPath.addPostComment,
data: {
SocialPostId: postid,
CommentDescription: comment,
CommentedUserId: UserId,
CommentedDate: new Date()
},
params: {
action: "post"
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'bearer ' + accessToken);
}
});
return (request.then(handleSuccess, handleError));
}
parameter accessToken have value.but while i set as request header, it always says Authrization: Bearer undefined.
Can anyone tell me what is wrong in this code?
$http({
method: "post",
url: apiPath.addPostComment,
data: {
SocialPostId: postid,
CommentDescription: comment,
CommentedUserId: UserId,
CommentedDate: new Date()
},
params: {
action: "post"
},
headers: {
'Authorization': 'bearer ' + accessToken
}
});
You Can send HTTP requests like this ...