Developing a Secure API with NestJS

Would you consider writing a followup article with a canonical implementation of Auth0 for NestJS + Angular SSR using @nestjs/angular-universal? NestJS + Angular Universal is a great stack, but getting auth working on it isn’t as straightforward as it could be.

I’ve got a version of it with Angular 14 / NestJS 9 almost working, after setting up a reverse proxy for https, enabling helmet, creating a mock auth service to load during the server-side portion of the render, wrapping the Auth0 service, and reconfiguring the Token Endpoint Authentication Method in Auth0 app config from Post to None.

1 Like

Howdy! Welcome to the Auth0 Community! :wave:

Let me share this feedback internally with other developer advocates to see if that’s a topic they’d like to cover. I am personally not well-versed on Angular anymore but Angular Universal sounds and looks very interesting.

getting auth working on it isn’t as straightforward as it could be.

What are current pain points that developers experience when implementing authentication or authorization in that stack?

Thanks Dan!

On the Angular side, configuring auth0-angular for SSR was the biggest pain point, since I needed to implement a mock service for running on server-side and wrap the client. This issue provided the info needed to get it working. On the Nest side, configuring the Auth0 strategy correctly is my current sticking point, and there’s very little information to work from when debugging. Although I’m now able to authenticate on the client side (which didn’t work until I set up an https reverse proxy, enabled helmet in Nest, and set token endpoint authentication method to None in Auth0 config), authorization isn’t working yet- I still get 401 on endpoints protected with my Auth0 AuthGuard, despite having authenticated on the client side successfully. I assume there’s some mismatch between the client and server config causing that, as the Auth0 strategy in Nest is set up the same as in your tutorial here. A full-stack example would be really helpful!

1 Like

Thanks for this feedback! I have shared it with our internal Angular community group. Angular Universal is not a common use case that comes up but it’s worth taking a look in more detail on how we could play a role in that stack. If any research or insight comes up, we’ll share it here :slight_smile:

Hi
I am having an issue with the WAB client not singing into auth0 or connecting to the API. I have the same URL in the settings and in postman: http://localhost:8000/api/v1/items

I can connect to the API from postman with the get.
Could you let me know the info I need to use from postman to send in the correct credentials. It is currently throwing an authorised error.
Many thanks

1 Like

Thanks for reading this blog post. I’ll investigate this issue today :slight_smile:

1 Like

Thanks a lot for that Dan!

Hi,
I am following the blog: Developing a Secure API with NestJS: Managing Identity

I am attempting to connect the test WAB application to API.
I can connect with postman with the URL http://localhost:8000/api/v1/items but the WAB client says “Network Error. Unable to retrieve menu information.”
In the API I have cors.enable()

Could you assist with this step in the blog?

Many thanks

Chris

1 Like

Howdy, I am following the tutorial but I am not getting that error. I was going to suggest enabling CORS but you’ve already taken that step from what you stated :thinking:

What browser are you using?

1 Like

Please verify that the following URL is set as the value of the “Auth0 Callback URL” field in the “Settings” for the WAB Dashboard demo app :pray:

https://dashboard-v1.whatabyte.app/home

I need to update the default value that shows up in there to reflect the new URL.

1 Like

I have the below in the setting as

https://dashboard-v1.whatabyte.app/home

It is now calling the back end. Thanks

1 Like

Awesome. Let us know if you have any other questions, please.

1 Like

Hi, when I click the sign-in button I get a window opening and immediately closing. I am using Firefox 110.0

1 Like

To clarify: Do you mean that the pop-up window is not coming up with the login box? If so, please ensure that your browser is not blocking pop-ups.

1 Like

Hi ,
Thanks for the popup blocker suggestion. I can now signin

1 Like

I am attempting to plug the security into an existing API but am getting 401 error
The call from wab menu based on logging output is to the below within the items module.

@UseGuards(AuthGuard('jwt'))
  @Get(':id')
  async find(@Param('id') id: number) {
}

The link in WAB settings base URL is

http://localhost:8000/api/v1/items

authz.module.ts

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';

import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [PassportModule.register({ defaultStrategy: 'jwt' })],
  providers: [JwtStrategy],
  exports: [PassportModule],
})
export class AuthzModule {}

jwt-authentication.guard.ts

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export default class JwtAuthenticationGuard extends AuthGuard('jwt') {}

jwt.strategy.ts is

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import * as dotenv from 'dotenv';
import { passportJwtSecret } from 'jwks-rsa';
import { ExtractJwt, Strategy } from 'passport-jwt';

dotenv.config();

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `${process.env.AUTH0_ISSUER_URL}.well-known/jwks.json`,
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: process.env.AUTH0_AUDIENCE,
      issuer: `${process.env.AUTH0_ISSUER_URL}`,
      algorithms: ['RS256'],
    });
  }

  validate(payload: unknown): unknown {
    return payload;
  }
}

Can you give any pointers as to why this would not be working?

1 Like

I am glad to hear that you can sign in using the pop-up method – I really like that method myself.

Do you need to use Passport.js for your NestJS app? If not, I am going to be release a new NestJS code sample for our Auth0 Developer Center Resources. As I went through this tutorial, I realized that it is not using the best approach to handle some things in NestJS. Our new code sample will use a simpler library to integrate with Auth0 and also simpler and better error handling for the guards. I estimate we’ll go live with it today or tomorrow.

I can share a link here once it’s ready. Updating this blog post will take a bit longer and likely we’ll start by having a quick Developer Guide on the Developer Center as that would focus on implementing authorization on an existing API instead of starting from scratch.

1 Like

A link to the developer guide to add to an existing API would be great as that is what I am looking to do.
Thanks

1 Like

We have the new code sample page ready :eyes:

We’ll have the guide ready later on! But this should give you a good start. Check out the basic-authorization branch and look at the src/authorization/authorization.guard.ts to see how we implement a NestJS decorate to act as an authorization guard.

2 Likes

Thanks for this link

1 Like