Protecting Routes

The purpose of this package, beyond the creation of JWTs, is to protect routes so that only users with a valid access token can reach certain resources. Endpoints in your application can be protected using the @protected decorator.


The @protected decorator

Purpose: To protect an endpoint from being accessed without a valid access token.
Example:

from sanic_jwt.decorators import protected


@app.route("/")
async def open_route(request):
    return json({"protected": False})


@app.route("/protected")
@protected()
async def protected_route(request):
    return json({"protected": True})

Now, anyone can access the / route. But, only users that pass a valid access token can reach protected.

If you have initialized Sanic JWT on a Blueprint, then you will need to pass the instance of that blueprint into the @protected decorator.

bp = Blueprint('Users')
Initialize(bp)

@bp.get('/users/<id>')
@protected(bp)
async def users(request, id):
    ...

Class based views

Using the standard Sanic methodology, you can protect class based views with the same decorator.

class PublicView(HTTPMethodView):
def get(self, request):
    return json({"protected": False})


class ProtectedView(HTTPMethodView):
    decorators = [protected()]

    async def get(self, request):
        return json({"protected": True})

app.add_route(PublicView.as_view(), '/')
app.add_route(ProtectedView.as_view(), '/protected')

Passing the Token

There are two general methodologies for passing a token: cookie based, and header based. By default, Sanic JWT will expect you to send tokens thru HTTP headers.

curl -X GET -H "Authorization: Bearer <JWT>" http://localhost:8000/auth/me

Header Tokens

Header tokens are passed by adding an Authorization header that consists of two parts:

  1. the word Bearer
  2. the JWT access token

If you would like, you can modify this behavior by changing the settings for authorization_header and authorization_header_prefix.

Initialize(
    app,
    authorization_header='somecustomheader',
    authorization_header_prefix='MeFirst',)
curl -X GET -H "somecustomheader: MeFirst <JWT>" http://localhost:8000/auth/me

Per view declaration

Coming soon - the ability to decide at the view level which token to accept