Angular canActivate Security

angular, angular-routing, security

Solution

TL;DR: `canActivate` guards are not used for security but user experience. Data should always be protected via APIs that require authentication.

Suppose you have an application with a login route that is always accessible and a secrets table which shows secret content for a logged-in user:

- Login

- SecretsTable with AuthGuard

The AuthGuard checks if the user is logged in and redirects to login if not authenticated. As you said, like anything on the client side this could be compromised. That's why the secret data of your SecretsTable should come from a protected API call. Even if the data is static (the same for any user) you would not just include it in your client application but protect it with this API call.

So what do we need the AuthGuard for? It is not so much for security but rather for user experience. Imagine that the user receives the URL `myapp.io/secrets-table` via a chat messenger. If we did not have an AuthGuard the user might receive an error message (401) or see an empty table view. Our data is protected but it's still bad user experience. Better: The AuthGuard instantly redirects to the login and might even bring the user back to the secrets table after a successful authentication. Also, we don't have to implement this logic for every view but can reuse our AuthGuard for multiple protected routes.

Problem

Lately, I've been thinking a lot about the security of the app I'm working on. The client side is built on Angular with a Rails API backend. From what I can gather, the general consensus is, if it's on the client, assume it can be compromised. So this makes me wonder when and if I should be using something like `canActivate` for a route or if I should instead check authorization every time on the server for route requests. I thought of putting the auth request to the server in the `canActivate` but I assume `canActivate` can be hacked to respond `true`, bypassing the need for the server response? If so, what's the point of something like `canActivate` if it's just a glass door?

Original source