Authentication session techniques for server rendered React js code? - javascript

I am writing a React.js non-single page application. I've been using auth tokens to store my authentication sessions which normally works fine with single page applications. But in my case, whenever the client makes a request directly from the address bar, I can't execute the js code that places the auth token in the header of the request.
I would prefer not to use cookies to handle this problem, especially if I plan to convert my application to a single page or isomorphic application. Is there another way to maintain sessions in my application?

This isn't specific to React.
You can use JavaScript as you were doing to manipulate custom headers, browser cookies, or URLs with custom query strings.
If users may type directly into the address bar a URL on your web site, you need to use cookies. The browser will automatically send them with each request. Using cookies is a common technique and shouldn't cause a problem if you move to a SPA or isomorphic application.

Cookies are your best bet becuse the browser will transparently send them for you. They also work with hybrid mobile platforms (phone gap, etc). And yes, cookies ARE secure if you use them the right way. I've elaborated on this issue in my blog post here: Token Based Authentication for Single Page Apps (SPAs)

Related

How do you implement digest authentication with SHA-256 when modern web browsers disable SubtleCrypto when you're not in a secure context (https)?

I've got a very basic web server running on an ESP8266 microcontroller, so system resources are very limited, but I figure it can probably deal with SHA-256 (I'll guess we'll see, but that's a separate issue).
I've got the barebones digest authentication implementation working well enough that I can access the site via curl.
This microcontroller is not meant to be exposed to the internet, it's only something you'd access internally via your lan, so SSL isn't an option (not sure how well the microcontroller would hold up if it tried to support HTTPS).
So, here's my scenario:
User tries to access the site on the microcontroller from their favourite web browser. They are given a 401 code and redirected to a login page (along with the WWW-Authenticate header).
This login page needs to take the information from the WWW-Authenticate header, as well as the username and password input by the user and generate the hash it needs to send in an Authorization header.
Unfortunately, the built in functionality for generating SHA-256 hashes is disabled if you're not connected via HTTPS (according to https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) - So does this mean that digest authentication is not supported by web browsers natively (unless they choose to use MD5 instead of something more secure)? If you're implementing digest authentication, you need to supply your own hashing functions?
I also don't quite understand why disabling the ability to do hashes helps user security (in a non-https context).
An assumption:
After a cursory google search, it seems that digest authentication only makes sense for http, as if you're using https then you've already got better encryption protecting your credentials.
So to answer my own question (partly):
It turns out that the user side is handled entirely by the browser (i.e. Generic login modal pop-up). Java script doesn't even have access to the response headers anyway.
I guess to prevent poorly implemented non-secure logins?
The examples I've seen work around it by providing functionality entirely via xhttprequests.
I still don't know what benefit denying access to hashing algorithms provides though

Spa app w/ Web API security concern. Can a logged in user with a JWT make random requests to API

I have a security concern about building a SPA application.
What is stopping an end user to make calls to my Web API as long as they have a token?
For example: I am an end user to a Spa web application and I login through the login form. Get access to the JWT token provided to me (assuming this is easy). Then open up postman and try making every call possible putting that token in the header of every request.
I am assuming the only calls I would be able to make are the ones I would be authorized to make through the UI due to Web API authorization.
Is there any type of security out there to prevent this or is it basically just make sure your Web API has proper authorization?
There is absolutely no difference here to regular websites/web applications. Yes, anyone can try to make any HTTP calls they wish to your server. That holds for plain websites, jQuery sites, SPA sites, mobile applications or Flash games. Your server needs to do the proper authorisation and validation to ensure the user is allowed to do what they're attempting to do.

External Private API Authentication with Backbone

I am building an API and had questions about handling authentication when using a front-end framework such as Backbone.js.
I have a single API server that is responsible for returning and modifying data based on RESTful web requests.
I have another app server that is a Backbone application. I want this application to connect directly with my API server, so set the entire project up so that this app server can make cross-domain AJAX requests to the API server.
There are some API routes that I do not want unauthorized parties to obtain access to. For example, I have a path /users that lists all the users of my app. I need this path later on for admin functions, but I don't want it publicly available to my app server.
What is a good authentication scheme to use? OAuth won't work because the secret token would be exposed on the front-end. And after that, I'm a little stuck with what my options are. Does anyone have any suggestions moving forward?
In cases like these I use a combination of techniques.
-- Good ole Cookie based auth
As a backbone app will always be used inside a browser and browsers have built-in cookie support, I would suggest that you should accept cookie based sessions on the server side. All the auth related stuff will be handled by the browser and you don't have to worry about storing keys etc. On top many libraries like (NSURL in iPhone) and frameworks (like PhoneGap/Trigger) all support cookies so woha you can support all kind of clients with litte work.
-- Plain API Key
For third-parties, I use api-key based authentication. You provide username and password, I provide key. You send me that key every time in HTTP header for all subsequent requests. I use the key to identify you and then allow/disallow actions accordingly.
I assume once you can authenticate a user (wait..who are you?), then you can setup authorizations ( you say Micheal ? ...ok you can access /users )
Also take a look at my backbone-parse plugin for an idea on how to authenticate users against an external API service #shamelessplug

Retain authentication via JavaScript client?

I have a WCF application where I make JavaScript calls to. I want to secure the web services so you have to be logged in to use it. This is easy if I have a server-side application making the requests to the WCF. If I am using a pure JavaScript / jQuery client-side app, I can authenticate fine by passing the credentials as JSON parameter, but how do I keep that client-side app logged in from that point on? Do I store a cookie? I do not want to store the credentials in the cookie of course because that is not secure. So how can I achieve this without introducing another server-side application to the mix? How do web apps achieve this?
OAuth is kind of the go to solution for JS API's. Netflix, Yelp, Facebook etc. use this.
Here is an article on OAuth in WCF
And here is a pretty well known library for doing auth in .NET: DotNetOpenAuth
If you use or are using ASP.Net form authentication (WCF should be running in ASP.Net compatibility mode) then there is not much to do.
If you set the form authentication ticket\cookie after your initial authentication, the cookie would be attached to every subsequent request from the browser without you writing any code. All future calls to WCF service then can be authenticated on the server using the standard ASP.Net authentication pipeline.

Securing my Node.js app's REST API?

I could do with some help on my REST API. I'm writing a Node.js app which is using Express, MongoDB and has Backbone.js on the client side. I've spent the last two days trying to work out all of this and not having much luck. I've already checked out:
Securing a REST API
Securing my REST API with OAuth while still allowing authentication via third party OAuth providers (using DotNetOpenAuth)
http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/
http://tesoriere.com/2011/10/10/node.js-getting-oauth-up-and-working-using-express.js-and-railway.js/
I want to keep my backend and frontend as separate as possible so I thought about using a carefully designed REST API would be good. My thinking is that if I ever get round to developing an iPhone app (or something else like that), it could use the API to access data.
BUT, I want this to be secure. A user has logged into my web app and I want to ensure my API is secure. I read about OAuth, OAuth 2.0, OpenID, Hmac, hashes etc... I want to avoid using external logging in (Facebook/Twitter/etc) I want the registering and logging in to be on my app/server.
...but I'm still confused here. Maybe it's late at night or my brain is just fried, but I could really do with some steps on what to do here. What are the steps for me to create a secure API?
Any help, any information, any examples, steps or anything would be great. Please help!
In order of increasing security / complexity:
Basic HTTP Auth
Many API libraries will let you build this in (Piston in Django for example) or you can let your webserver handle it. Both Nginx and Apache can use server directives to secure a site with a simple b64encoded password. It's not the most secure thing in the world but it is at least a username and password!
If you're using Nginx you can add a section to your host config like so:
auth_basic "Restricted";
auth_basic_user_file /path/to/htpasswd;
(Put it in your location / block)
Docs: http://wiki.nginx.org/HttpAuthBasicModule
You'll need to get the python script to generate that password and put the output into a file: http://trac.edgewall.org/browser/trunk/contrib/htpasswd.py?format=txt
The location of the file doesn't matter too much as long as Nginx has access to it.
HTTPS
Secure the connection from your server to the app, this is the most basic and will prevent man in the middle attacks.
You can do this with Nginx, the docs for it are very comprehensive: http://wiki.nginx.org/HttpSslModule
A self-signed certificate for this would be fine (and free!).
API Keys
These could be in any format you like but they give you the benefit of revoking access should you need to. Possibly not the perfect solution for you if you're developing both ends of the connection. They tend to be used when you have third parties using the API, eg Github.
OAuth
OAuth 2.0 is the one to go with here. While I don't know the underlying workings of the spec it's the defacto standard for most authentication now (Twitter, Facebook, Google, etc.) and there are a ton of libraries and docs to help you get those implemented. That being said, it's usually used to authenticate a user by asking a third party service for the authentication.
Given that you doing the development both ends it would probably be enough to put your API behind Basic HTTP Auth and serve it over HTTPS, especially if you don't want to waste time messing around with OAuth.
Here's a different way of thinking about it:
Let's suppose for a moment that you're not using an API. Your user logs into the app, providing some credentials, and you give a cookie or similar token of some sort to the user, which you use to identify that user has logged in. The user then requests a page containing restricted information (or creating/modifying/deleting it), so you check that this token to ensure that the user is allowed to view that information.
Now, it sounds to me that the only thing you're changing here is the way that information is delivered. Instead of delivering the information as rendered HTML, you're returning the information as JSON and rendering it on the client side. Your AJAX requests to the server will carry that same logged-in token as before, so I suggest just checking that token, and restricting the information down to 'just what the user is allowed to know' in the same way.
Your API is now as secure as your login is - if anyone was to know the token necessary for accessing the api, they would also be logged into the site and have access to all the information anyway. Best bit is, if you've already implemented login, you've not really had to do any more work.
The point of systems such as OAuth is to provide this 'logging in' method, usually from a third party application and as a developer. This would potentially be a good solution for an iPhone app or similar, but that's in the future. Nothing wrong with the API accepting more than one authentication method!
The answers so far do a great job of explaining, but don't give any actual steps. I came across this blog post that goes into great detail about how to create and manage tokens securely with Node + Passport.
http://aleksandrov.ws/2013/09/12/restful-api-with-nodejs-plus-mongodb/
Tips valid for securing any web application
If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.
You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:
1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)
2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)
3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized
4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request
5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.
Node.js specific libraries to implement JWTs:
Many libraries provide easy ways to create & validate JWTs, for example: in node.js one of the most popular is jsonwebtoken, also for validating the JWTs you can use the same library or use express-jwt or koa-jwt (if you are using express/koa)
Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.
One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).
You can learn more about JWTs from this link

Categories

Resources