best way to handle authentication in single page application ( SPA) - javascript

In single page application usually we request a web page (dashboard.html) and we get it from server and then we are rendering some dashboard data on it (using ajax)
I want to display dashboard.html only when user is authenticated from backed (have valid email and password) otherwise I want to redirect him to login page.
$.ajax({
url: "dashbaard.json",
dataType: "json"
}).done( function(data){
// data = { inValid: true } - from backend
if(data.inValid){
alert("You are not authorized user, please register 1st!");
location.href = "register.html";
} else {
// render data on dashboard page - valid user
}
})
but here is a problem suppose user is not valid
user requested the dashboard.html, all assets (css, js, images) would be loaded although user is not valid, in this case we have no point to load single css or js file
Expected result: user requested dashboard.html if user is not valid he should be redirected to login/register page immediately without loading anything un-necessarly from server.
How we handle it with single page application ( no page refresh if possible) i need best possible solution without page flicker, I am using Laravel 4 for handling back-end authentication that does it's job very well.

Two ways:
Change dashboard.html to another server language, like php, asp.net etc, and handle authentication at server side. Redirected to login page if invalid.
Request authentication on page ready, and add beforeSend setting on per ajax request. $.ajaxSetup({beforeSend: function(){ // request authentication sync and redirect }});
If you take No.2 method, you'd better add the authorize method to a javascript file.
Hope it helps.

My way is using a popup/modal login box for handling this situation
If the ajax request return unauthenticated user then show login box (facebox, bootstrap modal, anything)
If the ajax request return authenticated user (along with data) then render dashboard data

Related

Ajax request being blocked/canceled

I have two different apps hosted under two different domains.
Once the user is logged in app 1 (hosted on aws) and click on the "my profile" button, he/she is redirected to a html page that contains an ajax form.
This ajax form makes a request to app 1's backend and the backend responds with a html form already filled with the infos needed to send the user logged to app 2 (hosted on IIS). This html response also contains a <script> tag with a .submit() function to automaticaly submit the form.
The ajax then place this html form inside a given <div> and the form is submited to app 2.
The problem is that the submition of the form is being blocked... I doesn't say why, but in the browser's Network tab, the status appears as "canceled".
I can imagine that the issue might be related to CORS, but I'm not sure since it doesn't give the cors error explicitly.
Also, it works when running app 1 in localhost.
Edit:
It seems that is not the form submition that is being blocked, but maybe the ajax request to the api asking for the form or the api response containing the form... I'm not sure.
At first, when the ajax request POST to the api, the Network tab shows this (image 1).
Then, when I get the canceled/blocked error, it shows this (image 2)

Is it safe to redirect page using jQuery and AJAX in authentication

I am creating a user authentication system using PHP, JQuery, and AJAX. On submit, a request will be sent to 'authenticate.php' with data: username & password using AJAX. The PHP code checks a database for the record and returns 0 on success, 1 on failure. Then if the returned value is 0, the page will be redirected to the 'user private page' using 'window.location="user.php"'.
Now, the question is, is it safe and proper way to authenticate like this? Are there any security problems to use jQuery/JavaScript to redirect page?
Now, the question is, is it safe and proper way to authenticate like this?
Only if inside your user.php you check again if the user has successfully authenticated already. (This is usually where sessions come into play.)
Otherwise, of course everyone who knows the URL of user.php can access it directly.
Are there any security problems to use jquery/js to redirect page?
The only difference between window.location="user.php" (which is wrong, btw. – correct would be window.location.href="user.php") and, say, a normal link to that page, foo, is that the first one happens automatically, and the second one would require the user to click the link first.
So, it is as “secure” as if you had used a simple link. What that actually means here in this case, depends what I said above.
Depends on how secure and compliant you want you application to be. According to RFCs its not recommended to login like that, but keep the form on server side and integrate the login form on frontend (via iframe), then just redirect with redirect url and token, scopes etc to a local html which then eg. sends a window postmessage to your frontend application.
https://www.rfc-editor.org/rfc/rfc6749#page-19
If you just want to be quick and dirty you can go for window.location.href or document.location.href.
Or a bit more secure, send the user to the server and let this be redirected back, but can end up in redirection hell, as its not easy to get back to the state where the user was (including settings and stuff).
Anyways, you will always have to check for the current users's session state whatever you do afterwards with serverside (Sessions).
Since you are working with PHP already i don't recommend using JS to redirect the user. You can use PHP for that:
if($user == $db['user'] && $password == $db['password']){
$_SESSION['logged_in'] = true;
header('location:user.php');
}else{
echo 'username of password is wrong';
}
Then on your user.php file:
if(isset($_SESSION['logged_in'] && $_SESSION['logged_in'] == true){
echo 'welcome to the user page';
}else{
header('location:index.php');//Go back to login page
}
If people go directly to the user.php page, they will be redirected to the index.php page.

Validate a Django Form with external POST action

I have a Django form, which sends the form data to an external source(to be more precise, it is a PayPal payment form). The user enters the price for the product, clicks on the button and the POST request is send to PayPal triggering the normal payment process.
Now I want to use OTP (like Google Authenticator) to validate each payment.
How should the validation be realized? I thought of several scenarios, but none of them is really satisfying:
Should I send the request first to my site, validate the OTP and then redirect the User to the PayPal site with the data via a POST request, coming with the request? Problem: POST requests are not meant to be redirected and I don't know, how to realize it in django.
Should I write JavaScript code, which sends an ajax request to my site, and "activates" the form on success? Problem: smarter users could just activate the form from the browser console, without sending the ajax request. Does anybody know some kind of activation trick in JavaScript, which is not "hackable"
I would be glad to hear some more solutions from you or some suggestions, how the solutions above could be realized without the problems mentioned.
EDIT - My Solution so far:
I have done a work around and split the form in two. The first form checks the OTP and sends the data to my internal django view. It also creates a model instance with an generated invoice, which can then be checked in the PayPal IPN routine. The second form is a PayPal payment form, which sends the POST request to PayPal. You can find the simplified code in the following Github-Gist:
https://gist.github.com/BloodyD/2cd15f38d0f666cf3a73
First method - normal redirection after POST:
I don't know why do You think that there shouldn't be any redirect after POST request? In django it happens all the time, without that each page refresh directly after adding something to database will trigger adding it one more time.
To redirect user into proper paypal page, you can just send HttpResponseRedirect instead of normal response when form is submitted with valid form data. If not, display some error messages.
2nd solution: using javascript.
You can send url to redirect to (paypal url) in AJAX response, so user won't be able to bypass this. Simply put some form submitted by AJAX, if it returns URL to redirect, just redirect user. If not, display error message.

PHP or JS redirect to another page with reloading and url changing

I know there are a lot of similar questions, but no solution worked for me.
I have index.php with a login form. When a user tries to login, then the login-datas are send to login.php this file checks if the username and password are valid.
If so, the file map.php shell be loaded.
The only working solution I found for this is:
header("Location: map.php");
But when the page is loaded the url is still ../login.php how can I change this?
Another problem is, if I go from pageB.php to pageA.php, doing some database changes, then redirecting from pageA.php back to pageB.php with header("Location: pageB.php"); then pageB.php is loading, but doesn't show the changed database entries, just the old ones. How can I force to reload the page for just ONE time (means no Refresh:X)?
Your question is a bit confusing but the best way to handle client redirection is using Javascript rather than the headers being sent back from PHP unless you are redirecting due to a 404, 403 etc.
For the login use case when the client provides their info fire off an ajax post event containing the form data. Process the data using PHP and send back a response to the Javascript. Based on the return message from PHP use the window.location API to redirect / refresh as needed.

How to redirect with one time message after PUT

So here is the desired behavior I'm trying to get:
User goes to a password change web page.
User fills out form and the form PUTs to our REST server.
After a successfully PUT, the user is redirected to the "My Account" page with a message saying, "Password successfully changed".
If they refresh their "My Account" page, the password message should go away. (I.e. it is a one time message.)
Here are solutions I've tried (unsuccessfully):
1) Using JQuery to perform an AJAX PUT to the REST server. This works fine for the PUT, but the redirect has to be in the onSuccess JavaScript and if it passes a message on the URL to the My Account page, then that message hangs around after refresh.
2) Using a traditional form. However, this won't do a PUT ( method does not support put, on post and get). I could do a POST, but that is "wrong" from a REST perspective, because I'm updating the user account record, not creating a new record. The redirect and one-time message could all be handled server side with this solution (RESTlets, Servlets and/or JSP).
Is there are good solution out there? Or must I change my PUT to a POST?
You may do PUT using a traditional form using JavaScript. The only trick is to flash a temporary message. I've seen web frameworks that use a sort of temporary session state for this kind of stuff which requires little effort on your part. If you don't have that available, the trick would be to store a temporary session in the database and reference it through a cookie. It is not straight forward, and that is why web frameworks can really help you in this situation.
The typical setup is as simple as this:
$('form').submit(function () {
$.ajax({
url: 'service/api',
data: $('form').serialize(),
type: 'POST'})
.done(function () {
// perform redirect
});
On the server side you set the temporary session state and delete when complete.

Categories

Resources