Search code examples
oauth-2.0jwt

JWT authentication for public resources


I try to check JWT Access Tokens in server middleware zone

If JWT token is expired and if resources is only for authorized users then I return 401 code

But if user requests public resources (granted for anonymous users) with JWT token should I return 401 code when token is expired or not?

How do I notify a user that their token is invalid?


Solution

  • Public resources do not require securing, so you should ensure that your server middleware does not run for these requests, and whether or not a valid JWT is sent, you will then return the resource with a 200 status code.

    This is usually done by adopting a path convention such as the following. If resources are public you will not care if a hacker accesses them.

    /public/docs
    /public/news
    

    I have seen people protect public resources in a basic way, eg via a fixed API key, to limit denial of service risks, though I wouldn't usually recommend this. It is worth mentioning since in that case those paths would use a different server middleware.

    For secured endpoints, validate the JWT properly and follow Best Practices:

    • Use a library to verify the signature, expiry, issuer and audience
    • Return a 401 status if any of these fail
    • Then move onto business authorization checks using scopes and claims - eg checking a user is allowed to access the actual data requested
    • If business authorization fails, return a 403 (or 404 - not found for user) status