I set a cookie on ajax response call like this:
return response($response, 200)->cookie('xid', $token, 2*24*60);
The above creates a cookie like this (which is the token value, raw, non-encrypted):
You can see this when running this code in the view:
<script type="text/javascript">
var tid = "{{ Cookie::get('xid') }}";
var tid = "{{ $_COOKIE['xid'] }}";
</script>
I get the following output:
If I check the "laravel_session" cookie instead, the output is correct (it's encrypted):
Any ideas why the xid cookie is not being encrypted? There are no exceptions in the middleware.
Solved by adding the EncryptCookie class in the api middlewaregroups in the Kernel as per Laravel session cookie not encrypted when using AJAX
Related
I want to implement single sign on from my website(assume it as a.com) to vendor website(assume it as b.com)
My vendor is providing a service which will take user Id as input and returns token and cookies in response header. I need to call this service and redirect to vendor url with session token through post request and set cookies(which are received from service response).
In my code after making service call i am returning url and token to a jsp and cookies in httpservletresponse . Javascript in this jsp will autosubmit the form on page load to make post call. But when it is redirected, browser is not setting the b.com cookies in the request header.
Controller code :
#RequestMapping(value = "/sso", method = RequestMethod.GET)
public String ssoToVendor(final Model model, final HttpServletResponse response) {
/**
*Service call happens here and returns tok
*/
model.addAttribute("url","https:\\b.com");
model.addAttribute("tok",tok);
for (String cookie : cookies) {
response.addHeader("Set-Cookie", cookie);
}
return "dummyjsp"
}
JSP sample code :
<body>
<form id="redirect" action="${url}" name="redirect" method="POST">
<input type="hidden" name="tok" id="tok" value="${tok}"/>
</form>
</body>
<script type="text/javascript">
var redirect = document.getElementById("redirect");
redirect.submit();
</script>
I know that it is not possible to set cross domain cookies but some how there is another application which is implemented in c# is able to set those cookies.
Is there a way we can set b.com cookies in response header and that is created by browser and sent to b.com when redirected from a.com in java.
I can do GET requests, but when I do POST, in Chrome developer tools I see: "Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)"
I thought the problem is in Django's csrf_token, so I found this solution:
.config(function($httpProvider){
$httpProvider.defaults.headers.common['X-CSRFToken'] = CSRF_TOKEN;
});
In my index.html, in <head> I have:
<script>
CSRF_TOKEN = '{{ csrf_token }}';
</script>
But it still raises 500 error. Am I doing something wrong or the problem is not in csrf?
P.S. CSRF_TOKEN is declared before
<script src="{{ STATIC_URL }}lib/angular/angular.js"></script>
and other scripts.
I've figured out the problem.
Django by default appends slash to your URL. If you enter:
http://mydjangosite.com/page Django will redirect you to: http://mydjangosite.com/page/
Angular's $resource removes trailing slash (you can read about it on github: https://github.com/angular/angular.js/issues/992).
Django has APPEND_SLASH setting which uses HTTP 302 redirection to
append slash to urls without slash. This works with GET method but not
with others (POST,PUT,DELETE) because redirection cannot and will not
pass the data to the new URL
So, there are two options:
1) Use $http insread of $resource
or
2) In Django's settings.py add this line:
APPEND_SLASH = False
and in your urls.py remove all trailing slashes
simply escape the backslash like: /custom_api/get_nearest_hotels/:eventId\/
(From: http://pragmaticstartup.wordpress.com/2013/04/27/some-lessons-learnt-from-messing-with-django-and-angularjs/)
As you all know you need to dump dictionary in your HTTPRESPONCE object.
sometimes what happens, in your view; you try to dump something in to your dict that can not be serialized. that is python/django can not serialize that object.
the examples can be (FORM OBJECT), (MODEL OBJECT), etc
so you need to get those away.
context = {}
context['office_form'] = OfficeCompleteForm(request.POST)
this can not be serialized and you will get 500 error.
be free to add following data.
context['success'] = {"msg": "successfully updated. "}
context['error'] = {"msg": "error can not update. "}
and at last do not forget to call you response method like this.
return HttpResponse(json.dumps(context), content_type="application/json")
I am using the popular jquery cookie plugin to set a session cookie value via javascript like so:
function ChangeLoginUser(sel) {
var selectedUser = sel.options[sel.selectedIndex].value;
$.cookie("LoginUser", selectedUser);
location.reload(true); //refresh
}
This function is called after user selects from a site global drop-down box option.
Change the value on page1 - the cookie is set CookieName = Value1.
Go to page2 - The cookie is persisting correctly
Change the drop-down value to value2 - Fiddler now shows two cookies by the same name with both values like this:
CookieName = value2
CookieName = value1
I don't understand why this is happening. I need to keep only one cookie of this name. The new value is supposed to replace the old one.
Ok. It looks like the problem was with the cookie path. Each URL can have a separate cookie with the same name. The solution is to set the path to be domain wide like this:
$.cookie("LoginUser", selectedUser, { path: '/' });
or, if you need to narrow it down to only your application you can do it like this:
$.cookie("LoginUser", selectedUser, { path: AppPath });
where AppPath can be set in the beginning of your shared layout
<script type="text/javascript">
var AppPath = '#Url.Content("~/")'
</script>
I am trying to get the URL i see on my browser after i do an ajax request but the problem is that it changes the URL with the Ajax URL.
ex.
i am on domain.com/user/username
and the ajax URL that i call is in domain.com/posts/submit
when i echo $_SERVER['REQUEST_URI'] on the posts controller in submit function it will display the second URL and not the first... how can i assure and get the first inside the ajax function that its 100% valid and not changed by the user to prevent any bad action?
Thanks
There is HTTP_REFERER but I don't know if that works for javascript requests. Another problem of this: It won't work for all browsers.
You could try the following:
1.) As the user visits domain.com/user/username the current URL is saved with a token - let's say 5299sQA332 - into the database and the token is provided through PHP to Javascript
2.) The ajax request will send this token along with the other variables needed to the controller through POST
3.) In your ajax controller you search the database for the given token 5299sQA332 and there you have your first URL and you can be damn sure, that it hasn't been manupulated
:)
If I understand you correctly, you want to make sure the ajax call is coming from the page it is supposed to be on? In that case just pass a token with the call.
In the controller function set a token variable in session;
public function username() {
$this->session->set_userdata('ajax_token', time());
}
Then in the view with the js;
$.ajax({
url: '/user/username',
type: 'post',
data: 'whatever=bob&token='+<?php echo $this->session->userdata('ajax_token'),
success: function( data ) {
},
error: function( data ) {
}
});
Then in you form validation, do a custome callback to check they are the same.
Have you looked at CodeIgniter's Input Class ?
$this->input->get('something', TRUE);
i used javascript for it and it seems to work... hope not to have any problems in the future with it...
ps: i dont get why my other answer was deleted.. thats the answer anyway.
I need to know how to start a session by Ajax in Django. I'm doing exactly as described bellow, but it is not working! The request is sent correctly, but don't start any session. If a request directly without ajax it works! What is going on?
'# urls
r'^logout/$', 'autenticacao.views.logout_view'
'# view of login
def login_view(request):
username = request.GET.get('username', '')
password = request.GET.get('password', '')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse(user.get_profile().sos_user.name)
return HttpResponse('user invalido')
'# ajax in a html page
$(function(){
$.get('http://localhost:8000/logout/?username=usuario?>&password=senha', function(data){
alert(data);
});
You're not calling the login_view. You're ajax request is going to the /logout/ url which is calling the autenticacao.views.logout_view.
Also, The ?> after username=usuario doesn't look right in the your get url.
My guess is you should be doing something like http://localhost:8000/login/?username=usuario&password=senha. (but I'd need to see your login url mapping to be sure).
Also, you should be POSTing the login information and using HTTPS for security reasons, but that's a different issue.