ExtJS and Ajax with SSL (https) - extjs

I have an ExtJS application on top of a Django application, and I need to post to /accounts/logout/ in order to invalidate the session and then redirect to /.
The code below runs locally but fails on the live site, which has SSL. I have an issue with doing the Ajax POST via ExtJS. The code is the following:
Ext.Ajax.request({
url: '/accounts/logout/',
withCredentials: true,
method: 'POST',
success: function() {
console.log('successfully logged out');
window.location.href='/'
}
});
The response status in Chrome is (cancelled) as shown in this screenshot:
In addition I get this warning at console level:
The page at https://domain.example.com/ displayed insecure content
from http://console.pharmacy.com.mt/.
Am I missing some config object with the Ext.Ajax request above?

try removing withCredentials: true
Ext.Ajax.request({
url: '/accounts/logout/',
method: 'POST',
success: function() {
console.log('successfully logged out');
window.location.href='/'
}
});

Related

Microsoft Graph API: Access Token 403 Forbidden error Using ajax call but works properly using postman

When I try to make a rest call from postman I am able to get access token but using ajax call I am getting 403 forbidden error. Appended https://cors-anywhere.herokuapp.com/ url to access token url to avoid CORS error.
const formData = new FormData();
formData.append("client_id", "client_id");
formData.append("client_secret", "S7D7Q~excS5KjBh9JnPK-afZjTjtALGTKNweP");
formData.append("grant_type", "client_credentials");
formData.append("scope", "https://graph.microsoft.com/.default");
$(document).ready(function () {
requestToken();
});
var token;
function requestToken() {
$.ajax({
async: true,
crossDomain: true,
credentials: "include",
url: "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/b262d1f3-4738-400d-ad54-c82cdabb6540/oauth2/v2.0/token",
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded"
},
cache: false,
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
token = response.access_token;
},
});
}
You should not use a client credential in your front-end. That's your application's password and will be visible to anyone visiting the page. Also if that is your actual secret in the question, you should remove it and create a new one.
This URL will not work:
https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/b262d1f3-4738-400d-ad54-c82cdabb6540/oauth2/v2.0/token
The reason you get a CORS error is because Azure AD is trying to prevent you from shooting your own foot.
AAD sees the request and thinks it should not come from a browser front-end and thus denies it.
The correct way to get the token is to use MSAL.js and acquire a token on behalf of the signed in user (delegated permissions).

CSRF cookie not set [Django/AngularJS]

First of all, this is not a duplicate question. I have tried all the related posts on stackoverflow but could not find a solution.
I have a Django app for the backend and and AngularJS app for the frontend. I am using djangorestframework-jwt for API authentication. I have an API endpoint that does not require any authentication and I am getting CSRF Failed: CSRF cookie not set error on the browser only for this endpoint.
In my django settings I have:
ALLOWED_HOSTS = ['*']
and it does not include any CSRF_COOKIE_SECURE, CSRF_COOKIE_HTTPONLY, or SESSION_COOKIE_SECURE settings.
The djangorestframework-jwt settings is:
JWT_AUTH = {
'JWT_SECRET_KEY': SECRET_KEY,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000),
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_AUTH_COOKIE': 'refresh-token'
}
I noticed that in the browser cookies if there is any refresh-token key then the endpoint works just fine. The problem arises when that key is not present in the browser cookies. I set 'JWT_AUTH_COOKIE': None or removed the following lines:
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_AUTH_COOKIE': 'refresh-token'
from the JWT_AUTH settings but no luck.
I also tried #csrf_excempt for that endpoint but that did not work either.
Interestingly, when I send the request from postman it works.
Here is the request I am sending from the frontend:
$http({
url: url,
method: "PUT",
headers: {
'Content-Type': 'application/json'
},
data: data
})
I would like to know why I am getting the error when refresh_token key is not present in the browser cookies and how to solve this issue.
I solved my issue by adding 'X-CSRFToken': $cookies.get("csrftoken") to the Http request header, so the request now look like:
$http({
url: url,
method: "PUT",
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': $cookies.get("csrftoken")
},
data: data
})

Send cookies in ajax angular

I want to send the document cookie in the http call in angular.
I have already used withCredentials but it can only send the browser level cookie.
I also use the cross domain ,but it is not working fine.
Below is the code which I am using.
$http({
method: 'GET',
url: url,
xhrFields: { withCredentials: true },
crossDomain: true,
header:{ 'SHOPSESSIONID' : sessionStorage.getItem("SHOPSESSIONID") }
}).success(function(data){
return data;
}).error(function(data){
return data;
});
use $httpProvider in config phase:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}])
and you could give up the xhrFields and crossDomain proporties
btw, angular uses then instead of success, and catch instead of error. (that is the promise syntax)

Token authorization - Browser throws Login form

I am working on a token implementation into Angular/.Net application. My part is the front-end. What's happening is that when UI sends a request with the expired token and the server replies with 401 I cannot intercept that before the Browser raises the Login form. As the result I cannot send a request to refresh the token. Can someone please give me an idea how that is supposed be managed? I will provide code just don't know what's to show.
Thanks
Adding code:
var response = $http({
method: "GET",
dataType: "json",
params: params,
headers: {
'Content-Type': "application/xml; charset=utf-8",
},
url: someurl
});
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
The problem is that I cannot redirect on UI because Browser throws Login form before my code is hit when the server returns 401.
Make ajax request, and if you get 401 then redirect to login page.
P.s. for better understanding provide your code how you implement ajax request. Which module do you use for front-end auth? I recommend satellizer
Added:
I guess you need the following configuration on angular
var app = angular.module('App', ['satellizer'])
.config(function() {
/* your config */
}
.run(function($rootScope, $location, $auth) {
// Check auth status on each routing,
// Redirect to login page, if user is not authenticated or if token expired
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$auth.isAuthenticated()) {
$location.path('/auth/login');
}
});
});

Status Code 302 found on POST request using Angular, Revel and Go

I am using Revel + angular for my application. The index page is the login interface, and once you are successful, you should be directed to the dashboard.html page. The problem is once I have made a POST request, I get a GET request with my 'response body', however, I am still in the login page. I am using angular to make a post request to my restful server. However, whenever I make a POST request I get status 302 on my POST request but my GET request fetches the response for the page.
My Angular Controller
appMainLogin.controller('MainLoginForm',function($scope, $http){
$scope.user_email = null;
$scope.user_pass = null;
$scope.user_remember = true;
$scope.userLogin = function () {
var val = {
"user_email": $scope.user_email,
"user_pass": $scope.user_pass,
"user_remember": $scope.user_remember,
};
var stringify = JSON.stringify(val);
$http({
url: '/login',
method: 'POST',
data: stringify || '',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}
}).success($scope.getEmailData).error($scope.httpError);
alert("error");
};
});
My routes
POST /login App.Login
GET /dash Dash.Index
I get this: 302 on the POST request
I get this: 200 OK on the GET request
On the 'response body' of the GET request (firefox debugger) I see my I intended html page but I still remain in the index page.
Why is my app not redirecting to the dashboard.html(index.html->dashboard.html) after the user enters their login credential (based on my code above)?

Resources