Role-based access control (RBAC) is a policy-neutral access-control mechanism defined around roles and privileges. In this section, we'll demonstrate how to implement a very basic RBAC mechanism using Nest guards.
The project is a boilerplate or a simple demonstration of CRUD operations based on authentication cia /auth/login
credentials. After we get the token, are able to reuse among some operations like /auth/profile
and CRUD with /posts
in the project.
The example is called plane/simple, because it doesn't implement the efficient backend, rather than these simple auth tasks. Meaning: no real users, database connections or proper posts
handling.
A progressive Node.js framework for building efficient and scalable server-side applications.
Nest framework TypeScript starter repository.
npm install
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
The app runs on port 3001
of localhost
.
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
Choose among other users who are statically prewritten in UsersService
class.
curl --location 'http://127.0.0.1:3001/auth/login' \
--header 'Content-Type: application/json' \
--data '{
"username":"john",
"password":"changeme"
}'
After succesfully retreaving access_token
, we can reuse it as a Bearer token at any request.
We need to pass a Bearer token in the header of the request, that we retreated after successful auth, for all opeartions on /posts
except GET
, where we only retreave posts that doesn't need authorization and are publicly accessable.
curl --location --request POST 'http://127.0.0.1:3001/users' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEsInVzZXJuYW1lIjoiam9obiIsInJvbGVzIjpbInZlbmRvciIsInVzZXIiXSwiaWF0IjoxNjk5NTYxNzM5LCJleHAiOjE2OTk2MDQ5Mzl9.iV-eF1BzxwHRLMHOt3jMLnm4-WWw4WrtUmRFAG-C-Zc'