I generate an app from hipster generator and create a new factory to call my services.
All the existing services are called with x-csrf token in the headers but when i try to make a Get or a Post with my factory, i get de error 401, Unauthorized
In my app config, i have this:
//enable CSRF
$httpProvider.defaults.xsrfCookieName = 'CSRF-TOKEN';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
This is my factory:
angular.module('jhipsterApp')
.factory('WalletsService', function ($http) {
return {
findAll: function () {
return $http.get('api/walletslist/').then(function (response) {
return response.data;
});
}
};
});
When i execute findAll function, i get this error:
[Error] Failed to load resource: the server responded with a status of 401 (Unauthorized) (walletslist, line 0)
The x-csrf is saved in cookies but how i pass it in the headers?
thanks
Look at SecurityConfiguration, /api/** requires authentication, so your endpoint requires it too. It's not a CSRF issue, it's just that you must be logged in.
If api/walletslist has to be public, you must do this in SecurityConfiguration
.antMatchers("/api/walletslist").permitAll()
Warning: order matters and make sure your authorizations URLs matches your angular services and REST controller request mappings. It's easy to forget a final slash character in one place.
Any reason why you want to use $http, why not using $resource like other JHipster services?
Related
I need to emulate some state in my developer utility, and for it I need to pass some special cookie to the http request which made via angular $http module.
Code for making http request looks simple:
if (condition){
var headers = getHeaders();
if (headers !== 'undefined'){
config['headers'] = headers;
}
}
return $http(config);
So looks like I should add some field to the this config. But I can't find any related data about this in $http docs.
I do not want to set cookie 'to the browser' becase I want to pass it only for some several requests performed asynchronously.
Is it real to nmake it with angular.js?
I have used CakePHP + AngularJS for the application
I have below code in Sevices file
test.factory('Dashboard', function ($http, $q) {
return {
userDirectory: function (){
return $http.get(hostName + 'dashboards/userDirectory.json');
}
}
});
The above code calls dashboards's controllers userDirectory function and return JSON data this is how it's work.
Some one raised one issue, When he hit url "http://hostname/dashboards/userDirectory.json" he can see the response data in browser and that is not authenticated. Is there any way through which I can secure it.
By any encoding/decoding or What you prefer.
Decode/encode doesn't make any sense here if the client can decode it the user can get the data as well.
Just send data the user is allowed to see and use, even if he is authorized for that request, remove everything else that is not needed.
Use a JWT token to authorize them
https://github.com/ADmad/cakephp-jwt-auth
http://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/
http://florian-kraemer.net/2014/07/cakephp-and-token-based-auth-with-angular-js/
I am making a web service call using -
$http.get(url)
Note -
1) I am dynamically creating the url with query strings.
2) When i type the url in the address bar, it asks for login credentials.
Question -
1) How to add the login credentials in the url, while i am creating it dynamically? I know this is a not a good idea, is there a better way to deal with this situation?
2) I am getting the data from the $http call. Is it because i have logged in once before and the same session is continuing?
Is it standard HTTP credentials? If so, you can use the config flag
withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.
Your service:
app.service('myService', ['$http', function($http){
var service = {};
service.getUrlWithCredentials = function(url){
return $http(url,
{
withCredentials : true
}
}
return serivce;
}])
Taken from:
https://docs.angularjs.org/api/ng/service/$http
To overcome csrf attack, I have to send in csrf-token value in a header for every request by picking in the value from cookie as described here. Since this is to be done at every request, I am setting the default headers for $http in the main module's run function.
Now, If a new tab is opened for the same website, a new csrf token (in cookie) is issued by the server. Since the run function is run only once, the default header for csrf will be old one (for old tab), while the new csrf cookie will be sent to server, resulting in csrf-mismatch.
How to overcome this at a global level?
I want somehow to create a function which will be run everytime the $http is called, so that then I'll override the default headers.
Note: I do not want to set this header value for every $http request.
(Not that I think that it's relevant, but I'm using ui-router)
Edit
This is not just limited to csrf-token, I want to set some other headers too based on the logged in user, which has to be done dynamically (say when one user logs in, and logs out, then another user logs in).
you need to use http interceptor to do this on every request. read more about http interceptors here
below is one such example
module.factory('xsrfTokenInterceptor', function ($q, $http) {
return {
'response': function (response) {
var cookies = response.headers("Set-Cookie");
var token = someCrazyParsing(cookies);
$http.defaults.headers.common["X-CSRFToken"]=token;
return response || $q.when(response);
}
};
});
module.config(function($httpProvider){
$httpProvider.interceptors.push('xsrfTokenInterceptor')
})
How about headers $http(config) parameter.
$scope.getWithHeader = function(){
$http({
method: 'GET',
url: 'http://fiddle.jshell.net',
headers: {
'CustomHeader': 'HelloWorld'
}
}).success(function(){
console.log("success");
});
};
sample code on jsFiddle
I'm developing web app with angular.js, I'm currently a little confused about what's the proper way to handle errors. In my app, I have used ngResource to call rest API of server. So I'll have a lot of ngResource api calls.
e.g. user resource, there're user.query( ), user.get( ) , user.save( ) ......
Do I suppose to put an error callback into all of the ngResource api calls?
Just to handle all kinds of errors: like server down or no internet access ??
I just don't think put an error callback in every ngResource api call is a good idea. That'll produce a lot of redundant code and make my code not neat .
What will you do to handle various error types?
You can use an interceptor and do whatever you want when an error occured :
var app = angular.module("myApp", []);
app.config(function ($provide, $httpProvider) {
$provide.factory('ErrorInterceptor', function ($q) {
return {
responseError: function(rejection) {
console.log(rejection);
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('ErrorInterceptor');
});
With this interceptor you can read the status code and do what you need (a perfect use case is to redirect your user to a login page if status code is 401).
Since ngResource use $http, your interceptors will also be executed when you call a resource method.
Of course, you can do more and add an interceptor before / after a request is made.
See the full documentation here : http://docs.angularjs.org/api/ng.$http
See this fiddle : http://jsfiddle.net/4Buyn/ for a working sample.