-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
docs(techniques/authentication): add refresh-token implementation steps #1468
Open
dinuka-rp
wants to merge
2
commits into
nestjs:master
Choose a base branch
from
dinuka-rp:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -262,7 +262,7 @@ export class LocalStrategy extends PassportStrategy(Strategy) { | |||||
|
||||||
We've followed the recipe described earlier for all Passport strategies. In our use case with passport-local, there are no configuration options, so our constructor simply calls `super()`, without an options object. | ||||||
|
||||||
> info **Hint** We can pass an options object in the call to `super()` to customize the behavior of the passport strategy. In this example, the passport-local strategy by default expects properties called `username` and `password` in the request body. Pass an options object to specify different property names, for example: `super({{ '{' }} usernameField: 'email' {{ '}' }})`. See the [Passport documentation](http://www.passportjs.org/docs/configure/) for more information. | ||||||
> info **Hint** We can pass an options object in the call to `super()` to customize the behavior of the passport strategy. In this example, the passport-local strategy by default expects properties called `username` and `password` in the request body. Pass an options object to specify different property names, for example: `super({{ '{' }} usernameField: 'email' {{ '}' }})`. See the [Passport documentation](http://www.passportjs.org/docs/configure/) for more information. | ||||||
|
||||||
We've also implemented the `validate()` method. For each strategy, Passport will call the verify function (implemented with the `validate()` method in `@nestjs/passport`) using an appropriate strategy-specific set of parameters. For the local-strategy, Passport expects a `validate()` method with the following signature: `validate(username: string, password:string): any`. | ||||||
|
||||||
|
@@ -921,6 +921,159 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'myjwt') | |||||
|
||||||
Then, you refer to this via a decorator like `@UseGuards(AuthGuard('myjwt'))`. | ||||||
|
||||||
#### Refresh-Token Functionality | ||||||
|
||||||
When the JWT strategy is in play, the token will expire within a short time frame and the user will have to re-enter authentication details to generate a new JWT. Instead, the user can be sent a refresh-token together with a JWT at the time of authentication. This refresh-token would preferably have a different secret and a longer expiration time. | ||||||
|
||||||
Since the refresh-token is generated at the same time as the JWT follwing a similar mechanism, it's convenint to keep this within the AuthModule. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Small typo, There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
||||||
But, because the secret and signOptions which contains the expiration time are defined in AuthModule when registering the JwtModule, they will have to be overwritten. | ||||||
|
||||||
Update `constants.ts` in the `auth` folder to contain a new secret for refresh-token mechanism: | ||||||
|
||||||
```typescript | ||||||
@@filename(auth/constants) | ||||||
export const jwtConstants = { | ||||||
secret: 'secretKey', | ||||||
refreshSecret:'refreshSecretKey' | ||||||
}; | ||||||
@@switch | ||||||
export const jwtConstants = { | ||||||
secret: 'secretKey', | ||||||
refreshSecret:'refreshSecretKey' | ||||||
}; | ||||||
``` | ||||||
|
||||||
Create a new JSON object called `options` and pass in the required values as follows: | ||||||
|
||||||
Then, pass this in as a second argument to `this.jwtService.sign()` function when generating the refresh-token in `auth.service.ts`. | ||||||
|
||||||
```typescript | ||||||
@@filename(auth/auth.service) | ||||||
import { Injectable } from '@nestjs/common'; | ||||||
import { UsersService } from '../users/users.service'; | ||||||
import { JwtService } from '@nestjs/jwt'; | ||||||
import { jwtConstants } from './constants'; | ||||||
|
||||||
@Injectable() | ||||||
export class AuthService { | ||||||
constructor( | ||||||
private usersService: UsersService, | ||||||
private jwtService: JwtService | ||||||
) {} | ||||||
|
||||||
async validateUser(username: string, pass: string): Promise<any> { | ||||||
const user = await this.usersService.findOne(username); | ||||||
if (user && user.password === pass) { | ||||||
const { password, ...result } = user; | ||||||
return result; | ||||||
} | ||||||
return null; | ||||||
} | ||||||
|
||||||
async login(user: any) { | ||||||
const payload = { username: user.username, sub: user.userId }; | ||||||
return { | ||||||
access_token: this.jwtService.sign(payload), | ||||||
refresh_token: await this.getRefreshToken(payload), | ||||||
}; | ||||||
} | ||||||
|
||||||
async getRefreshToken(payload: any): Promise<any> { | ||||||
const options = { secret: jwtConstants.refreshSecret, expiresIn: '30d' }; | ||||||
return this.jwtService.sign(payload, options); | ||||||
} | ||||||
} | ||||||
|
||||||
@@switch | ||||||
import { Injectable, Dependencies } from '@nestjs/common'; | ||||||
import { UsersService } from '../users/users.service'; | ||||||
import { JwtService } from '@nestjs/jwt'; | ||||||
import { jwtConstants } from './constants'; | ||||||
|
||||||
@Dependencies(UsersService, JwtService) | ||||||
@Injectable() | ||||||
export class AuthService { | ||||||
constructor(usersService, jwtService) { | ||||||
this.usersService = usersService; | ||||||
this.jwtService = jwtService; | ||||||
} | ||||||
|
||||||
async validateUser(username, pass) { | ||||||
const user = await this.usersService.findOne(username); | ||||||
if (user && user.password === pass) { | ||||||
const { password, ...result } = user; | ||||||
return result; | ||||||
} | ||||||
return null; | ||||||
} | ||||||
|
||||||
async login(user) { | ||||||
const payload = { username: user.username, sub: user.userId }; | ||||||
return { | ||||||
access_token: this.jwtService.sign(payload), | ||||||
refresh_token: await this.getRefreshToken(payload), | ||||||
}; | ||||||
} | ||||||
|
||||||
async getRefreshToken(payload){ | ||||||
const options = { secret: jwtConstants.refreshSecret, expiresIn: '30d' }; | ||||||
return this.jwtService.sign(payload, options); | ||||||
} | ||||||
} | ||||||
``` | ||||||
|
||||||
After this, in order to regenerate the tokens, the following method will be required to be implemented in `AuthService`: | ||||||
|
||||||
```typescript | ||||||
@@filename(auth/auth.service) | ||||||
async regenerateTokens(refresh: any): Promise<any> { | ||||||
const options = { secret: jwtConstants.refreshSecret }; | ||||||
|
||||||
if (await this.jwtService.verify(refresh.refreshToken, options)) { | ||||||
// if the refreshToken is valid, | ||||||
|
||||||
const oldSignedPayload: any = this.jwtService.decode( | ||||||
refresh.refreshToken, | ||||||
); | ||||||
const newUnsignedPayload = { | ||||||
sub: oldSignedPayload.sub, | ||||||
username: oldSignedPayload.username, | ||||||
}; | ||||||
|
||||||
return { | ||||||
access_token: this.jwtService.sign(newUnsignedPayload), | ||||||
refresh_token: await this.getRefreshToken(newUnsignedPayload), | ||||||
}; | ||||||
} | ||||||
} | ||||||
@@switch | ||||||
async regenerateTokens(refresh) { | ||||||
const options = { secret: jwtConstants.refreshSecret }; | ||||||
|
||||||
if (await this.jwtService.verify(refresh.refreshToken, options)) { | ||||||
// if the refreshToken is valid, | ||||||
|
||||||
const oldSignedPayload = this.jwtService.decode( | ||||||
refresh.refreshToken, | ||||||
); | ||||||
const newUnsignedPayload = { | ||||||
sub: oldSignedPayload.sub, | ||||||
username: oldSignedPayload.username, | ||||||
}; | ||||||
|
||||||
return { | ||||||
access_token: this.jwtService.sign(newUnsignedPayload), | ||||||
refresh_token: await this.getRefreshToken(newUnsignedPayload), | ||||||
}; | ||||||
} | ||||||
} | ||||||
``` | ||||||
Notice that here, the expiration time isn't included in `options` and that the oldSignedPayload is used to retrieve the usename & password (sub) for the token regeneration process. | ||||||
|
||||||
Extra steps of validation can be added to this by saving the refresh-token in a Database and checking if the refresh-token exists there when it's requested to be regenerated. | ||||||
|
||||||
|
||||||
#### GraphQL | ||||||
|
||||||
In order to use an AuthGuard with [GraphQL](https://docs.nestjs.com/graphql/quick-start), extend the built-in AuthGuard class and override the getRequest() method. | ||||||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍