Skip to content

Commit c825727

Browse files
committed
docs(authentication): fix incorrect jwt response
- Payload should have key `sub` instead of `userId` - Add missing quotation mark
1 parent 2a72046 commit c825727

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

content/security/authentication.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,7 @@ export class AuthService {
237237
if (user?.password !== pass) {
238238
throw new UnauthorizedException();
239239
}
240-
const payload = { username: user.username, sub: user.userId };
240+
const payload = { sub: user.userId, username: user.username };
241241
return {
242242
access_token: await this.jwtService.signAsync(payload),
243243
};
@@ -449,11 +449,11 @@ $ # result -> {"statusCode":401,"message":"Unauthorized"}
449449

450450
$ # POST /auth/login
451451
$ curl -X POST http://localhost:3000/auth/login -d '{"username": "john", "password": "changeme"}' -H "Content-Type: application/json"
452-
$ # result -> {"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vybm... }
452+
$ # result -> {"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vybm..."}
453453

454454
$ # GET /profile using access_token returned from previous step as bearer code
455455
$ curl http://localhost:3000/auth/profile -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vybm..."
456-
$ # result -> {"userId":1,"username":"john"}
456+
$ # result -> {"sub":1,"username":"john","iat":...,"exp":...}
457457
```
458458

459459
Note that in the `AuthModule`, we configured the JWT to have an expiration of `60 seconds`. This is too short an expiration, and dealing with the details of token expiration and refresh is beyond the scope of this article. However, we chose that to demonstrate an important quality of JWTs. If you wait 60 seconds after authenticating before attempting a `GET /auth/profile` request, you'll receive a `401 Unauthorized` response. This is because `@nestjs/jwt` automatically checks the JWT for its expiration time, saving you the trouble of doing so in your application.

0 commit comments

Comments
 (0)