How authentication works in rest Api


Restful APIs is Stateless Server so it is different then our server validation what we normally use for our backend. but in case of REST APIs we will use a different approach


We will still check the combination of Email and password but then instead, we return a so-called token to the client. That token will be generated on the server and will hold some information which can only be validated by the server and this token will then be stored in the client, so there in storage in the browser, there are specific storage mechanisms for this and the client can then attach this token to every subsequent request it sends to the server.

So this stored token is then attached to every request that targets a resource on the server which requires authentication. That token can only be validated by the server which created the token and if you change that token on the frontend or you try to create it to fake that you are authenticated, that will be detected because the server used a certain algorithm for generating the token which you can't fake because you don't know it or you don't know the private key used by that server for generating the token to be precise. That token contains json data or JavaScript data in the end plus a signature which as I mentioned is generated on the server with a special private key which is only stored on the server and this gives us a so-called json web token. This json web token is then returned to the client and the signature as we know can only be verified by the server, so you can't edit or create the token on the client. Well you can but then the server will detect this and will treat the token as invalid.

This is how we implement Authentication in rest API

We have the token which can be checked by the server but which does not to be stored on the server and this gives us an elegant way of authenticating requests in a rest API world.



Implementing Authentication:-

First lets make the router function




First lets install another package

npm install --save jsonwebtoken


now lets import into our controller and start working on the token

const jwt = require('jsonwebtoken')


jwt.sign() this creates a new signature and packs that into a new json web token. We can add any data we want into


exports.login = (req, res, next) => { const email = req.body.email; const password = req.body.password; let loadedUser; User.findOne({ email: email }) .then(user => { if (!user) { const error = new Error('A user with this email address could not exist') error.statusCode = 401; throw error; } loadedUser = user; return bcrypt.compare(password, user.password) }) .then(isEqual => { if (!isEqual) { const error = new Error('Wrong Password') error.statusCode = 401; throw error; }


const token = jwt.sign({ email: loadedUser.email, userId: loadedUser._id.toString() }, 'Asecretkey', //key must be bigger then mine it can be anything { expiresIn: '1h' }) res.status(200) .json({ token: token, userId: loadedUser._id.toString() }) }) .catch(err => { if (!err.statusCode) { err.statusCode = 500; } next(err); }) }

This is the code of our authentification on the server side and that will generate the token autmatically and on the frontend if you know REACT then it will be easy other wise we need

loginHandler = (event, authData) => { event.preventDefault(); this.setState({ authLoading: true }); fetch('http://localhost:8080/auth/login', { method: 'POST', headers: { 'content-Type': 'application/json' }, body: JSON.stringify({ email: authData.email, password: authData.password }) })

A minimum of this code we need promises too but we can work with this much content too.


After logged in we can check our token too

go to jwt.io

there paste your token

HOW TO FIND THE TOKEN

  1. go to inspect on google chrome and

  2. click on application

now copy that token and again go to jwt


paste your token on the left side and

we write a server side key 'Asecretkey'

Now to validate

Paste your key here and you will see that our token didnot change otherwise if you change any single detail the token will change entirely











1 view0 comments

Recent Posts

See All

SQL UNION Operator UNION operator is used to combine the results of two or more SELECT statements Every SELECT statement within UNION must have the same number of columns The columns must also have si

JOIN clause is used to combine rows from two or more tables. INNER JOIN === selects records that have matching values in both tables SELECT Orders.OrderID, Customers.CustomersID, Orders.OrdersDate FRO