OAuth2 server in Node.js with Redis

Ganga Siva Krishna Palla
3 min readMay 20, 2019
break security not heart

What is OAuth?

OAuth(Open Authorization) is an open standard for access granting/delegation protocol. It is used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. It does not deal with authentication.

OAuth examples

The simplest example of OAuth is when you go to log onto a website and it offers one or more opportunities to log on using another website’s/service’s logon. You then click on the button linked to the other website, the other website authenticates you, and the website you were originally connecting to logs you on itself afterward using permission gained from the second website.

for more information refer this link: https://developer.okta.com/blog/2017/06/21/what-the-heck-is-oauth

Server Implementation

Here i am using the oauth2-server module for server implementation. It supports authorization_code, client_credentials, refresh_token and password grant, as well as extension grants, with scopes.

For now, i will be using the Password Grant for OAuth2.

The Structure of OAuth2Server

Setup your file tree :

Entry Point:

app.js for the application main entry point.

app.js

OAuth2Service:

Represents an OAuth2 server instance.

OAuth2Service.js

OAuth2Model:

OAuth2Service requires a model object through which some aspects of storage, retrieval and custom validation are abstracted.

This OAuth2 model is for Password Grant type.

The password grant is suitable for clients capable of obtaining the resource owner’s credentials (username and password, typically using an interactive form).

OAuth2Model.js

Create test data :

This file makes use of creating a simple data model where clients, tokens, refresh tokens and users are stored as hashes in Redis.

create_data.js

Package.json

package.json

Making Authorization requests:

Token request:

POST oauth/token. Allows a registered application to obtain an OAuth 2 Bearer Token, which can be used to make API requests on an application’s own behalf, without a user context. This is called Application-only authentication.

**Headers**
Authorization: "Basic " + clientId:clientSecret base64'd
(for example, to use application:secret, you should send
Basic YXBwbGljYXRpb246c2VjcmV0)
**Body** contains 3 parameters: grant_type, username and password)

Request using Bearer token :

**Headers**
Authorization: "Bearer " + accesstoken
(for example, Bearer d3e07f7c14f8f73268eea97e96398f96af8c89da)

Thanks for reading guys. Hope you find it useful 👊

Resources:

--

--