Spring + Angular / IE gets 403 on PUT (others don't) - angularjs

I have a spring webapp with spring security(3.2.3, so no CSRF protection) and angular.
In a controller i have a method like this one to update the users pw:
#RequestMapping("/accountinfo/password", method = arrayOf(RequestMethod.PUT))
#ResponseBody
#Secured("ROLE_USER")
open fun updateOwnPassword(user: User, #RequestBody password: String) {
val editedUser = user
editedUser.password = encoder.encode(password)
userRepository.save(editedUser)
}
The request is done via angular Service:
function changeOwnPassword(newPassword) {
return $http
.put('accountinfo/password', newPassword)
.then(function (response) {
return response.data
});
}
This works fine in every browser i tested with. Except if using IE 11.0.35 in a Citrix environment (Works outside of it,but can't see any specific configuration).
In that case i get 403 on the Request. When i change the method to POST it works fine again. I could do that for every function where i got this problem of course, but that doesn't seem like a clean solution.
As far as my research goes, i think it's something wrong with the way the browser writes the Request, but that's were i can't find out what to do.
EDIT:
I compared the request headers of both IE 11.0.35 inside and outside of Citrix and they seem exactly the same. The only difference is that the working version uses DNT=1 and the non-working version as WOW64 in the User-Agent attributes?
UPDATE:
I found out that it happens with DELETE too

Found the problem: The client sends the Requests through an additional Proxy that doesn't like PUT and DELETE and just cuts the session cookies off of it. We are adressing that problem with putting the tokens in the header in the future.

Related

CSRF Validation Failed in Drupal 7

I've been searching and searching, including the many topics here, for a solution to my problem. I've had no luck thus far.
A bit of a backstory: I'm writing an AngularJS app with Drupal 7 as a backend. I'm able to login without problem, save Session Name and Session ID, and put them together for a Cookie header (I had to use this "hack"). Further, if I made a login call in the Postman app, then tried to update the node, it'd work. It makes me think that there's a problem with session authentication, but I still can't figure it out.
That being said, I'm at a roadblock. Whenever I try to PUT to update a node, I get the following error:
401 (Unauthorized : CSRF validation failed)
Now, my ajax call looks like this:
$http({
method: 'PUT',
url: CONSTANTS.SITE_URL+"/update/node/"+target_nid,
headers:{
'Content-Type': CONSTANTS.CONTENT_TYPE,
'Authentication': CONSTANTS.SESS_NAME +"="+CONSTANTS.SESS_ID,
'X-CSRF-Token' : CONSTANTS.TOKEN
},
data: {
(JSON stuff)
}
})
The CONTENT_TYPE is "application/json", the "Authentication" is the band-aid for the Cookie header problem, and the "X-CSRF-Token" is what is (presumably) giving me the problem. SESS_NAME, SESS_ID, and TOKEN are all gathered from the response at Login. I can pull lists made by users on the website, I can pull the list of all of the nodes of a certain type on the website as well. I only run into a problem when I attempt to PUT to update the node.
If I missed any information, let me know and I'll add it!
EDIT: I'm using AngularJS version 1.5.3.
After trying everything else, I followed one of the comments in the thread I linked at the beginning of my original post. They had to comment out a line in Services.module :
if ($non_safe_method_called && !drupal_valid_token($csrf_token, 'services')) {
//return t('CSRF validation failed');
}
It's around line 590, plus or minus a few depending on how much you've messed with the file. I don't like doing it this way, but I can't for the life of me figure out why the token's not working right. It's a temporary fix, for sure, but if someone runs across this with the same problem in the future it'll hopefully help you out!
Instead of removing the line you could also add a true to drupal_valid_token
if ($non_safe_method_called && !drupal_valid_token($csrf_token, 'services',true)) {
return t('CSRF validation failed');
}

http-auth-interceptor is not settings the headers correctly

I have 2 issues using http-auth-interceptor. Let talk about the first one.
When the API return 401 (for the first time), the application is catching the event event:auth-loginRequired within a directive present in the index.html and display the modal so the user can login. Then on authentication success, the login script is calling authService.loginConfirmed(user, httpConfigCallback()). In the callback I'm setting 2 HTTP headers in order to update the API token. The problem is that I cannot see the header set when the initial request is dequeued. Here is my code:
$scope.user = UserAuthService.getUser();
// User is now auth, we confirm it
authService.loginConfirmed($scope.user, function(config){
config.headers["API_USER"] = $scope.user.guid;
config.headers['API_TOKEN'] = $scope.user.api_token;
return config;
});
But the header is not set:
The second issue I have is that the dequeued request is returning a 401, but the directive is not catching it anymore and so it's not displaying the login screen.
It's working well. The request header screenshot was the one from the OPTIONS request. It was denied by my server because I did not allowed my additional headers. I've added this:
$response->headers->set('Access-Control-Allow-Headers', "Origin,X-Requested-With,Content-Type,Accept,API_USER,API_TOKEN");
Now everything is working well.
Thanks
I suggest to use Angular interceptors to set your config headers.
Aa example: UserAuthInterceptor

Making calls from the Javascript client library with #Named and unnamed parameters makes no sense

I have a Cloud Endpoints method that looks like this:
//HTTP POST
#ApiMethod(name = "hylyts.insert")
public Hylyt insertHylyt(#Named("url") String url, Hylyt hylyt, User user)
throws OAuthRequestException{
log.info("Trying to save hylyt '"+hylyt+"' with id '"+hylyt.getId());
if (user== null) throw new OAuthRequestException("Your token is no good here.");
hylyt.setArticle(getArticleKey(url, user));
ofy().save().entity(hylyt);
return hylyt;
}
I call it from the Javascript Client Library using this:
gapi.client.hylytit.hylyts.insert({PARAMS}).execute(callback);
Now, if I structure {PARAMS} as suggested in the docs (second example),
{
'url': url,
'resource': {
'hylyt': {
'contentType': 'application/json',
'data': hylyt
}
}
}
I get a null object in the endpoint (not to mention that the whole point of this library is to make these calls simple, which this structure clearly violates).
When I structure {PARAMS} as these answers suggest,
{
'url': url,
'resource': hylyt
}
I get a null object in the endpoint again. The correct syntax is this:
{
'url': url,
'id': hylyt.id
'text': hylyt.text
}
Which just blows my mind. Am I doing this all wrong? Is this a bug? Is it only happening because gapi is also passing the auth token in the background?
Yes, I could use the request syntax instead, but, again, why even use the library if it's just as complex as making the XHRs in pure javascript? I wouldn't mind the complexity if Google explained in the docs why things are happening. But the docs, paraphrased, just say use these methods and the auth, CORS, and XHR magic will happen behind closed doors.
Is the API method correctly recognized as POST method?
The resource parameter which is sent as POST body won't work correctly in a GET request.
The way it looks you are actually sending a GET request with the Hylyt properties in the query string.
To make sure you can change the method annotation to this:
#ApiMethod(name = "hylyts.insert", httpMethod = HttpMethod.POST)
Yup, agreed it's a bug. caused me great pains as well.
So i guess the work around is to create a combined object to pass to your api all named and un named parameters. Rather than hardcode each.. a quick loop might be better.
var param = {};
param["url"] = url;
for (var prop in hylyt) {
param[prop] = hylyt[prop];
}
gapi.client.hylytit.hylyts.insert(param).execute(callback);
That mashing together of parameters / objects can become a slick function if you really want.. but it's a band aid for what I'd consider a defect.
I see in the related question (cloud endpoints resource attribute for transmitting named params & body not working), you actually logged a defect.. Good stuff. Though there still appears no movement on this one. fingers crossed for someday!
The bug has been resolved. The correct syntax is
gapi.client.hylytit.hylyts.insert({url: url}, hylyt).execute(callback);

angular $resource works with IIS express but not IIS ? I think something is wrong with the PUT?

I have isolated the problem down to a few lines. With IIS express it calls the PUT on the web API. When I switch to using IIS with the same code the call to the PUT method never happens.. The GET call works with both just fine.. any idea?
$scope.save = function (msa) {
$scope.msa = msa;
var id = this.msa.PlaceId;
Msa.update({ id: id }, $scope.msa, function () {
alert('finished update'); //only gets here with iis express
$scope.updatedItems.push(id);
$location.path('/');
});
}
MsaApp.factory('Msa', function ($resource) {
return $resource('/api/Place/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
EDIT 1:
I thought it was working but now it only works when 'localhost' and not the computer name.. it is not calling the server method.. any ideas what things to look out for that make the site act differently from localhost to ? .. and even stranger.. the angular site wont load in IE.. but it loads in chrome
EDIT 2:
I think I have the answer.. The dewfault webapi PUT/UPDATE creates invalid code.. It sort of randomly would breaking at db.Entry(place).State = EntityState.Modified... I found code here that seems to fix it so far.. not exactly sure what it does though
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key
Remove WebDAV module from IIS, it should work
IIS does block some of the actions by default, I believe PUT is one (DELETE is another).
See: https://stackoverflow.com/a/12443578/1873485
Go to Handler Mappings in your IIS Manager. Find ExtensionlessUrlHandler-Integrated-4.0, double click it. Click Request Restrictions... button and on Verbs tab, add both DELETE and PUT.

DOM Exception 18 in Awesomium

I have a webpage being loaded from the local file system and rendered using awesomium, the page is using AngularJSto render part of the page. However, I have a problem with part of my AngularJS controller generating a Dom Exception 18:
angular-1.0.0rc10.js # line 5349 Error: SECURITY_ERR: DOM Exception 18
It seems this exception is caused by the presence of this code at the end of my AngularJS controller:
$http({method: 'GET', url: 'http://placeholdermetaserver.appspot.com/list?format=json&game=Heist'})
.success(function(data)
{
//Do stuff with data
});
Oddly enough everything is just fine if I use a straight XMLHttpRequest instead of the AngularJS $http object:
var request = new XMLHttpRequest();
request.onload = function() {
//Do stuff with data
};
request.open("GET", "http://placeholdermetaserver.appspot.com/list?format=json&game=Heist", true);
This exception is not generated when I simply load this page in chrome (off the local file system, same as awesomium).
What could cause this and how can I fix it?
The $http service includes some Cross Site Request Forgery (XSRF) countermeasures. I'm not especially familiar with Awesomium, so I'm not sure what security features it implements, but I'd consult the documentation (both of Awesomium and AngularJS) for more info.
http://docs.angularjs.org/api/angular.module.ng.$http
From the perspective of your server, this is prone to the textbook XSRF img tag attack if you ever send a GET request like:
"http://myapp.com/doSomething/somegame/12345"
From the perspective of your client, let's say you make a request like:
"http://myapp.com/doSomething/somegame/" + someId
A clever hacker might coax someId to be:
"#123.45.56.689/myEvilFakeJson.json"
In which case the request isn't made to your server, but instead some
other one. If you hard code the location of the request or are careful with sanitizing input, it probably won't be that much of a risk.

Resources