Authenticate an Ember app with a Sails API using sane-auth. This setup is based on JSON Web Token (JWT) and OAuth2.
This combination is what has worked best for me, but there are many other options, you can read about those here: Ember and Sails authentication options.
First of all, you need to install Node. If you haven't done it yet, I strongly recommend that you do it through NVM.
The version that we'll be using is:
node -v v0.12.4
Install the necessary tools:
npm install -g email@example.com npm install -g firstname.lastname@example.org npm install -g email@example.com
Create a new sane project.
sane new sane-auth-example # it will take a couple of minutes, # stand up and stretch a bit cd sane-auth-example/ sane install sane-auth # we are done, really sane up # visit
http://localhost:4200/register and register a new user, you can login after that.
I wasn't joking, we are done.
You can see the code here: givanse/sane-auth-example.
This was extremely easy because we are leveraging multiple open source projects. What follows is an overview of what is happening under the hood.
Sane gives us a medium for full stack development using Ember and Sails.
0.1.0-beta.1 introduces the addons feature,
sane-auth is an addon and that is why we were able to set everything up with a single command.
Both of them are a really nice glue between Sails, Ember and a bunch of other packages.
Sane-auth installs the Ember Simple Auth (ESA) addon with the OAuth2 authenticator.
It also creates the routes
register with their respective templates.
It saves us from all that boilerplate.
On this side its relying on
express-jwt, both built by auth0.
Sane-auth creates the
Auth controller, the
User model and the
hasToken policy that protects all our routes.
Every request will be filtered by the policy
internally it uses
jsonwebtoken) to verify that the request comes with a proper and valid JWT.
That is the flow once you are logged in.
When a user submits a log-in this happens:
- ESA sends a request to
- ESA sends a request to
Authcontroller handles the request and does one of two things:
bcryptto validate the user password and generate a new JWT for the user using
- If the request comes already with a JWT, it uses
jsonwebtokento verify it and generate new tokens.
logout action only deletes the token in the client, it will remain as a valid token in the server until it expires.
That is 2 hours, the default set by
If you want extra security you'll have to implement your own process for token invalidation in the backend.
There is no magic, since both frameworks have strong conventions its relatively easy to automatically generate stuff for them. Composability is giving us all this goodness. We have an addon that installs and configures other addons.