Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for JWT Auth microservice example

I am wanting to build a authentication/authorization service using NodeJS, Mongo, and JWT. This service would be a micro-service that handles requests not only from my API Gateway before allowing requests, but from other services that might want to check auth and roles. I am assuming that all other services will use this Auth Service to validate the JWT as well as roles, etc.

Hopefully this diagram better explains what I am looking for. enter image description here

Can anyone point me to a resource that might help me learn how to do this with NodeJS?

like image 260
sonoerin Avatar asked Oct 30 '17 01:10

sonoerin


1 Answers

If you have a single client application then you can do following steps

  • Make one microservice for authentication that generates jwt token.

  • The jwt contains all essential user information in its payload, ie Role, UserId etc.

  • The jwt token will be sent in Authorization header for every authorised request.

  • Before processing any request you can validate and decode the jwt token using middlewares. Now you can set the user's info in req object easliy and can easily access users role and its id in your controller.

  • if the token is not valid then you can throw error in middlewares and it will provide json response of unauthorised.

  • You can call the authentication api to validate and decode your token or you can write 3 to 4 line of code in every microservice in middleware.

Here are some links for sample implementation of jwt, you should customize these sample code according to above steps.

5-steps-to-authenticating-node-js

authenticate a nodejs api with json web tokens

If you have multiple client applications

  • You should use openid connect standard that provides single sign on solution to authenticate multiple application with same username and password.

  • here is a openid connect playground to understand the authorization flow.

like image 187
Vikash Dahiya Avatar answered Oct 05 '22 23:10

Vikash Dahiya