Laravel Forbidden Access when using Ajax - laravel

I installed a fresh Laravel App with authentication. I am using laragon. The login, registration, reset password pages are working fine. I created a profile controller for the user to edit profile. However, when submitting the form through Ajax, it gives me a Forbidden - You don't have permission to access / / /profile/edit_profile on this server..
class ProfileController extends Controller
{
//
function index()
{
return view('profile.index');
}
function edit_profile(Request $request)
{
$txt_midname = $request->input('txt_midname');
$txt_firstname = $request->input('txt_firstname');
$txt_lastname = $request->input('txt_lastname');
$extname = $request->input('extname');
$user = Auth::user();
$user->firstname = $txt_firstname;
$user->midname = $txt_midname;
$user->lastname = $txt_lastname;
if ($user->save()) {
return 'ok';
}
}
}
Here is also the route:
Route::post('/profile/edit_profile', 'ProfileController#edit_profile')->name('edit_profile');
and the view:
$('#btn_update').on('click', function() {
var btn_text = $('#btn_update').text();
var txt_firstname = $.trim($('#txt_firstname').val());
var txt_midname = $.trim($('#txt_midname').val());
var txt_lastname = $.trim($('#txt_lastname').val());
var extname = $.trim($('#extname').val());
$.post(baseUrl + '/profile/edit_profile', {
'_token': token,
'txt_midname': txt_midname,
'txt_firstname': txt_firstname,
'txt_lastname': txt_lastname,
'extname': extname
}, function(data) {
if (data == 'ok') {
window.location.reload();
}
})
})

You need to inject the csrf token to your request.
$.post({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/gallery/create/ajax',
data: {},
method: 'POST',
success: function(response) {
},
error: function(error) {
}
})
or if you want every ajax request inject the csrf token you can do this as well.
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});

It was my mistake. The problem is with my baseUrl in javascript. It should be var baseUrl = "{{url('')}}";instead of var baseUrl = '{{url('')}}';

Related

Django: How to send csrf_token with Ajax

I have my Ajax in a jQuery function:
btnApplyConfig.js:
$(".btnApplyConfig").click(function(){
var token = $("input[name=csrfmiddlewaretoken]").val();
// Some other vars I'm sending properly
console.log('token: '+token); //printing correctly
$("#"+frm).submit(function(e){
e.preventDefault();
console.log('Post method via ajax');
$.ajax({
url: '/ajax/validate_config',
type: 'POST',
data: {
'token': token,
//and other stuff I'm sending properly
},
dataType: 'json',
});
});
});
my Django view:
def validate_config(request):
token = request.GET.get('token', None)
#some other vars I've sent ok with ajax
data = {
#some vars
'token': token,
}
if request.method == 'POST':
item = MyClass.objects.filter(my_keyword=my_filter_values).update(my_ajax_values)
return JsonResponse(data)
All the data is being processed properly, the only problem for me is that I'm getting the following error:
Forbidden (CSRF token missing or incorrect.): /ajax/validate_config/
I've put some prints in view in order to check if vars are being sent properly, and yes they are.
How could I handle it?
I checked some tutorials but I couldn't find a solution so far.
A very simpler way
let cookie = document.cookie
let csrfToken = cookie.substring(cookie.indexOf('=') + 1)
$.ajax({
url: 'url/path',
type: 'POST',
headers: {
'X-CSRFToken': csrfToken
}
})
You can use this. You don't have to put anything in your view for it. It will automatically find it.
$.ajax({
url: ,
type: "POST",
data: {
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
// plus other data
},
dataType: 'json',
success: ,
});
You probably also want to add if request.is_ajax() to your view.
This was the solution that worked for me in this case:
Added this code before the Ajax code:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});

How to implement Antiforgerytokens with partial views in mvc4?

I am trying to implement antiforgerytoken in my project. I am able to implement it when making ajax call below.
function docDelete(id) {
var _upload_id = $("#docId").val();
var _comments = $("#name").val();
var forgeryId = $("#forgeryToken").val();
$("#dialog-form").dialog("open");
$.ajax({
type: 'GET',
cache: false,
url: '/DeleteDocument/Delete',
dataType: 'json',
headers: {
'VerificationToken': forgeryId
},
data: { _upload_id: _upload_id, _comments: _comments },
success: function (data) {
$('#dialog-form').dialog('close');
$('#name').val('');
$('#dvSuccess').val(data);
Getgridata(data);
}
});
}
above code works fine. But in some cases i am making ajax request as below.
var forgeryId = $("#forgeryToken").val();
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
headers: {
'VerificationToken': forgeryId
},
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}
Above code does not send any token to below method.
private void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToken = string.Empty;
string formToken = string.Empty;
string tokenValue = request.Headers["VerificationToken"]; // read the header key and validate the tokens.
if (!string.IsNullOrEmpty(tokenValue))
{
string[] tokens = tokenValue.Split(',');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken); // this validates the request token.
}
}
In layout.cshtml i have implmented code to get token.
<script>
#functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + "," + formToken;
}
}
</script>
<input type="hidden" id="forgeryToken" value="#GetAntiForgeryToken()" />
The variable tokenValue catching null each time. So what i understood is through headers i am not able to send token value. I tried many alternatives. So anyone suggest me how can i overcome this issue? Thank you in advance.
I tried as below still i am getting null value.
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
alert(token);
var forgeryId = JSON.stringify($("#forgeryToken").val());
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
cache: false,
headers: headers,
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}

Django Ajax Request still results to CSRF Token Missing or Incorrect

I tried all the documentation on Django and other answers here in StackOverflow but the result is still (CSRF Token Missing or Incorrect)
So here is my view in views.py:
class MyView(View):
#method_decorator(ensure_csrf_cookie)
def post(self, request, *args, **kwargs):
t = TemplateResponse(request, 'mytemplate.html', data)
t.render()
return JsonResponse({'html' : t.content, 'title' : data['title']})
and this is the ajax in my js file which is in a function for a click event:
$.ajax({
url: window.location.href,
type: 'POST',
data: data,
beforeSend:
function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
var token = $.cookie('csrftoken');
console.log(token);
xhr.setRequestHeader("X-CSRFToken", token);
}
},
success:
function(result) {
},
});
The first call is successful but the succeeding call leads to missing token.
For the debugging, I used console.log and it is returning a different token every click.
Add the below code in the script. This will send the csrf token in the request in each ajax request
1. This will allow to get csrf token
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
2. This will send csrf token on every ajax request
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
3.Now send your ajax request
$.ajax({
url: window.location.href,
type: 'POST',
data: data,
success: function(result) {
console.log(result);
},
});
For more information visit django official documentation

Angular Datatables use source object

With Angular Datatables I want to pre-load a JSON object with Ajax so that I can re-use the object elsewhere without doing another ajax request.
But how do I load this object into the datatable?
.controller('ResponsiveDatatableCtrl', function ($scope, $rootScope, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $state, $http) {
$scope.dataLoading2 = true;
var vm = this;
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.files.php"+data;
var headers = {'Content-Type': 'application/x-www-form-urlencoded'};
$http({
method: 'POST',
url: url,
headers: headers,
})
.success(function (response) {
$rootScope.globals.files = response;
$scope.dataLoading2 = false;
//console.log($rootScope.globals.files);
});
vm.dtOptions = DTOptionsBuilder.fromFnPromise($rootScope.globals.files)
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);
})
Ok I have attempted the following and it seems to call my code under success but then the table doesn't update?
vm.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: url,
type: 'POST',
headers: headers,
data: function(data, dtInstance) {
},
success: function(response) {
$rootScope.globals.files = response;
}
})
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);

ASP.Net MVC Checking Facebook Login status before executing code in the controller

I'm using Facebook JavaScript SDK to log in with Facebook,
the only problem is that the JavaScript code executed after the controller.
all i want is to check if the user logged in before going to the controller.
Any help?
This is the java script Code
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: '#Facebook.FacebookApplication.Current.AppId', channelURL: '#Request.Url.Scheme://#Request.Url.Authority#Url.Content("~/fbchannel.ashx")', cookie: true, xfbml: true, oauth: true });
FB.Event.subscribe('auth.login', function (response) { window.location.reload(); });
FB.Event.subscribe('auth.logout', function (response) { window.location.reload(); });
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
$.ajax({
url: '/Home/SaveAccess',
type: 'POST',
data: { A: accessToken },
success: function (data) {
},
error: function() {}
});
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
$.ajax({
url: '/Home/SaveAccess',
type: 'POST',
data: { A: accessToken },
success: function () {
}
});
} else {
}
});
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
i save the Access Token in a session, the problem is that this code executed after the controller code.
Didn't understand exactly what you wanted. Here's a solution for what I did.
You can call FB.getLoginStatus anytime to check if the user is connected or not.
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// user logged in and connected
}
});
You can also add this in the fbAsyncInit to check user status every time the page loads.

Resources