Advanced Auth Patterns

Preview — 3 of 10 questions

In a RolesGuard, why is Reflector.getAllAndOverride preferred over Reflector.get when reading @Roles()?

javascript
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from './roles.decorator';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(ctx: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
      ctx.getHandler(),
      ctx.getClass(),
    ]);
    if (!required) return true;
    const { user } = ctx.switchToHttp().getRequest();
    return required.some((role) => user?.roles?.includes(role));
  }
}
AIt is faster at runtime
BIt merges/overrides metadata from both handler and class, letting a method-level @Roles() override a controller-level default
CIt bypasses the guard
DIt reads metadata from middleware

What is a key trade-off of permission-based authorization compared to pure role-based?

javascript
@SetMetadata('permissions', ['orders:refund'])
@Post(':id/refund')
refund(): void {}

// guard checks: user.permissions.includes('orders:refund')
APermissions are finer-grained and more flexible but require more management overhead, while roles are coarser yet simpler to administer
BPermissions cannot be checked in a guard
CRoles are always more secure than permissions
DThey are functionally identical

Which JWT claims set follows best practices for a stateless access token?

javascript
const token = this.jwt.sign(
  { sub: user.id, jti: crypto.randomUUID() },
  { expiresIn: '15m' }, // iat/exp added automatically
);
AEmbed the full user record including password hash and all permissions
BPut the database connection string in the payload
COmit exp so tokens never expire
DUse registered claims like sub (user id), iat, exp, and a jti, keeping payload minimal and non-sensitive

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.