node.jsauthenticationjwtno-framework

Is it possible to create a JWT authentication or something similar in Node.js without using frameworks?


I'm creating a Website and I've understood that the best authentication is through JWT, but I'm not a fun of frameworks because I like to go deep in the code and understand all the code in my files. Thus I'm asking if someone have done it, or something similar, in pure Node.js and if could give me an explanation of how to do that.

Thanks


Solution

  • Yes, it's of course possible, just consider how frameworks are made. There's no magic involved, just knowledge and a lot of javascript code.

    You can find the sources of most frameworks on Github and study them there.

    In a first step, you should make yourself familiar with the basics of JWT, e.g. with the help of this introduction and by reading RFC7519.

    You'll find out, that a JWT basically consists of base64url encoded JSON objects and a base64url encoded signature.

    The simplest signature algorithm is HS256 (HMAC-SHA256).

    In the jwt.io debugger window, you see in the right column the pseudo code for creating a JWT signature:

    HMACSHA256(
      base64UrlEncode(header) + "." +
      base64UrlEncode(payload),
      secret
    )
    

    so basically you need to learn:

    With this, you already have a basic JWT framework that would allow you to create a signed token and verify the signature.

    In the next step you can add "features" like

    You can use the jwt.io debugger to check the if your token can be decoded and verified.