GithubHelp home page GithubHelp logo

lokicoule / nestjs-cognito Goto Github PK

View Code? Open in Web Editor NEW
72.0 1.0 7.0 19.93 MB

AWS Cognito utilities module for NestJS.

Home Page: https://www.npmjs.com/package/@nestjs-cognito/auth

License: MIT License

JavaScript 0.69% Shell 0.20% TypeScript 99.12%
aws-cognito chain-of-responsibility nestjs nestjs-cognito amazon-cognito aws cognito typescript

nestjs-cognito's Introduction

@nestjs-cognito

Node.js CI Coverage Status

Hey there! Integrating user authentication into your NestJS application can be a bit overwhelming, especially when you're dealing with the complexities of AWS Cognito. But don't you worry, because NestJS Cognito is here to simplify the entire process for you.

Why go through the hassle of managing Cognito manually when you can take advantage of NestJS Cognito's amazing features? Here are some reasons why you should definitely consider using it:

  • Effortless NestJS Integration: NestJS Cognito makes it super easy to bridge the gap between NestJS and AWS Cognito while utilizing the strengths of both frameworks.
  • Pre-built Modules: With pre-built modules, you can save a lot of development time and handle common Cognito functionalities in a jiffy.
  • Focus on Your App: You can focus on crafting your application's core features instead of spending time on authentication with NestJS Cognito.
  • Enhanced Security: NestJS Cognito uses AWS Cognito's robust security measures, which ensure that your user data is always safe and secure.
  • Simplified Testing: NestJS Cognito comes with dedicated testing modules that make testing your authentication system an absolute breeze.

So, what are you waiting for? Say goodbye to the hassle of raw Cognito and start building amazing NestJS applications with NestJS Cognito!

This package collection includes @nestjs-cognito/core, @nestjs-cognito/auth, @nestjs-cognito/graphql, and @nestjs-cognito/testing.

nestjs-cognito's People

Contributors

kbanman avatar lokicoule avatar p14 avatar renovate[bot] avatar shawngustaw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

nestjs-cognito's Issues

Expecting 'CognitoService' to provide some utility methods like register, login

Hey!
I was expecting @nestjs-cognito/auth would provide something like the following:

import { CognitoService } from @nestjs-cognito/auth

const cognitoService = new CognitoService()
const newUser = await cognitoService.register({ username, email, password })
const tokenPayload = await cognitoService.login({ email, password })

I was trying to create a new cognito user from the nestjs server! so currently I did not find a way to do this using this @nestjs-cognito/auth library.

Thanks :)

sample/02-auth-graphql not working

Hi,
I wanted to execute and test sample/02-auth-graphql. I cloned the repo, cd to sample/02-auth-graphql, run npm install and executed npm run start and got the following error:

src/auth/auth.resolver.ts:1:26 - error TS2724: '"@nestjs-cognito/graphql"' has no exported member named 'CognitoUser'. Did you mean 'GqlCognitoUser'?

1 import { Authentication, CognitoUser } from '@nestjs-cognito/graphql';
                           ~~~~~~~~~~~

  node_modules/@nestjs-cognito/graphql/dist/user/cognito-user.decorator.d.ts:9:22
    9 export declare const GqlCognitoUser: (...dataOrPipes: (string | string[] | import("@nestjs/common").PipeTransform<any, any> | import("@nestjs/common").Type<import("@nestjs/common").PipeTransform<any, any>>)[]) => ParameterDecorator;
                           ~~~~~~~~~~~~~~
    'GqlCognitoUser' is declared here.

Found 1 error(s).

Return `undefined` if used @CognitoUser without @Authentication or @Authorization

Hi. Once again, I would like to thank you for your hard work, and I would want to ask a question.

Can we make changes so that the @CognitoUser decorator returns undefined or null in case the data is unavailable?

My case is a route that is accessible by two different authentication methods: Cognito JWT and another one.

@Post()
  async create(
    @CognitoUser('email') email?: string,
    @Headers(API_KEY_AUTH_HEADER) apiKey?: string,
  ): Promise {

Right now, I'm getting a 500 error and a "message": "Cannot read properties of undefined (reading 'cognito:email'), but I'd like the error not to be thrown, and I could process undefined or null as data from Cognito myself.

Unit tests won't work with `AuthorizationGuard` enabled

Describe the bug
Controllers that utilize AuthorizationGuard are impossible to unit test - they will fail due to missing Cognito dependencies.
I think this is due to the fact that AuthorizationGuard is not real class, and the overrideGuard method is unable to mock it. This causes tests to try loading the entire module, effectively breaking everything.
I have created an example repo which highlights this issue.

To Reproduce
Steps to reproduce the behavior:

  1. See file in this repository: https://github.com/marcin-dlubakowski/nestjs-cognito-unit-testing/blob/main/src/qweasd/qweasd.controller.spec.ts
  2. If you run npm run test in this repo, you will be greeted with failed test:
> jest

 PASS  src/app.controller.spec.ts
 FAIL  src/qweasd/qweasd.controller.spec.ts
  ● QweasdController › /qweasd › should return "Hello World!"

    Nest can't resolve dependencies of the 308c31108bc06f1613772 (?, Reflector). Please make sure that the argument "COGNITO_JWT_VERIFIER_INSTANCE_TOKEN" at index [0] is available in the RootTestModule context.

    Potential solutions:
    - Is RootTestModule a valid NestJS module?
    - If "COGNITO_JWT_VERIFIER_INSTANCE_TOKEN" is a provider, is it part of the current RootTestModule?
    - If "COGNITO_JWT_VERIFIER_INSTANCE_TOKEN" is exported from a separate @Module, is that module imported within RootTestModule?
      @Module({
        imports: [ /* the Module containing "COGNITO_JWT_VERIFIER_INSTANCE_TOKEN" */ ]
      })

       7 |
       8 |   beforeEach(async () => {
    >  9 |     const app: TestingModule = await Test.createTestingModule({
         |                                ^
      10 |       controllers: [QweasdController],
      11 |     })
      12 |       .overrideGuard(AuthorizationGuard)

      at TestingInjector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:254:19)
      at TestingInjector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:207:33)
      at TestingInjector.resolveComponentInstance (../node_modules/@nestjs/testing/testing-injector.js:19:45)
      at resolveParam (../node_modules/@nestjs/core/injector/injector.js:128:38)
          at async Promise.all (index 0)
      at TestingInjector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:143:27)
      at TestingInjector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:70:13)
      at TestingInjector.loadInjectable (../node_modules/@nestjs/core/injector/injector.js:93:9)
      at ../node_modules/@nestjs/core/injector/instance-loader.js:80:13
          at async Promise.all (index 0)
      at TestingInstanceLoader.createInstancesOfInjectables (../node_modules/@nestjs/core/injector/instance-loader.js:79:9)
      at ../node_modules/@nestjs/core/injector/instance-loader.js:41:13
          at async Promise.all (index 1)
      at TestingInstanceLoader.createInstances (../node_modules/@nestjs/core/injector/instance-loader.js:39:9)
      at TestingInstanceLoader.createInstancesOfDependencies (../node_modules/@nestjs/core/injector/instance-loader.js:22:13)
      at TestingInstanceLoader.createInstancesOfDependencies (../node_modules/@nestjs/testing/testing-instance-loader.js:9:9)
      at TestingModuleBuilder.createInstancesOfDependencies (../node_modules/@nestjs/testing/testing-module.builder.js:118:9)
      at TestingModuleBuilder.compile (../node_modules/@nestjs/testing/testing-module.builder.js:74:9)
      at Object.<anonymous> (qweasd/qweasd.controller.spec.ts:9:32)

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.578 s, estimated 2 s
Ran all test suites.```

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
N/A

**Desktop (please complete the following information):**
N/A

**Additional context**

Great start!

Upon googling "nestjs aws cognito", I found this repository.
It seems still new one that much things needs to be implemented yet, but it's a really good start.
And, its structure and architecture looks so professional.
I believe that this package can become a great one.
Expecting much more in future...

`User must have an username` when JWT payload has `username` key

I receive the following error when adding the Authentication() decorator to my controller:

{
	"response": {
	  "statusCode": 401,
           "message": "User must have an username",
           "error": "Unauthorized"
	},
	"status": 401,
	"options": {},
	"message": "User must have an username",
	"name": "UnauthorizedException"
}

The JWT payload is:

{
  sub: "a08464d7-b408-4ab5-b58d-ac75531a9103,
  iss: "https://cognito-idp.eu-west-1.amazonaws.com/...",
  version: 2,
  client_id: "...",
  event_id: "14261d37-e312-4f54-9561-09d19bd7c2a5",
  token_use: "access",
  scope: "openid",
  auth_time: 1676576732,
  exp: 1676578459,
  iat: 1676578159,
  jti: "249d6b08-ff28-4212-a676-9ac2fcf29234",
  username: "a08464d7-b408-4ab5-b58d-ac75531a9103",
}

It appears that you check for cognito:username only, which may be a custom attribute? Could you extend this check to use either cognito:username or username, depending on which one is present on the payload?

const username = payload["cognito:username"]?.toString() ?? null;

Nest can't resolve dependencies of the Service (ConfigService, ?). Please make sure that the argument COGNITO_IDENTITY_PROVIDER_INSTANCE_TOKEN at index [1] is available in the Module context.

I have the following code:

@Module({
  imports: [
    ConfigModule.forRoot({
      cache: true,
      isGlobal: true,
      load: [appConfig],
    }),
    CognitoModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService<ApplicationConfig>) => {
        const cognitoClientID = configService.get('cognitoClientID');
        const cognitoMainRegion = configService.get('cognitoMainRegion');
        const cognitoUserPoolID = configService.get(
          'cognitoUserPoolID',
        ) as string;

        return {
          identityProvider: {
            region: cognitoMainRegion,
          },
          jwtVerifier: {
            clientId: cognitoClientID,
            tokenUse: 'id',
            userPoolId: cognitoUserPoolID,
          },
        };
      },
    }),
   Module,
  ],
})
export class AppModule {}
import {
  CognitoIdentityProvider,
  ListUsersInGroupCommandOutput,
} from '@aws-sdk/client-cognito-identity-provider';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectCognitoIdentityProvider } from '@nestjs-cognito/core';
import { ApplicationConfig } from '../app.config';

@Injectable()
export class Service {
  constructor(
    private configService: ConfigService<ApplicationConfig>,
    @InjectCognitoIdentityProvider()
    private readonly client: CognitoIdentityProvider,
  ) {}

  getList(): Promise<ListUsersInGroupCommandOutput> {
    const poolId = this.configService.get('cognitoUserPoolID');
    const GroupName = this.configService.get('cognitoGroupName');

    console.log(this.client);

    return this.client.listUsersInGroup({
      GroupName: GroupName,
      UserPoolId: poolId,
    });
  }
}

and I have the error:

[Nest] 11596  - 01/08/2024, 4:16:31 PM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the Service (?, ConfigService). Please make sure that the argument COGNITO_IDENTITY_PROVIDER_INSTANCE_TOKEN at index [0] is available in the Module context.

Potential solutions:
- Is Module a valid NestJS module?
- If COGNITO_IDENTITY_PROVIDER_INSTANCE_TOKEN is a provider, is it part of the current Module?
- If COGNITO_IDENTITY_PROVIDER_INSTANCE_TOKEN is exported from a separate @Module, is that module imported within Module?
  @Module({
    imports: [ /* the Module containing COGNITO_IDENTITY_PROVIDER_INSTANCE_TOKEN */ ]
  })

How can i fix it?

Merge PR #448 and #539

          @Lokicoule is it possible to merge this PR? I am currently getting issues because of the fixed peerDependencies  "@nestjs/common": "^8.0.0 || ^9.0.0".

Originally posted by @khenneken in #4 (comment)

Question: db query in authguard.

In the authguard, I would like to set a current user like

const userFromDB = //some query
request[COGNITO_JWT_PAYLOAD_CONTEXT_PROPERTY] = {currentUser: userFromDB}

Is there any good way to do this, other than monkey patch?

Invalid Access Token (@nestjs-cognito/auth)

Hi Loïk,
do you have an idea why I am getting the Invalid Access Token in auth/lib/cognito/cognito.service.ts:42:13?

I am passing the JWT within Authorization header prefixed with Bearer to my backend system. On my frontend I am using Amplify-Auth and I am generating the token with:

const session = await Auth.currentSession();
jwt = session.getIdToken().getJwtToken();

That never made any troubles before 🙈

Support: Multiple Cognito User Pools

Do you know how can I add multiple user pools?

I assume this way will not working at all, right?

imports: [
    CognitoAuthModule.register({
      jwtVerifier: {
        userPoolId: "user_pool_2_id",
        clientId: "client_2_id",
        tokenUse: "id",
      },
    }),
   CognitoAuthModule.register({
      jwtVerifier: {
        userPoolId: "user_pool_id",
        clientId: "client_id",
        tokenUse: "id",
      },
    }),
  ],

`jwksCache` option to avoid a time out error

I encountered a cognito timeout error describe in:
awslabs/aws-jwt-verify#72 (comment)

To avoid this error, jwksCache option is necessary.
To fix this, the code in cognito.utils.js should be like this:
const { userPoolId, clientId, tokenUse = "id", additionalProperties, ...others } = cognitoModuleOptions.jwtVerifier;

Should I make the PR for this?

Support for ID tokens

Hi, I'd like to use ID tokens instead of access tokens because they contain the custom attributes I need for just about every request. From a quick test it seems only access tokens work with this library.

If it's just a matter of implementing this I'd be happy to give it a go.

Refresh Credentials

How can I update these credentials? Since the token I use there is only valid for 4 hours, I wanted to exchange it via a cronjob. How is this intended?

Bildschirm­foto 2023-09-03 um 11 31 44

Feature Request: Support usage of JwtRsaVerifier supported by aws-jwt-verify

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

I would like to use this library in a project using Localstack for development purposes, where the Cognito IDP is at an endpoint such as https://cognito-idp.localhost.localstack.cloud/${userPoolId}.

Describe the solution you'd like
A clear and concise description of what you want to happen.

Expand the jwtVerifier property when registering the CognitoAuthModule to accept input matching the shape outline in the aws-jwt-verify docs here https://github.com/awslabs/aws-jwt-verify?tab=readme-ov-file#using-the-generic-jwt-rsa-verifier-for-cognito-jwts in order to allow custom JWKS issuers.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

I've attempted to set the identityProvider.endpoint property to the Localstack Cognito IDP, which allowed getting the JWKS correctly, but the default CognitoJwtVerifier that seems to be constructed through CognitoAuthModule.registerAsync is defaulting to use the https://cognito-idp.<region>.amazonaws.com domain for token issuer validation purposes, even though the localstack JWKS allows http://localhost.localstack.cloud:4566/<userPoolId> as an issuer.

Additional context
Add any other context or screenshots about the feature request here.

Registering the CognitoAuthModule:

    CognitoAuthModule.registerAsync({
      imports: [forwardRef(() => ConfigModule)],
      useFactory: (configService: ConfigService) => {
        const clientId = configService.get<string>('COGNITO_CLIENT_ID');
        const userPoolId = configService.get<string>(
          'COGNITO_USER_POOL_ID'
        ) as string;
        return {
          jwtVerifier: {
            clientId,
            userPoolId,
            tokenUse: 'access',
            includeRawJwtInErrors: true,
          },
          identityProvider: {
            region: configService.get<string>('COGNITO_REGION');
            endpoint: `https://cognito-idp.localhost.localstack.cloud/${userPoolId}`,
          },
        };
      },
      inject: [ConfigService],
    })

Decorator for websocket and socketIo gateway

Hello,
i don't find any way to authenticate users in gateways.

@Authentication()
@WebSocketGateway({
    namespace: '/messages',
    cors: '*',

})

export class MessagesGateway implements OnGatewayInit, OnGatewayConnection {
    constructor(@InjectModel(Message.name) private messageModel: Model<Message>, @InjectModel(Reaction.name) private reactionModel: Model<Reaction>, private readonly messagesService: MessagesService) { }
    private logger = new Logger('MessagesGateway');
    @WebSocketServer()
    wss: Server;
    handleConnection(client: Socket, @CognitoUser() cognitoJwtPayload: any, ...args: any[]) {
        this.logger.log(`Client: ${cognitoJwtPayload} connected`);
        this.logger.log(`Client connected: ${client.id}`);

    }

The token location will be in client.handshake.auth.

Could you please add this to the package ?

Question | Update tokens

Hello,

First of all thanks for this useful library. We are using the IdToken and registered the module (see below).
How can I update the tokens when the IdToken expires ? Does nestjs-cognito has a flag to be set up in order to automatically update the tokens ?

 CognitoAuthModule.registerAsync({
      imports: [ConfigurationModule],
      inject: [ApiConfigurationService],
      useFactory: async (configurationService: ApiConfigurationService) => ({
        jwtVerifier: {
          userPoolId: configurationService.AWS_COGNITO_USER_POOL_ID,
          clientId: configurationService.AWS_COGNITO_CLIENT_ID,
          tokenUse: 'id',
        },
      }),
    }),

Thanks in advance.

Question: is there a way to load additional user information from database?

@Lokicoule thanks for such a cool library! Quick question for you: i am using access token that is sent from a mobile app to my api. I am assuming using access token is best practice. after this library validates access toke is there a way to "hook" into the process and look up user's aditional information in my own database using email from @CognitoUser?

thank you

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm @types/graphql Unavailable

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/node.js.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/npm-publish.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
npm
package.json
  • @apollo/server 4.11.0
  • @commitlint/cli 19.4.0
  • @commitlint/config-angular 19.3.0
  • @golevelup/ts-jest 0.5.0
  • @nestjs/config 3.2.3
  • @nestjs/core 10.3.10
  • @nestjs/platform-express 10.3.10
  • @nestjs/testing 10.3.10
  • @types/graphql 14.5.0
  • @types/jest 29.5.12
  • @types/node 20.14.15
  • @types/node-fetch 3.0.3
  • @types/normalize-path 3.0.2
  • @types/ws 8.5.12
  • @typescript-eslint/eslint-plugin 8.1.0
  • @typescript-eslint/parser 8.1.0
  • class-transformer 0.5.1
  • class-validator 0.14.1
  • coveralls 3.1.1
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-import 2.29.1
  • eslint-plugin-prettier 5.2.1
  • graphql 16.9.0
  • husky 9.1.4
  • jest 29.7.0
  • lerna 8.1.8
  • lerna-changelog 2.2.0
  • lint-staged 15.2.9
  • pactum 3.7.1
  • prettier 3.3.3
  • reflect-metadata 0.2.2
  • rimraf 6.0.1
  • rxjs 7.8.1
  • supertest 7.0.0
  • ts-jest 29.2.4
  • ts-node 10.9.2
  • typescript 5.5.4
  • whoami ^0.0.3
packages/auth/package.json
  • aws-jwt-verify ^4.0.0
  • @nestjs/jwt ^10.0.1
  • @nestjs/testing 10.3.10
packages/core/package.json
  • @aws-sdk/client-cognito-identity-provider 3.627.0
  • @nestjs/common 10.3.10
  • @nestjs/testing 10.3.10
  • @types/jest 29.5.12
  • aws-jwt-verify ^4.0.0
  • @aws-sdk/client-cognito-identity-provider 3.627.0
  • @nestjs/common ^8.0.0 || ^9.0.0 || ^10.0.0
  • aws-jwt-verify ^3.4.0 || ^4.0.0
packages/graphql/package.json
  • @apollo/server 4.11.0
  • @nestjs/apollo 12.2.0
  • @nestjs/graphql 12.2.0
  • @nestjs/jwt 10.1.0
  • @nestjs/testing 10.3.10
packages/testing/package.json
  • @aws-sdk/client-cognito-identity-provider 3.627.0
sample/01-auth/package.json
  • @nestjs-cognito/auth ^1.0.2
  • @nestjs/common 10.3.10
  • @nestjs/core 10.3.10
  • @nestjs/platform-express 10.3.10
  • reflect-metadata 0.2.2
  • rimraf 6.0.1
  • rxjs 7.8.1
  • @nestjs/cli 10.4.4
  • @nestjs/schematics 10.1.3
  • @types/express 4.17.21
  • @types/node 20.14.15
  • @typescript-eslint/eslint-plugin 8.1.0
  • @typescript-eslint/parser 8.1.0
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-prettier 5.2.1
  • prettier 3.3.3
  • ts-loader 9.5.1
  • ts-node 10.9.2
  • tsconfig-paths 4.2.0
  • typescript 5.5.4
sample/02-auth-graphql/package.json
  • @nestjs-cognito/auth ^1.0.2
  • @nestjs-cognito/graphql ^2.0.0
  • @nestjs/apollo 12.2.0
  • @nestjs/common 10.3.10
  • @nestjs/core 10.3.10
  • @nestjs/graphql 12.2.0
  • @nestjs/platform-express 10.3.10
  • @apollo/server 4.11.0
  • graphql 16.9.0
  • reflect-metadata 0.2.2
  • rimraf 6.0.1
  • rxjs 7.8.1
  • @nestjs/cli 10.4.4
  • @nestjs/schematics 10.1.3
  • @types/express 4.17.21
  • @types/node 20.14.15
  • @typescript-eslint/eslint-plugin 8.1.0
  • @typescript-eslint/parser 8.1.0
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-prettier 5.2.1
  • prettier 3.3.3
  • ts-loader 9.5.1
  • ts-node 10.9.2
  • tsconfig-paths 4.2.0
  • typescript 5.5.4

  • Check this box to trigger a request for Renovate to run again on this repository

Randomly faced a 401 authentication failure upon starting the server

When I start the dev server locally, I notice that the first three or four requests to an API with @UseGuards(AuthenticationGuard) result in a 401 authentication failure.

However, after retrying the request a few times, it starts to work. I am unsure about the root cause of this flaky behavior. Here is how my API is set up.

user.controller.ts

...
  @Get('')
  @UseGuards(AuthenticationGuard)
  @ApiBearerAuth()
  @ApiOkResponse({ type: UserEntity })
  @ApiOperation({ summary: 'Get the current user' })
  async getUserByAmplifyUserId(@CognitoUser() cognitoJwtPayload): Promise<User> {
    return await this.userService.user({ amplifyUserId: cognitoJwtPayload.sub })
  }
...

app.module.ts

...
@Module({
  imports: [
    ConfigModule.forRoot(),
    CognitoAuthModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        jwtVerifier: {
          userPoolId: configService.get('COGNITO_USER_POOL_ID'),
          clientId: configService.get('COGNITO_CLIENT_ID'),
          tokenUse: 'id',
        },
      }),
      inject: [ConfigService]
    }),
    ...
})
export class AppModule { }

my package versions:

  • @nestjs/common 10.2.10
  • @nestjs/core 10.2.10
  • @nestjs-cognito/auth 1.0.11
  • @nestjs-cognito/core 1.1.7

Question: Is there a way to define public routes if whole controller uses `@Authentication()` decorator?

@Lokicoule Is there a way to define public routes if whole controller uses @Authentication() decorator? basically i would like /config endpoint to not require JWT token.

for example i have following code:

import { Authentication, AuthenticationGuard, CognitoUser } from '@nestjs-cognito/auth';

@Authentication()
@Controller(URL)
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private userActivityService: UserActivityService
  ) {}

  /**
   * Returns the user object based on the JWT token.
   *
   * @param {User} authUser
   * @returns {Promise<UserResponse>}
   * @memberof AuthController
   */
  @ApiBearerAuth()
  @UseGuards(AuthenticationGuard)
  @Get()
  async getUserWithToken(@CognitoUser() authUser: User): Promise<UserWithFavorites> {
    const favorites = await this.userActivityService.getUserFavorites(authUser.id);
    return {
      ...authUser,
      favorites
    };
  }
  //////////////////////////////////////////////////////////
  // is there a way to make this public?
  //////////////////////////////////////////////////////////
  @ApiBearerAuth()
  @Get('config')
  async getConfig(): Promise<ConfigResponse> {
    return this.authService.getConfig();
  }
}

Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.