I have developed a dynamic page with javascript (no reloading) where a user inserts a private number.Then I send a Ajax request to manually log in the user associated with that number.After that if the user wants he can exit (send Ajax request to logout) and the main page appears to log in again.
Steps To Reproduce:
Enter Number, click login and I verify that the first login works.
Click exit and the logout works
Insert same or another number and click login again and now the user is not authenticated.
Note: If I refresh the page after exit(logging out), the 2nd login works.
-> Code where I send Ajax request to verifyNIF()
$('#start').on('click', function() {
$.ajax({
url: '/' + slug + '/vote-in-person/verify-nif',
type: "POST",
data: {
nif: nif
},
dataType: "json",
success: function (data) {
//NIF VERIFIED AND USER LOGGED IN
}
});
});
-> verifyNIF() verifies the number on the DB and then authenticates the user
Auth::login($user);
-> logout() function, which uses Laravel Fortify logout route.
function logout(){
$.ajax({
url: '/logout',
type: "POST",
success: function () {
console.log("logged out");
// location.reload();
},
error: function (data) {
console.log(data);
}
})
}
On the front side, the CSRF token becomes invalid after logout with an ajax request. You can add a new endpoint to refresh the CSRF token manually. I think that helps you. https://stackoverflow.com/a/57252273/9215587
Related
I have a view in my django backend called getUserInfo that will return the user's info as json format.
This is my view:
#api_view(["POST"])
def getUserInfo(request):
if request.user.username:
serial = userInfoSerializer(request.user)
return Response(serial.data)
else:
return Response({"notLoggedIn": True})
When I'm not logged in ajax request are working ok but when I login to a user account I get an "forbidden" error and it says csrf validation failed. I am also refreshing the csrf token every time the user logs in or out.
So it should work but it is not working.
This is my ajax request:
function login(){
getcsrf();
$.ajax({
url: '/api/login/',
type: 'POST',
headers: {
"XCSRF_TOKEN": csrf
},
data: {
username: $("#l-username").val(),
password: $("#l-password").val(),
},
})
.done(function(data) {
console.log(data)
if(data.msg){
console.log(data.msg)
$(`<div class="p-2 bg-danger">`+data.msg+`</div>`).prependTo('#message-box')
}else{
getcsrf();
getUserInfo();
}
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
The function getcsrf refreshes the global variable containing the csrf-token value called "csrf" and then I send my ajax request. After the request I refresh it again. I'm sure the value of csrf token changes every time I am refreshing it when user logs in or out but server always says "forbidden".
I have inserted this code in my settings.py file:
CSRF_HEADER_NAME = "HTTP_XCSRF_TOKEN"
and I am sending ajax request with a header called XCSRF_TOKEN
Can any one help me?
SORRY FOR MY ENGLISH
Maybe try:
headers: {
"HTTP_XCSRF_TOKEN": csrf
},
so that it matches the header name in your settings file.
okay let me answer it my self.
i cleared my browser cookies and then it worked properly
I have developed various UI5 apps and if i want to logout on one of them, all UI5 apps should be logout out.
For example. The first App is a menu. So I login in the first Menu-App. From this app there is a link to another app. Now i want to logout from this app and want to geht the redirect link to the menu-login.
I have the following code for logout of the second app (not the menu-app):
handleLogout: function (oEvent) {
$.ajax({
type: "GET",
url: "/sap/.../logoff",
}).done(function (data) {
if (!document.execCommand("ClearAuthenticationCache")) {
window.localStorage.clear()
$.ajax({
type: "GET",
url: "/sap/.../logoff",
username: '',
password: '',
statusCode: {
401: function () {
}
},
error: function () {
}
});
}
});
var myVar = setInterval(function (oEvent) {
window.location.replace("/sap/...->link to the menu<-");
}, 100);
},
The result of this code is, that i get redirected to the menu-app and not to its login. I guess because there am still logged in.
Is there a chance or some sort of code where i can logout of all existing ui5-apps?
Has it something to do with cache-settings?
Solution is related with your session mechanism. How to you manage user session? Are you using cookies or local storage?
For example you need to invalidate cookies in logout process for cookie option.
Check your ClearAuthenticationCache method, it is look like using local storage method.
I'm going to use Facebook JS SDK to login users to my site.
function myLogin(){
FB.api('/me',{fields: 'name,email'}, function(response) {
if(response.email){
//Ajax call function
jQuery.ajax({
url: 'inc/social_logins/fb/account_auth.php',
type: "POST",
data: { func: 'nac', name: response.name, email: response.email},
success:function(data) {
if(data == 1){
window.location = "user_dashboard.php";
}
}
});
//Ajax call function ends
}
}
Above ajax request calls account_auth.php and it checks for accounts associated with the email comes with FB authorization. And if FB authorization returns true, it runs the myLogin() in the following logic.
function statusChangeCallback(response) {
if (response.status === 'connected') {
qksellLogin();
}
}
Everything works fine and gets redirected to the private dashboard area after FB login popup window closed.
What I want to do is, to block manual Ajax requests by unauthorized users.
Let's say if I can fake the response object and add someone else's FB name and email, then I call the above Ajax call function in the console, it still runs and logs in. That's terrible huh...
So, what actions may I want to take here ?
I'm about to implement a Login using Google OAuth. I followed the official Google docs
The client does get a token from the Google server. But whenever I try to send it back to my server to store it, I do not seem to get data from the AJAX call. Here is my code:
function signInCallback(authResult) { //called when client has confirmed the Login dialog
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
console.log("signinCallback. Send code to server:")
console.log("Code = "+ authResult['code']);
console.log("performing AJAX call now...\n\n")
// Send the code to the server
$.ajax({
type: 'POST',
url: 'http://localhost:9000/storeauthcode',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
console.log("AJAX call --> success");
console.log(result)
},
processData: false,
data: authResult['code']
});
} else {
//There was an error.
console.log("AJAX call failed.")
}
I created a line in my routes file:
POST /storeauthcode controllers.Application.storeAuthCode
The method on the server:
def storeAuthCode = Action { request =>
Ok("storeauthcode called with queryString = "+request.rawQueryString)
}
The following is a console output of my Chrome browser:
hello.js:2 Welcome to your Play application's JavaScript!
(index):67 signinCallback. Send code to server:
(index):68 Code = <token deleted for privacy reasons>
(index):69 performing AJAX call now...
(index):77 AJAX call --> success
(index):78 storeauthcode called with queryString =
So although my browser gets a token back, I cannot store it on the server, because I don't get any data back.
Ok("storeauthcode called with queryString = "+request.body.asJson)
is also empty.
This one here also delivers an empty result:
def storeAuthCode = Action { request =>
Ok("storeauthcode called with queryString = "+request.getQueryString("data"))
}
I implemented a system on my ASP.NET Web Forms site for passing notifications to the client. The notifications can be validation messages, success messages, warnings, errors etc. These messages are generated by code on the server side and then retrieved from the server via script on the client side and displayed.
On each page of my site I have embedded a JavaScript function that calls a web service (on the server side) via jQuery AJAX and requests the latest notifications. If there are notifications, they are displayed using Noty. On the server side, messages that have been sent to the client are removed from the queue.
This works pretty well. However, let's say I'm on a page called NewEmployee.aspx and they create a new employee by filling out a new form, and this generates some kind of notification such as "New Employee Created With ID 58478" and also takes them to the ViewEmployee.aspx page. If the postback happens slowly enough, the message will start to display while the user is still on NewEmployee.aspx but before the user arrives at ViewEmployee.aspx. The end result is that the notification is only displayed for a split second and the user never sees it.
I need a way in JavaScript on the client side to detect if the page is performing a postback. If I have that, I can prevent it from calling the webservice during a postback and have it wait until it completes. I want it to look something like this.
setInterval(oneSecondFunction, 1000); //check for messages every 1 second
function oneSecondFunction()
{
var IsPostingBackRightNow=GetIsPostingBackStatus(); //I need your help writing this function
if(!IsPostingBackRightNow)
{
$.ajax({
type: 'POST',
url: 'myurl/MessageService.asmx/GetCurrentMessage',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ sessionid: sessionid, locale: 'en-US' }),
dataType: 'xml',
success: function (msg)
{
//show message via noty if there's a message
}
});
}
}
The post back is passing from the form, so you capture the onsubmit event on the form, and there you open your flag.
Here is how... add that on code behind
Page.Form.Attributes["onsubmit"] = "return GoForPostBack();";
to have this attribute also rendered on your form...
<form ... onsubmit="return GoForPostBack();">
and the javascript
var IsPostingBackRightNow = false;
function GoForPostBack()
{
IsPostingBackRightNow = true;
return true;
}
setInterval(oneSecondFunction, 1000); //check for messages every 1 second
function oneSecondFunction()
{
if(!IsPostingBackRightNow)
{
$.ajax({
type: 'POST',
url: 'myurl/MessageService.asmx/GetCurrentMessage',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ sessionid: sessionid, locale: 'en-US' }),
dataType: 'xml',
success: function (msg)
{
//show message via noty if there's a message
}
});
}
}