Login with JWT Token

Alright then, with all this JWT functionality we can now add a login page to the project. A website can’t easily send a token with every request the way an API client can, so instead the token is stored in a browser cookie, which the browser sends back automatically with every request.

We’ll add functions for setting the cookie and checking who is logged in, and GET and POST views to present and process a login page, and to log out.

Add a function to api/auth_apis.py that puts a token in a cookie:

api/auth_apis.pypython
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status  # UPDATED
api/auth_apis.pypython
AUTH_COOKIE = "access_token"
api/auth_apis.pypython
def set_auth_cookie(response: Response, token: str) -> None:
    response.set_cookie(key=AUTH_COOKIE,
                        value=token,
                        max_age=settings.CONF_AUTH_EXPIRE_MINUTES * 60,
                        httponly=True,
                        secure=settings.CONF_AUTH_COOKIE_SECURE,
                        samesite="lax")

Each of the cookie’s settings matters:

  • max_age makes the cookie last as long as the token (in seconds).
  • httponly=True hides the cookie from JavaScript, so if an attacker ever did manage to run a script on your pages, it still couldn’t steal the token.
  • secure=True means the browser only sends the cookie over HTTPS. Browsers treat http://localhost as secure too, so this works in development. If you test from another machine over plain HTTP, set CONF_AUTH_COOKIE_SECURE=false in .env.
  • samesite="lax" stops the browser sending the cookie with forms submitted from other websites. This protects against cross-site request forgery (CSRF): another site can’t make a logged-in visitor’s browser post to /blog/delete/... on yours. That’s also why changes are only ever made with POST, never GET.

Who is logged in?#

Next, a function that reads the token from the cookie and returns the id of the logged-in user, or None:

api/auth_apis.pypython
from jwt.exceptions import InvalidTokenError  # NEW
api/auth_apis.pypython
def get_current_user_api(request: Request) -> uuid.UUID | None:
    """The id of the logged-in user, from the JWT in the cookie, or None."""
    token = request.cookies.get(AUTH_COOKIE)
    if token is None:
        return None
    try:
        payload = jwt.decode(token, settings.CONF_AUTH_SECRET_KEY, algorithms=[settings.CONF_AUTH_ALGORITHM])
        return uuid.UUID(payload["sub"])
    except (InvalidTokenError, KeyError, ValueError):
        # Expired, tampered with or malformed: treat the visitor as logged out
        return None

jwt.decode() checks the signature and the expiry, and raises InvalidTokenError if either is wrong. Passing algorithms=[...] matters: it stops a forged token from choosing a weaker algorithm.

An invalid token simply means “not logged in”. Raising an error instead (as an earlier version of this guide did) would break every page, including public ones, for anyone whose login had expired, until they cleared their cookies.

The token only holds the user’s id. To check things like whether the user is an author, or whether their account has been deactivated since they logged in, look the user up in the database. This function does both steps, and is what the views will use:

api/auth_apis.pypython
def is_user(request: Request, session: Session) -> User | None:
    """The logged-in, active user, or None."""
    user_id = get_current_user_api(request)
    if user_id is None:
        return None
    user = session.get(User, user_id)
    if not user or not user.is_active:
        return None
    return user

We’ll also want a READ API to return a user by id:

api/auth_apis.pypython
@router.get('/auth/user/{id}', status_code=status.HTTP_200_OK)
def get_user_by_id_api(id: uuid.UUID, session: Session = Depends(get_session_db)) -> UserOut:
    user = session.get(User, id)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No user found with id {id}.")
    return user

Here is the complete api/auth_apis.py at this point:

api/auth_apis.pypython
import datetime
import uuid
from typing import Annotated

import jwt
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
from fastapi.security import OAuth2PasswordRequestForm
from jwt.exceptions import InvalidTokenError
from pwdlib import PasswordHash
from pydantic import BaseModel
from sqlmodel import Session, select

from config.settings import settings
from db.db import get_session_db
from db.schemas.user_schemas import User, UserIn, UserOut

router = APIRouter()

AUTH_COOKIE = "access_token"

password_hash = PasswordHash.recommended()
DUMMY_HASH = password_hash.hash("dummypassword")

class Token(BaseModel):
    access_token: str
    token_type: str

# Functions
def get_password_hash_api(password: str) -> str:
    return password_hash.hash(password)

def verify_password_api(plain_password: str, hashed_password: str) -> bool:
    return password_hash.verify(plain_password, hashed_password)

def authenticate_user_api(username: str, password: str, session: Session) -> User | None:
    query = select(User).where(User.username == username)
    user = session.exec(query).first()
    if not user:
        # Check against a dummy hash anyway, so the response takes the same time
        # whether or not the user exists (otherwise timing reveals valid usernames)
        verify_password_api(password, DUMMY_HASH)
        return None
    if not verify_password_api(password, user.hashed_password):
        return None
    return user

def create_access_token_api(user_id: uuid.UUID) -> str:
    now = datetime.datetime.now(datetime.UTC)
    payload = {
        "sub": str(user_id),
        "iat": now,
        "exp": now + datetime.timedelta(minutes=settings.CONF_AUTH_EXPIRE_MINUTES),
    }
    return jwt.encode(payload, settings.CONF_AUTH_SECRET_KEY, algorithm=settings.CONF_AUTH_ALGORITHM)

def set_auth_cookie(response: Response, token: str) -> None:
    response.set_cookie(key=AUTH_COOKIE,
                        value=token,
                        max_age=settings.CONF_AUTH_EXPIRE_MINUTES * 60,
                        httponly=True,
                        secure=settings.CONF_AUTH_COOKIE_SECURE,
                        samesite="lax")

def get_current_user_api(request: Request) -> uuid.UUID | None:
    """The id of the logged-in user, from the JWT in the cookie, or None."""
    token = request.cookies.get(AUTH_COOKIE)
    if token is None:
        return None
    try:
        payload = jwt.decode(token, settings.CONF_AUTH_SECRET_KEY, algorithms=[settings.CONF_AUTH_ALGORITHM])
        return uuid.UUID(payload["sub"])
    except (InvalidTokenError, KeyError, ValueError):
        # Expired, tampered with or malformed: treat the visitor as logged out
        return None

def is_user(request: Request, session: Session) -> User | None:
    """The logged-in, active user, or None."""
    user_id = get_current_user_api(request)
    if user_id is None:
        return None
    user = session.get(User, user_id)
    if not user or not user.is_active:
        return None
    return user

# APIs
@router.post('/auth/create/user', status_code=status.HTTP_201_CREATED)
def create_user_api(user_in: UserIn, session: Session = Depends(get_session_db)) -> UserOut:
    if session.exec(select(User).where(User.email == user_in.email)).first():
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="A user with that email already exists.")
    new_user = User.model_validate(user_in, update={"hashed_password": get_password_hash_api(user_in.password)})
    session.add(new_user)
    session.commit()
    session.refresh(new_user)
    return new_user

@router.get('/auth/user/{id}', status_code=status.HTTP_200_OK)
def get_user_by_id_api(id: uuid.UUID, session: Session = Depends(get_session_db)) -> UserOut:
    user = session.get(User, id)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No user found with id {id}.")
    return user

@router.post('/auth/token')
def login_for_token_api(form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
                        session: Session = Depends(get_session_db)) -> Token:
    user = authenticate_user_api(form_data.username, form_data.password, session)
    if not user or not user.is_active:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail="Incorrect username or password",
                            headers={"WWW-Authenticate": "Bearer"})
    return Token(access_token=create_access_token_api(user.id), token_type="bearer")

The login page#

Now the views, starting with a new file:

web/views/auth_views.pypython
from fastapi import APIRouter, Depends, Form, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlmodel import Session

from api.auth_apis import AUTH_COOKIE, authenticate_user_api, create_access_token_api, is_user, set_auth_cookie
from db.db import get_session_db

router = APIRouter()

templates = Jinja2Templates('web/templates')

@router.get('/auth/login', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def login_get_view(*, request: Request, session: Session = Depends(get_session_db)):

    if is_user(request, session):
        return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)

    context = {
        "page": "login"
    }

    return templates.TemplateResponse(request, 'login.html', {'context': context})

@router.post('/auth/login', response_class=HTMLResponse)
def login_post_view(*,
                    request: Request,
                    username: str = Form(...),
                    password: str = Form(...),
                    session: Session = Depends(get_session_db)):

    user = authenticate_user_api(username, password, session)
    if not user or not user.is_active:
        context = {
            "page": "login",
            "username": username,
            "msg": "Incorrect username or password"
        }
        return templates.TemplateResponse(request, 'login.html', {'context': context},
                                          status_code=status.HTTP_401_UNAUTHORIZED)

    response = RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
    set_auth_cookie(response, create_access_token_api(user.id))
    return response

@router.get('/auth/logout')
def logout_view():
    response = RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
    response.delete_cookie(key=AUTH_COOKIE)
    return response

Stepping through it:

  • login_get_view shows the login form, or sends you to the home page if you’re already logged in.
  • login_post_view checks the username and password with authenticate_user_api. If they’re wrong, the login form is shown again, with the email address filled in, an error message, and a 401 status. If they’re right, it creates a token, puts it in a cookie on the redirect response, and sends the browser to the home page.
  • logout_view deletes the cookie. The token itself stays valid until it expires, but the browser no longer has it.

Add a new template for the login page:

web/templates/login.htmljinja
{% extends "_base.html" %}

{% block content %}

    <!-- Page Header -->
    <header class="intro-header" style="background-image: url('/static/img/about-bg.jpg')">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="page-heading">
                        <h1>Login</h1>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <p>Use the form to login:</p>
                <form action="/auth/login" method="post">
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Email</label>
                            <input type="email" class="form-control" placeholder="Email" id="email" name="username"
                                   value="{{ context.username or '' }}" autocomplete="username" required>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Password</label>
                            <input type="password" class="form-control" placeholder="Password" id="password" name="password"
                                   autocomplete="current-password" required>
                        </div>
                    </div>
                    <br>
                    <div class="row">
                        <div class="form-group col-xs-12">
                            <button type="submit" class="btn btn-default">Login</button>
                        </div>
                    </div>
                </form>
                {% if context.msg %}<p><strong>{{ context.msg }}</strong></p>{% endif %}
            </div>
        </div>
    </div>

{% endblock %}

The autocomplete attributes help password managers fill in the form.

Remember to import auth_views and plumb in the new router in your main.py:

main.pypython
from web.views import home_view, blog_views, contact_view, auth_views  # UPDATED
main.pypython
    main_app.include_router(auth_views.router, tags=["web_views"])  # NEW

If you go to the login page http://localhost:8000/auth/login and log in with a test user, you will be redirected to the home page. To check the JWT token was set as a cookie in your browser, explore the developer tools.

In Firefox, this is More Tools -> Web Developer Tools. You need the Storage tab, and Cookies:

Restricting pages#

With all this now in place, you can add the following to any view that should only be available to logged-in users:

    current_user = is_user(request, session)
    if current_user is None:
        return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)

That deals with authentication, the logging in bit. But you probably still don’t want every user to have the ability to create blog posts. What we’ll also need is authorisation: sure, you can be logged in, but are you authorised to do certain things?

In the User schema we included a set of booleans, which provide the means to control what a user can do:

    is_superuser: bool = False
    is_active: bool = True
    is_author: bool = False
    is_member: bool = False

As an example, update the view blogpost_create_get_view, so you need to be logged in and an author:

web/views/blog_views.pypython
from api.auth_apis import is_user  # NEW
web/views/blog_views.pypython
@router.get('/blog/create', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_create_get_view(*, request: Request, session: Session = Depends(get_session_db)):  # UPDATED

    current_user = is_user(request, session)  # NEW
    if current_user is None:  # NEW
        return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)  # NEW
    if not current_user.is_author:  # NEW
        return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)  # NEW

    context = {
        "page": "create",
        "user": current_user  # NEW
    }

    return templates.TemplateResponse(request, 'blog_create.html', {'context': context})

So now a user needs to be logged in and be an author to access the page for creating new blog posts. Moreover, we are returning the current_user in the context, so we can present personalised information on the page:

web/templates/blog_create.htmljinja
                    <h1>Create</h1>
                    <span class="subheading">{{ context.user.first_name }} {{ context.user.last_name }}</span>

The next page applies this throughout the project.