Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 42 ยท Projects

Project: Auth Service

Build an auth service in NestJS: registration, password hashing, login, JWT access tokens, a global guard, roles, and rotating refresh tokens.

Almost every API needs to know who is calling it. In this project you design a small auth service: people register with an email and a password, log in to receive tokens, call protected routes with a token, and are limited by roles. Access tokens expire quickly, and long-lived refresh tokens rotate so that a stolen one is detected. It builds on Guards and Authorization and Authentication with JWT; read those first if guards or JwtService are new to you.

The Nest code is read-only because it needs Node, npm and a database. The runnable stand-ins implement the same service logic in plain Node with node:crypto: salted scrypt password hashes, HS256 tokens signed by hand, a guard with roles, and refresh-token rotation with reuse detection. They show the real mechanics, but they are teaching code. In production use the maintained libraries named below.

The flow

Register Store a password hash, never the password.
Login Get a short access token and a refresh token.
Guard Verify the token on every request.
Refresh Swap an old refresh token for a new pair.
1 / 2

Design decisions

Decision Choice Why
Password storage A slow hash with a per-user salt (argon2 or bcrypt in real code) A leaked table should not reveal passwords
Access token JWT, 15 minutes, signed with a secret Stateless checks, no lookup per request
Refresh token Random opaque string, stored hashed, rotated on use It can be revoked, and reuse is detectable
Protection Global guard plus @Public() for exceptions New routes are secure by default
Roles @Roles('admin') metadata read by a second guard One generic guard, declarative routes
Role at signup Never accepted from the client Prevents self-promotion (mass assignment)

The Nest side (read-only)

Install @nestjs/jwt, argon2 (or bcrypt) and the validation packages. The module wires the pieces:

TypeScript
// auth.module.ts
@Module({
  imports: [
    UsersModule,
    JwtModule.registerAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        secret: config.getOrThrow('JWT_SECRET'),
        signOptions: { expiresIn: '15m' },
      }),
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, { provide: APP_GUARD, useClass: AuthGuard }],
})
export class AuthModule {}

The service registers, logs in and refreshes:

TypeScript
@Injectable()
export class AuthService {
  constructor(
    private readonly users: UsersService,
    private readonly jwt: JwtService,
    private readonly refreshTokens: RefreshTokenRepository,
  ) {}

  async register(dto: RegisterDto) {
    if (await this.users.findByEmail(dto.email)) throw new ConflictException('Email already registered');
    const passwordHash = await argon2.hash(dto.password);
    return this.users.create({ email: dto.email, passwordHash, roles: ['user'] });
  }

  async login(dto: LoginDto) {
    const user = await this.users.findByEmail(dto.email);
    const valid = user && (await argon2.verify(user.passwordHash, dto.password));
    if (!valid) throw new UnauthorizedException('Invalid email or password');
    return this.issueTokens(user);
  }

  private async issueTokens(user: User, family = randomUUID()) {
    const accessToken = await this.jwt.signAsync({ sub: user.id, roles: user.roles });
    const refreshToken = randomBytes(32).toString('base64url');
    await this.refreshTokens.save({ hash: sha256(refreshToken), userId: user.id, family });
    return { accessToken, refreshToken };
  }
}

The guard checks the bearer token and honors @Public():

TypeScript
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private jwt: JwtService, private reflector: Reflector) {}

  async canActivate(context: ExecutionContext) {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(), context.getClass(),
    ]);
    if (isPublic) return true;

    const request = context.switchToHttp().getRequest();
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    if (type !== 'Bearer' || !token) throw new UnauthorizedException();
    try {
      request.user = await this.jwt.verifyAsync(token);
    } catch {
      throw new UnauthorizedException();
    }
    return true;
  }
}

A RolesGuard (registered after it) compares request.user.roles with the @Roles() metadata, exactly as in the guards lesson. The controller marks register, login and refresh as @Public() and leaves everything else protected. Add rate limits on login, and put the JWT secret in validated configuration.

The stand-in: primitives first

Before the service, here are the primitives. The first demo hashes passwords with scrypt and a random salt (the same password gives different hashes, and verification is constant-time), then signs and verifies an HS256 token by hand. A JWT is just three base64url parts: a header, a payload and an HMAC signature over the first two.

Node.js Password hashing and a hand-made HS256 token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The tampered token keeps the original signature but carries a changed payload that claims admin. The signature no longer matches, so verification refuses it. Note that a JWT payload is encoded, not encrypted: anyone can read it, so never put secrets in it. Real code should use JwtService (the jsonwebtoken library underneath), which also handles algorithms, nbf, issuer and audience checks.

The stand-in: the full service

The second demo is the service plus a request dispatcher with a global guard and roles, driven by a client session with a fake clock so expiry is deterministic. It implements registration without a client-supplied role, login, protected routes, role checks, and refresh-token rotation with reuse detection: every refresh token can be used once, and presenting a used one revokes the whole family, because it means the token was stolen or replayed.

Node.js Register, login, guard, roles and rotating refresh tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the session top to bottom. The guard answers 401 for a missing, tampered or expired token and the roles guard answers 403 for a valid token that lacks the role. Registering with a roles field is refused, so nobody can make themselves an admin. The refresh flow is the interesting part: the first use of a refresh token returns a new pair, but replaying the old token is treated as theft, and it also kills the new token from the same family. The honest user simply logs in again.

What a production version adds

  • argon2 or bcrypt instead of scrypt parameters chosen by hand, with tuned cost.
  • Persistent storage: users and refresh-token hashes in a database, with an expiry date and cleanup of old rows (Repositories, Entities and Relations).
  • Cookies for refresh tokens: an HttpOnly, Secure, SameSite cookie keeps the refresh token away from page scripts, which needs CSRF thought (Security and Hardening).
  • Logout by deleting the refresh family, and password change by revoking all families.
  • Email verification, password reset, throttling and lockout, plus audit logs.
  • Key rotation: a kid header and several valid keys, or asymmetric signing so other services can verify without knowing the secret.

Or you might not build it at all: for many products a managed identity provider is the better choice, with Nest only verifying its tokens.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the refresh token stored as a hash in the database?

    Like passwords, refresh tokens are credentials. Storing only a hash means a database leak does not reveal tokens that can be presented.
  2. 2. Alice presents a refresh token that was already used once. What should the service do?

    A rotated token should never come back. If it does, either the honest user or an attacker holds a copy, so the family is revoked and a fresh login is required.
  3. 3. A valid access token without the admin role calls an admin route. Which status is correct?

    The caller is known (authenticated) but not permitted, which is 403. 401 is for missing, invalid or expired credentials.
  4. 4. Why does registration reject a roles property in the body?

    Privilege fields must be set by the server. Whitelisting the DTO and assigning roles: ['user'] in the service closes the hole.
  5. 5. What is true about the payload of a JWT signed with HS256?

    The payload is only base64url-encoded. The signature protects integrity, not secrecy, so never store secrets in a token.

Summary

  • Store salted slow hashes of passwords, never the passwords; compare in constant time.
  • Issue a short-lived JWT access token and a random refresh token stored only as a hash.
  • A global guard plus @Public() makes routes secure by default; a roles guard reads @Roles() metadata and answers 403.
  • Never accept roles or other privilege fields from a registration body.
  • Rotate refresh tokens on each use and treat reuse as theft by revoking the family.
  • JWTs are signed, not encrypted; use maintained libraries in production and consider a managed identity provider.

Next, build relations and response shaping in Project: Blog API with Relations.