Authorized vs Authenticated

🗓 April 29, 2024

If you're experience writing enterprise software is anything like mine, than your code is full of (maybe gnarly) authorization checks to make sure that the user trying to do some CRUD action is actually allowed to do said action.

I see a lot of code that looks something like this...

if !user.CanUpdate(thing) {
    http.Error(w, "Unauthorized", http.StatusUnauthorized)

But wait, there is a problem here!

In the above psuedo-code, the very fact that we have a valid user that we can call the CanUpdate method on is a hint that we already authenticated the user (by parsing a jwt, validating a basic auth header, etc).

403 Instead

In cases where we have a valid user identity but the user is attempting to do something they shouldn't, use a 403 Forbidden instead.

When to 401?

From MDN's Docs, "Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response."

Annoying mishap in the spec... nonetheless, 401 Unauthorized should be used in scenarios where the request is unauthenticated... meaning, the authentication data was missing or invalid.