This project purpose is to learn about JWT auth flow, using TypeScript.
-
Install both:
You will need to have MongoDB running on port 27017.
-
Clone the project:
git clone https://github.com/AloisCRR/ts-api-users.git
-
Go to the project directory:
cd ts-api-users
-
Install dependencies:
npm install
-
Start the dev server:
npm run dev
REST API will run in http://localhost:3000.
-
To compile TypeScript to JavaScript and run the project:
npm run build && npm start
POST /signup
Body | Type | Description |
---|---|---|
email |
string |
Required. User email address |
password |
string |
Required. Account password |
POST /signin
Body | Type | Description |
---|---|---|
email |
string |
Required. User email address |
password |
string |
Required. Account password |
GET /auth
Headers | Type | Description |
---|---|---|
Authentication |
JWT |
Required. Jwt given on sign in or sign up |
Basic input validation
Invalid password or email
Successful sign in
Sending token on headers
Authorization
Name | Description |
---|---|
Node.js | Business logic |
MongoDB | Database |
Express | HTTP Server |
TypeScript | JavaScript super-set to add static code analysis |
JWT | Library to generate JWTs |
Mongoose | ODM (Object Data Modeling) |
Passport JWT | Passport strategy for authenticating with a JSON Web Token. |
Bcrypt | Algorithm used to hash passwords. |
import { Router } from "express";
import { signIn, signUp } from "../controllers/user.controller";
const router = Router();
router.post("/signup", signUp);
router.post("/signin", signIn);
export default router;
router.get(
"/auth",
passport.authenticate("jwt", { session: false }),
(req, res) => {
res.status(200).json({ msg: "Auth route succeeded" });
}
);
function createToken(user: Iuser) {
return jwt.sign({ id: user.id, email: user.email }, config.jwtSecret, {
expiresIn: 86400,
});
}
Works in this way... With JWT obviously you can generate a token for authentication, a token can hold public data in a stateless way. Public info is like the algorithm used to sign token or the type of token, also included something called "payload" which is content or body of token (this includes all data registered for token).
To generate a token we use a function from jwt module called sign, passing a "payload" that is information that token will save, and a secret used to sign the token.
Token is signed by a private key, and with the same key we can check if token is valid and use it to authenticate an user, passport takes his time in this, with passport-jwt we can use a function called passport.authenticate() which is a middleware that handles all the logic from getting the token from auth header to validate it and attach the token payload to the request object of express.
- App functionality
- Testing
- Hosting, domain, etc.
- CI/CD