is there a way to tell if a request is an Angular (1.1.5) $resource request. I'm pretty much looking for a "Request.IsAjaxRequest()" method for this type of request.
I'm looking this as in the HandleUnauthorizedRequest of an overriden AuthorizeAttribute I need to set the context result to some json if an Ajax or angular request or something else if not.
I don't know well MVC3 but you can set a custom header for all request from AngularJS.
Then on server side you just have to get this header and do what you want with request from angular.
To have custom header in AngularJS just do this :
angular.module('myModule', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common["FROM-ANGULAR"] = "true";
}])
For use the X-Requested-With you have to do this too :
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
It's not set by default anymore because a lot part of the community have to delete this header to enable CORS request
Related
I've built a simple SignalR hub that lives within a WebAPI service, I've included all the required CORS attributes on both WebAPI and SignalR. My WebAPI endpoints are all working as expected but SignalR isn't.
I've tried all I can think of and all I can find online but nothing works, I already tried this answer, and this other to no solution.
My SignalR extension method looks like this
public static IAppBuilder UseSignalrNotificationService(this IAppBuilder app)
{
var config = new HubConfiguration();
config.Resolver = new HubDependencyResolver();
config.EnableDetailedErrors = true;
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR(config);
return app;
}
And I even tried adding the response headers on all requests using the Web.config but I allways get the same error:
XMLHttpRequest cannot load https://MyApplicationServer/notifications/signalr/negotiate?clientProtocol=1.5&access_token=&connectionData=. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'MyOriginService' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
After more research and fiddling with the server side of the problem, I ran into this answer and found the error to be with the client side of the request. according to this GitHub issue, the "withCredentials" parameter of the request is always set to 'true'. The solution was to call on the client the start method as follows:
$.connection.hub.start({ withCredentials: false }).done(function () { //... }
Are you changing the request somewhere with some kind of global interceptor? For some reason, the XMLHttpRequest starts with withCredentials:true and this is forbidden when the Access-Control-Allow-Origin is set to *.
What about setting the 'Access-Control-Allow-Origin' to 'http://MyApplicationServer'? It's safer than * and will remove your problem at source.
I am trying to use ajax in my laravel project. but it's showing me an error while dealing with ajax request like
POST http://localhost/hr_management/user/process-Requisition-Form 404 (Not Found)
can you please help me out?
Do you have a valid route entry for /hr_management/user/process-Requisition-Form in routes.php? If so, ensure that it uses post instead of get, for example:
Route::post('/hr_management/user/process-Requisition-Form', 'HomeController#processAjaxRequest');
If you're using a library like jQuery, for example, ensure you're specifying 'post'.
$.ajax({
url: '/hr_management/user/process-Requisition-Form',
method: 'post'
})
Make Ajax request in laravel 5.1
first register your route in routes.php
Route::post('/your/ajax/url','yourController#ajaxProcessFunction');
And make a ajax request with your favorite javascript library and don't forget to send X-CSRF-TOKEN in request header and valid request type.
Here is example for jQuery
$.ajax({
method:'post',
url:'{!!url('/') !!}/your/ajax/url',
data:yourdata
headers:{'X-CSRF-TOKEN':'{!! csrf_token() !!}'}
})
My current setup is AngularJS + Django 1.5 and I have completely thrown away the use of Django's template engine (ie. the backend is pretty much an API server).
Since I am not using the csrf_token template tag, Django, in turn, does not set and send the csrftoken cookie in response. As instructed by the official docs, the ensure_csrf_cookie() decorator should be used to force the decorated view to send the csrftoken cookie.
I have applied the ensure_csrf_cookie() decorator to the view, which serves the first GET request that my web client calls at bootstrapping. With that, my web client gets a hold of the CSRF token and henceforth is allowed to call unsafe methods (ex. POST) to the server.
The above setup works fine only if the CSRF token remains the same until the browsing session ends.
Question: Does Django's CSRF token get updated during the course of a browsing session? If 'yes', does that mean I would need to apply the ensure_csrf_cookie() decorator to all the views I have?
1) Does Django's CSRF token get updated during the course of a browsing session?
Looks like the CSRF token is unique per session, but it is based in my observations, I have no "official" source. With Angular.js I use the following code without problems:
angular.module('app', ...)
.config(function($httpProvider) {
var cookies = document.cookie.split(';');
var csrftoken = _.find(cookies, function(v) {
return v.trim().indexOf('csrftoken=') == 0;
});
if(csrftoken) {
$httpProvider.defaults.headers.common['X-CSRFToken'] = csrftoken.split('=')[1];
}
})
Since I serve the HTML from Django, by the time Angular bootstraps the cookie is already there.
2) If 'yes', does that mean I would need to apply the ensure_csrf_cookie() decorator to all the views I have?
You can try CORS instead if CSRF. Otto Yiu maintains the django-cors-headers package, which is known to work correctly with REST framework APIs.
Some (untested) ideas to apply ensure_csrf_cookie():
monkey-patch APIView
create a CSRFCookie mixin and add it to your views
apply ensure_csrf_cookie() to your base classes
Giving support to the #Paulo Scardine ideas of applying the ensure_csrf_cookie() (which I consider valid, and useful), I would like to add a new one possible solution to it, if you definitely have to ensure_csrf_cookie() in all your views. You could write a custom middleware, and implement the logic that is there inside the ensure_csrf_cookie. Something like this:
On your app.middleware.py:
from django.middleware.csrf import get_token
class EnsureCsrfCookie(object):
def process_request(self, request):
# Forces process_response to send the cookie
get_token(request)
and of courses on your settings file add the middleware to the MIDDLEWARE_CLASSES:
MIDDLEWARE_CLASSES = (
.,
.,
.,
'app.middleware.EnsureCsrfCookie',
.,
.,
.,
)
It is just one idea more to face this problem. I hope it can be useful for somebody in the future.
How do I set headers before letting breeze make a request?
Example: my service expects a certain key to be part of the request in
a header name 'x-service-key'. Till now, I was using jquery ajax and
amplify, so pretty easy to set up the header. Since I don't have any
control over the request that breeze is making, how do I pass extra
stuff like headers?
This question was posted by sujesharukil on our IdeaBlade forums. I am reposting the question and answer here since I think it will be useful to the Breeze Stack Overflow community.
As of Breeze 0.70.1 we now support for the ability to completely customize or replace any Ajax communication between the breeze client and the web service on the server.
The Breeze documentation on our Ajax support is still in progress, but hopefully the following will get you started.
To control the headers on every Ajax request that Breeze makes, you can execute the following code when your app first starts up.
var ajaxImpl = breeze.config.getAdapterInstance("ajax");
ajaxImpl.defaultSettings = {
headers: {
// any CORS or other headers that you want to specify.
"X-Test-Header": "foo2"
},
};
Alternatively, you can intercept the individual Ajax calls and add your headers selectively based on the request.
var ajaxImpl = breeze.config.getAdapterInstance("ajax");
ajaxImpl.defaultSettings = {
beforeSend: function(jqXHR, settings) {
// examine the jqXHR or settings and customize the headers accordingly.
jqXHR.setRequestHeader("X-Test-Before-Send-Header", "foo2");
}
};
A django web app needs to make ajax calls to an external url. In development I serve directly from django so I have a cross domain problem. What is the django way to write a proxy for the ajax call?
Here's a dead simple proxy implementation for Django.
from django.http import HttpResponse
import mimetypes
import urllib2
def proxy_to(request, path, target_url):
url = '%s%s' % (target_url, path)
if request.META.has_key('QUERY_STRING'):
url += '?' + request.META['QUERY_STRING']
try:
proxied_request = urllib2.urlopen(url)
status_code = proxied_request.code
mimetype = proxied_request.headers.typeheader or mimetypes.guess_type(url)
content = proxied_request.read()
except urllib2.HTTPError as e:
return HttpResponse(e.msg, status=e.code, mimetype='text/plain')
else:
return HttpResponse(content, status=status_code, mimetype=mimetype)
This proxies requests from PROXY_PATH+path to TARGET_URL+path.
The proxy is enabled and configured by adding a URL pattern like this to urls.py:
url(r'^PROXY_PATH/(?P<path>.*)$', proxy_to, {'target_url': 'TARGET_URL'}),
For example:
url(r'^images/(?P<path>.*)$', proxy_to, {'target_url': 'http://imageserver.com/'}),
will make a request to http://localhost:8000/images/logo.png fetch and return the file at http://imageserver.com/logo.png.
Query strings are forwarded, while HTTP headers such as cookies and POST data are not (it's quite easy to add that if you need it).
Note: This is mainly intended for development use. The proper way to handle proxying in production is with the HTTP server (e.g. Apache or Nginx).
I ran across this question while trying to answer it myself, and found this Django app:
http://httpproxy.yvandermeer.net/
...which is a little heavyweight for what I needed (recording and playback, requires a syncdb to add in model stuff). But you can see the code it uses in its generic proxying view, which is based on httplib2:
http://bitbucket.org/yvandermeer/django-http-proxy/src/1776d5732113/httpproxy/views.py
Am I right that you are asking about how to write view in Django that could accept incoming AJAX request, issue request to the remote server and then return received response to browser?
If so, then it's not really Django-specific question - remote calls could be done with Python's urllib2 or httplib, and then you just have to put:
return HttpResponse(received_response)
-- in your Django proxy-view. I assume no reponse processing here, because if it's just a proxy for AJAX call then JavaScript expects unprocessed data.