Obtaining Request Headers Clientside - javascript

I'm working on making a login page with for SSO. The flow is that a user goes to an outside application, the application redirects to my login, which then recognizes that it's received a jwt authentication request, I authenticate the user and then redirect with a new token that I generate.
My question is, am I receiving a token in the request when the outside application redirects to mysite.net/login, or am I supposed to pick up the query string and recognize it?
I tried it for myself and it went to mysite.net/login?return_to=%2F
Are they sending me a token (like how I normally do serverside) and if so, how do I access it?
Here's the documentation in question: https://support.aha.io/hc/en-us/articles/203636345-Idea-portal-single-sign-on-JSON-Web-Token-JWT-

window.location.search gives you access to the entire "query string", which is the name of the thing you are talking about.
Here's a Stackoverflow answer that demonstrates how to pass it: How can I get query string values in JavaScript? But there are probably a whole lot of NPM packages that do the same thing. Or you could do a very simple regex / replace string.

Related

NodeJS Routing - Post Login - with JWT and jQuery

I have seen more examples than I can count of how to build an NodeJS api with JWT, however, I have not seen anything on how to use the token when navigating your page via the routing.
I have the JTW authentication working. I am returning a token to the user and saving it in cookies and local memory. The part I am stuck on is the proper way to use that token when trying to navigate to other URIs on my site.
For example, when the user goes to my main page (mySite.com), they will be presented with an awesome picture and a login form. They successfully log in, get the token, but now the site needs to forward to mySite.com/home. If I am not using any fancy tools, just jQuery GET/PUT/POST/etc, how is this done?
Currently I make the original PUT, sending the username and password, which if successful it calls a jQuery callback that takes the returned token and saves it in the cookies and then makes a GET call (with the token) to get the "/home" page html. The GET returns the HTML which I then call $('body').html(response) to render that HTML. The only problem is that I am still at the URL mySite.com, not mySite.com/home.
If I try to do a redirect in the backend of the frontend, my JWT blocks it because I am not passing the token with it. Is there a way to do a redirect with a JWT or something?

Is it possible to prevent that a popup be opened directly as opposed to being opened by Javascript?

The application I'm working on relies on many popups. Those popups rely themselves on query strings. If someone can just type the url in the browser address bar, the page will throw an error as the query strings values are dynamically constructed.
function myFunction(id)
{
window.open("mypopup.aspx?id=" + id);
}
Is there a why to prevent the page from displaying if the requester of the page is not a Javascript? If someone type something like:
https://mycompanyname.com/path/mypopup.aspx
It shouldn't let the user do so. Or, at least check whether the requester is not javascript so I can display a message or redirect the user to a different page? Otherwise, without all those pieces of data needed to construct a request, the page will throw an exception.
Thanks for helping.
Validate the query string directly in myPopup.aspx, if something is missing just redirect or display a message.
Use the Request.QueryString collection to validate in myPopup.aspx.
There is no easy way to validate if the request came from javascript as far as I know. You could try creating a token to validate that the sender is the one you expect, but if you only need to validate the parameters, no need to worry about who is sending the request.
The page cannot differentiate how it was requested, if both requests come from a same browser.
However, you can include in query string to differentiate them.
For example,
window.open("mypopup.aspx?request=javascript&id=" + id);
If a user intentionally type in https://mycompanyname.com/path/mypopup.aspx?request=javascript, so be it. I won't worry about it.
Popups are browser windows too. So it will be tricky to check if the window requesting the page is normal window or popup.
You should restrict the users to see on what url the popup is being opened you can hide the address bar. So user can not copy or know the what's in the url.
window.open('/pageaddress.html','winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');
Setup a token based validation. Make request to server(Ajax request) to get a random token(with one time validation mechanism and expire it), You can send the token in the query string and validate it on server if it's same issued token. Identify if the requested page have valid token(popup) otherwise deny the request or show error message. Think of how captcha works, you just need to do it programmatically.
Though it's also not the best solution as token information can be sniffed through network traffic tracker tools like fiddler but it's will work to prevent manual requests.

How to authenticate an AJAX request to a PHP file?

On my website I have a registration page which makes an AJAX request to check if a username is available after it has been entered. This file is called check.php and is in the same directory as the registration.php file. When data is posted to check.php it will perform a query at a MySQL database and return how many users it found with that username.
If anybody were to post data to the check.php file they would see the result, too. I need to stop this somehow, I've read on a few answers I need to "authenticate" each request. This is probably a very large topic although I'm not too sure what to search for to find more about it. Is authenticating each request a good way to stop unnecessary username checks? If so I would really appreciate it if anyone could point me in the right direction as to how to do this.
A solution is to generate a unique token in session, and put it in all pages that will contain a form. Post this token on each AJAX request you make.
It is called CSRF protection, Cross-Site Request Forgery.
You can add a protection layer checking the user referer in HTTP headers.
Answer for common case: no - you can't prevent this, since AJAX is just an HTTP-request. It can be sent no matter how you'll protect your server. So if the point is - to protect from 'evil hackers' - there's no way to do this. The correct though is to check/validate anything on server side.
But is it's about only basic check, you can read
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest')
-but be aware - this is also a data, which came from client i.e. it can't be trusted (actually, it's just HTTP-request header, nothing more)
I think you can create a Session variable when the user logs in your aplication and check if this variable has the correct value whe you post something to your 'check.php' file to check if your user is previous authenticate
Missing a lot of info but conceptually I am not sure you are worrying about a real risk. Bottom line is that people can use your form to check if emails exist so it's logical they can use check.php as well. Would be overkill to try and prevent that.
I have one think - you can generate some unique token, store it on SESSION before show the page. Than on each checking you must to add this token to request. check.php must regenerate token and return it new.
But each request can emulate and it not protect you from people, which want to know results of check.php. Nothing protect...
Also you can make mechanism for analyzing ip request for checking

Sending token by POST or cookie?

I've got a single page node.js FB Canvas App. Every user action triggers an AJAX POST to my node.js HTTPS server, returning the result.
Now I need a way to send a user token I create from the userId on app boot (this is an AJAX POST too, returning all content + user token). I verify that it is this user by doing a Graph API call (which is required for my boot for another reason) on the server.
Q1 So to create the token what should I use?
Q2 How to send the token with every AJAX call:
POST param?
cookie?
something else?
Q1 I assume that tokens should be unique and secure. That's generally not an easy problem. I would go with following steps:
generate a random number
try to save it into DB (or any other shared storage)
if it already exists in DB go to step 1. if not go to step 4
send the token
Ad.1. To generate a random number use crypto.randomBytes with large enough size param (256 is more then enough) in order to minimize collisions:
http://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
crypto.randomBytes should be secure. There are however some subtleties with it. For example you have to ensure that your machine has enough entropy. It can be a problem when your server does not have keyboard, mouse or mic. You can always add a hardware entropy generator:
http://en.wikipedia.org/wiki/Hardware_random_number_generator
If you don't need it to be secure then you can use crypto.pseudoRandomBytes instead.
Also it is a good idea to create and use your own algorithm (based on crypto of course). For example add a current date to that number, hash it, whatever. Just be careful not to overdo it.
Also remember about cleaning DB from old tokens.
Q2 It doesn't really matter. Whatever suits you. Probably putting it in a cookie is the easiest solution.
If you need this token for preventing from a CSRF attack, I'd recommend to send it into a POST parameter.

Security for an Instapaper-like bookmarklet

I'm trying to make a bookmarklet that does something similar to what Instapaper's does. I need the bookmarklet to send the URL of the page the user is visiting and the user's token(so the server identifies the user). How can this be done? Do you recommend I send a POST request or rather by routing the URL(for eg http://example.com/USER_TOKEN/URL )?
Also, will I need to worry about the user's token being stolen? If so, how can I handle that?
will I need to worry about the user's token being stolen
Since everything you transmit over plain HTTP is basically unencrypted plain-text, yes, you need to worry about the token being stolen.
What's more important imo, is that including the user token into your bookmarklet seems rather hack-ish:
What if a machine is used by multiple users A, B and C?
Users A and B are both using your service? Separate bookmarklets?
User C is pissed off about something A did - clicking his bookmarklet on a dozen porn sites sure sounds like fun, eh?
I would suggest something along the following lines:
Submit the URL to a GET (if you care about performance much) or POST (if you care about getting CRUD right) route.
Server-Side: Check if a user session exists (via cookies, obviously).
If so, process your data, send success callback as JSONP.
If not, send failure callback as JSONP which triggers a "Please Log in" popup/overlay.
Extra points are given for the "Please log in" thingy remembering the URL the user has been trying to save so he doesn't have to re-submit after having logged in.

Categories