Validate permissions

Permissions allow us to limit the access to a group of resources. You should be aware that authentication is not enough if we want to secure our backend APIs. To implement permissions, open the admin-api.js file and apply the following changes:

...
const auth =require('express-jwt')
const guard = require('express-jwt-permissions')()

const updateScore = async (matchId, teamId) => {
...
}

api
.route('/admin/match/:id?')
.post(auth({ secret: 's3cret'}),
guard.check('admin:create:match'),
(req, res, next) => {

...

})
...

First, we start by initializing a guard constant. Secondly, we call guard.check; this function will look for the admin:create:match permission in the JWT. Remember that these permissions have to be present in the token. If the user has permission, the flow will continue and the new Match will be created. Otherwise, we will receive a Could not find permissions error.

Let's try to create a new Match; execute the following command:

$ curl -X POST -H "Content-type: application/json" -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWRtaW4iLCJpYXQiOjE1MTk2OTgyMjksImV4cCI6MTUxOTcwOTAyOX0.HQiz-NbBDBc9kVyBRNUeMsrDexEsk92WXoRyijNp1Rk" -d '{"team_1": "Peru", "team_2": "Brasil", "score": { "team_1": 80, "team_2": 5} }'  localhost:3000/admin/match/

{"error":"Permission Denied"}

That's interesting! Although we are authenticated and are passing a valid token, why are we not able to create the Match? Let's look at the user token generation logic. Open the security-api.js file:

...
const logIn = (username, password) => {
if (username == 'admin' && password == 'admin') {

let userData = {
name: "Admin"
}

return generateToken(userData)

} else {
return null
}

}
...

As you can see, our token doesn't have the permissions defined. Let's fix this by adding the right permissions:

...    
let userData = {
name: "Admin",
permissions: ["admin:create:match"]

}
...

That's all. Let's generate a new token by logging in again, and let's test things out.

First, execute the following command to generate a valid token:

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

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWRtaW4iLCJpYXQiOjE1MTk2OTk4MzIsImV4cCI6MTUxOTcxMDYzMn0.cVTtJHcbQ2J76s6uRjuySCWq4dKXlNzAfInl0ZLgri

Cool! this new token contains the permissions. Next, let's try to create the new Match again by passing this new token:

$ curl -X POST -H "Content-type: application/json" -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWRtaW4iLCJpYXQiOjE1MTk2OTgyMjksImV4cCI6MTUxOTcwOTAyOX0.HQiz-NbBDBc9kVyBRNUeMsrDexEsk92WXoRyijNp1Rk" -d '{"team_1": "Peru", "team_2": "China", "score": { "team_1": 5, "team_2": 5} }'  localhost:3000/admin/match/

{"__v":0,"team_1":"Peru","team_2":"China","_id":"5a94c87987d2820a0d1931e7","score":{"team_1":5,"team_2":5}}

Hot dog! We are now able to manage authentication and authorization in our backend API. Of course, you can improve this security authentication by saving a collection of users in a MongoDB database and create different users with different roles. Also, implement log out using express-jwt-blacklist and in another fashion, but for the purpose of this book, we are good with this basic implementation. Keep reading!

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

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