Authentication, Authorization, OAuth NodeJS express production-ready real-life example

Intro <<<<< Still a Draft >>>>>

Although the target is real simple, we have a SPA that talks to an API, we want to add a user login system so many terms, protocols, and methodologies can be very confusing at first. so let us take a closer look.

first thing first, for sake of code example i will be using NodeJS because everybody knows javascript! yet same concepts you can implement in any language.

first the What.. then the Why.

before we start, we will be talking about Authentication, this not to be confused with Authorization which will have another post.

What is Authorization? John wants to delete a post, can he do that? this is Authorization

verifying the user is allowed to do the action he is trying to do; a.k.a Authorized

now that's unrelated to how you will implement your Authentication. with that aside let us start talking about our topic

What is Authentication?

someone send a request to your server, and claim his name is John; Auth is the process of making sure that John is really John !

make sure user is who he claims to be; a.k.a Authentic

1. oAuth?

Do you know this "login with Facebook" button? that's OAuth.

in simple terms, it's the same as when you go to the club and he asks you for your id, you call your cool friend and that friend tell the guards in the club that he knows you, your name is Jhon and he guarantees that you are cool!

It's an Authentication standard, first developed by Twitter, Google; that describes how you can authenticate a user using another server.

OAuth allow unrelated servers/services to authenticate a user without sharing user credential, where a certain identity provider guarantees to the consumer that this person is indeed who he claims to be

2. Token-based Authentication

the protocol involves standard steps:

  1. User request: most common type use username-password
  2. Server Generate Token: after the server made sure the user is authentic, it generates a token that is unique to this user
  3. Client store token: the client will use this token in all his subsequent requests to the server, so the server can fetch user info from/using this token.

concept here is that instead of using session/cookie to save user info accross multiple requests; you use token.

Many Token Types exists, most commonly known:

  1. JWT: jsonwebtoken encrypt user info. made popular by micro-services/distributed cloud apps as they can decrypt token to extract user info without need to contact auth. server or do database call.

  2. stored token: a random generated string stored in database linking to user record

each has its advantages and usecases, and also has its disadvantages and contra-indications.

JWT Example:

Signing Token

  1. using secert_key
  2. using key-pair (id_rsa, id_rsa.pub)

Workflow

  1. To create token
  2. to logout user
  3. to logout a token
  4. to refresh token