The authentication REST controller

We have already defined the route that will be responsible to make our logic available as a REST endpoint, so the only step required is to call our logIn function. Go ahead and apply the following change:

...

const generateToken = (userData) => {
return jwt.sign(userData, "s3cret", { expiresIn: '3h' })
}


api
.route('/auth')
.post((req, res, next) => {
let { username, password } = req.body
let token = logIn(username, password)
if (token) {
res.send(token)
} else {
next(new Error("Authentication failed"))
}
})


module.exports = api

First, we extract the username and password from the req.body object. After that, we call the logIn function and host the result in the token variable. If the token is not null, we respond with a successful response by calling the res.send function. If the token is null, we pass an Error object into the next parameter, which will raise a global exception along with a failed response.

Lastly, we have to modify the server.js file to register our API to express, as follows:

const express = require('express')
..
const seurityApi = require('./src/routes/security-api')
const mongooseConfig = require('./src/config/mongoose-connection')
const app = express()

app.use(bodyParser.json())
app.use(teamsApi)
app.use(seurityApi)
...

Now we are ready to test our implementation. In a new Terminal window, run the following curl command:

$ curl -X POST -H "Content-type: application/json" -d '{"username":"admin", "password":"admin"}' localhost:3000/auth

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWRtaW4iLCJpYXQiOjE1MTk1NzYwMDEsImV4cCI6MTUxOTU4NjgwMX0.4cNGYgz_BZZz5GEfN6MS3pkreGTkUBqJS1FZVC3_ew

If everything is well implemented, you should receive an encrypted JWT as a response.

Cool! It's time to play with authorization. Keep reading!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.23.181