JSON Web Auth Using Angular 8 And NodeJS
This article discusses the JSON Web Token (JWT) and its authentication into your Angular 8 project with a secure backend API running on Node.JS.
Join the DZone community and get the full member experience.Join For Free
What are JSON Web Tokens?
JSON Web Token is an open standard or RFC Standard (Request for Comments). It comprises a best-practice set of methodologies that describes a compact and autonomous way for securely transmitting information between parties as a JSON object. This information is digitally signed or encrypted, and hence it can be simply verified and trusted. For this purpose, a secret key such as an HMAC algorithm is set, or a public/private key pair is generated using RSA or ECDSA.
Why are JSON Web Tokens Useful?
JWT offers the most secure way for authenticating the integrity of the exchange of information between the client and the server. It is adapted for verification so, in the case of any violation or breach, the token will not verify or expire based on time.
Moreover, the benefits of JSON Web Tokens (JWT) weigh more compared to Simple Web Tokens (SWT) or Security Assertion Markup Language Tokens (SAML), so JWT can be preferred over the other two.
Let's take a glance at the theory in practice for JSON web authentication using Angular 8 and NodeJS.
Here, Angular 8 will be used on the frontend while Node.JS server on the backend. First, an interceptor will be formed on the Angular side. An interceptor can break any HTTP request sent from Angular, replicate it, and insert a token to it before it is sent at last.
All the requests obtained will first be broken and replicated or cloned on the Node.JS side. Then, the token will be extracted and authenticated. If the verification is successful, the request will be forwarded to its handler for a specific response. If the authentication fails, all remaining requests will be invalid, and a 401 unauthorized status will be sent to Angular.
All requests will be verified for a 401 status in the interceptor of the Angular App, and for such a request, the token will be removed, which is stored at Angular. The user will be logged out of all sessions and will land on the login screen.
Let’s Get Started
The Angular App is created at the frontend, followed by interceptor creation.
Then, the Interceptor.
Now go to src/app/app.module.ts
Here, the HTTP Module is imported for HTTP Calls to obtain global access.
First, the token from local storage is retrieved. Then the httpRequest req is cloned or replicated, and the header is added to it, which is
Authorization, Bearer: token. Hence the token is formed, which will be sent in the header of the httpRequest. This method can also be applied to standardize all the requests with the Content Type and Accept header injection.
If there is an error response such as 401 or 402, the pipe guides to catch the error and further logic to de-authenticate the user due to bad or unauthorized requests can be implemented. For other error requests, it simply gives back the error in the call to the frontend.
Next, move on to the creation of the Backend.
Form a Directory for the Server and type in npm init to initialize it as a node project,
To install the required libraries, use the command:
Now, let’s generate an app.js in the node_server folder and start coding the backend.
Following is app.js and the boilerplate code:
Generally, a token is generated in a production app, which is also the route for authenticating the user, the login route. Once successfully authenticated, you will send the token.
As we have a route now, a secret for encoding our data and remember a data object, i.e., userData. Therefore, once you decode it, you will get back to this object, so storing a password is not a good practice here, maybe just name and ID.
Let’s run the application and check the token generated.
Listening to 3000.
Being one of the great tools, you can use ‘postman’ to test the routes.
Hence, the first web token is generated successfully.
To illustrate a use case, path1 is created, and the endpoint is secured using JSON Web Token. For this, use express-jwt.
To further illustrate the code, it states that only allow these paths to access the endpoint without token authentication.
Now in the next step, let’s try to access the path without a token sent in the header.
It can be seen that path can’t be accessed. It also sent back a 401 Unauthorized, so that’s great. Now let’s test it with the token obtained from the token/sign route.
As you can see, when adding the Bearer Token, access is received successfully. Heading back to Angular, a new component home is created:
Now, this is home.component.ts file:
So, on the sign In function, a token is requested and stored in local storage. Then on the second function, the path is requested.
Published at DZone with permission of Nicholas Winston. See the original article here.
Opinions expressed by DZone contributors are their own.