Skip to content

Commit

Permalink
Update JwtProvider configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
hhfrancois committed Jan 2, 2024
1 parent ea60cfa commit b47ab53
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,14 @@ Jwt Provider
`AppModule.ts`
```typescript
@Module({
// Declare the module and define the option apply (for apply or not the security)
// Declare the module and define the option apply (for apply or not the security) and GrantedInfoJwtProvider (for decode user info from jwt token)
imports: [
GrantedModule.forRoot({apply: environment.applyAuthGuard, infoProvider: new GrantedInfoJwtProvider('-----BEGIN PUBLIC KEY-----\nMIIBIj...IDAQAB\n-----END PUBLIC KEY-----', 'RS256')}),
GrantedModule.forRoot({apply: environment.applyAuthGuard, infoProvider: new GrantedInfoJwtProvider({
algorithm: 'RS256', // RS256, EC256, PS256
pemFile: 'path/jwt_public_key.pem',
// or
base64Key: '-----BEGIN PUBLIC KEY-----\nBASE64KEYENCODED\n-----END PUBLIC KEY-----'
})}),
],
})
export class AppModule {}
Expand Down
18 changes: 16 additions & 2 deletions src/services/granted-info.jwt-provider.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { Request } from 'express';
import * as fs from 'fs';
import { IncomingMessage } from "http";
import { Algorithm, decode, verify } from 'jsonwebtoken';
import { IGrantedInfoProvider } from "./igranted-info.provider";
import { verify, decode, Algorithm } from 'jsonwebtoken';

export class GrantedInfoJwtProvider implements IGrantedInfoProvider {

constructor(private base64Key?: string, private algorithm?: Algorithm) { // 'RS256'
base64Key: string;
algorithm: Algorithm;

constructor(conf: {pemFile?: string, base64Key?: string, algorithm?: Algorithm}) { // 'RS256'
this.base64Key = conf.base64Key;
this.algorithm = conf.algorithm || 'RS256';
if (conf.pemFile) {
this.base64Key = fs.readFileSync(conf.pemFile, 'utf8');
}
}

getUsernameFromRequest(request: Request): string {
Expand Down Expand Up @@ -81,6 +90,11 @@ export class GrantedInfoJwtProvider implements IGrantedInfoProvider {
try {
return verify(token, this.base64Key, { algorithms: [this.algorithm] });
} catch (err) {
console.log(`Error while decoding JWT.`);
console.log(`Token: ${token}`);
console.log(`Algorithm: ${this.algorithm}`);
console.log(`Public Key: ${this.base64Key}`);

console.error(err);
return {};
}
Expand Down

0 comments on commit b47ab53

Please sign in to comment.