- * Authenticate a user by verifying their "credentials" (such as username/password, JSON Web Token (JWT), or identity token from an Identity Provider)
- * Manage authenticated state (by issuing a portable token, such as a JWT, or creating an Express session)
- * Attach information about the authenticated user to the
Request
object for further use in route handlers
Authentication requirements :
* Let's flesh out our requirements. For this use case, clients will start by authenticating with a username and password. Once authenticated, the server will issue a JWT that can be sent as a bearer token in an authorization header on subsequent requests to prove authentication. We'll also create a protected route that is accessible only to requests that contain a valid JWT.
First we need to install the required packages. Passport provides a strategy called passport-local that implements a username/password authentication mechanism, which suits our needs for this portion of our use case.
npm install --save @nestjs/passport passport passport-local
npm install --save-dev @types/passport-local
NOTICE
For any Passport strategy you choose, you'll always need the @nestjs/passport
and passport
packages. Then, you'll need to install the strategy-specific package (e.g., passport-jwt
or passport-local
) that implements the particular authentication strategy you are building. In addition, you can also install the type definitions for any Passport strategy, as shown above with @types/passport-local
, which provides assistance while writing TypeScript code.
npm i bcrypt
npm i -D @types/bcrypt
hash
function, as follows: import * as bcrypt from 'bcrypt';
JWT functionality#
We're ready to move on to the JWT portion of our auth system. Let's review and refine our requirements:
- Allow users to authenticate with username/password, returning a JWT for use in subsequent calls to protected API endpoints. We're well on our way to meeting this requirement. To complete it, we'll need to write the code that issues a JWT.
- Create API routes which are protected based on the presence of a valid JWT as a bearer token
We'll need to install a couple more packages to support our JWT requirements:
npm install --save @nestjs/jwt passport-jwt
npm install --save-dev @types/passport-jwt
app.service.ts
Output :
Login page:
app.controller.ts
app.service.ts
Output :
password or email incorrect to show the error message :