DEV Community

Cover image for Day 21: Backend Security – The Last Line of Defense
Nader Fkih Hassen
Nader Fkih Hassen

Posted on

Day 21: Backend Security – The Last Line of Defense

"Sometimes it’s not about what you add, but what you protect."

In my internship journey, I revisited a crucial lesson that every developer (especially full-stack ones) should hold dear: never trust the frontend when it comes to security.

🔍 The Problem
In the early days of building Lura – The Lawyer Management System, we did most of our RBAC (Role-Based Access Control) checks on the frontend. Buttons were shown or hidden based on role, navigation was blocked, and unauthorized users couldn’t even see actions they shouldn’t take.

It felt secure... until I asked myself:
“What happens if someone just sends a crafted POST request directly to our backend?”

Answer: They might just bypass all our hard work.

🔒 The Solution: Backend Enforcement
So I shifted focus and began securing our NestJS backend endpoints. Here's what I did:

🧰 Backend Guards and Decorators
I created a series of custom guards and decorators in NestJS:

ts
// Example: Role Guard
@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
    return requiredRoles.includes(user.role);
  }
}

// Used like this:
@UseGuards(RolesGuard)
@Roles('admin')
Enter fullscreen mode Exit fullscreen mode

This simple logic ensures that even if someone sends a forged request, they won't pass unless the role matches.

🔁 Workspace Validation
We also have workspace-scoped actions. For that, I added:

  • A @WorkspaceMember() decorator
  • Logic to confirm the user is part of the workspace they’re acting on
  • AuthorizationService with reusable checks

🧪 Testing
Finally, I used Jest to write tests for key routes:

  • Can an admin delete a document?
  • Can a lawyer access a case from a different workspace? (They shouldn’t)
  • Can anyone else invite users to a workspace?

💡 Takeaways

  • Frontend is UX. Backend is law.
  • NestJS makes it easy to build modular, reusable security logic
  • Good security is invisible to the user — and obvious to the developer
  • I now have a deeper respect for backend checks and how they actually protect users

❓ Today’s Question
What’s your approach to securing backend logic in multi-role applications? Do you go with service-based policies, decorators, or custom guards?

I’d love to hear how others handle authorization at scale.

Thanks for reading — and see you for Day 22!

NestJS #BackendSecurity #RBAC #LearningInPublic #30DaysOfLearning #LuraApp #WebDevJourney

Top comments (0)