shinokada / fastapi-web-starter

A static simple website ready to deploy using FastAPI and Bootstrap 5
104 stars 59 forks source link

How would you handle login with FastAPI JWT? #1

Closed danieljfarrell closed 3 years ago

danieljfarrell commented 3 years ago

Thank you for this! 👍

It really helped me to understand the pieces and how you put them together for a web frontend.

I have a question about adding a login page. I have a FastAPI REST API, some of the routes require authentication before use (JWT in the header).

I've added a new route to serve the page app/routers/login.py,

import os
from fastapi import Request, APIRouter, Depends
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

#from dotenv import load_dotenv
#load_dotenv()

templates = Jinja2Templates(directory="/proj/app/templates/")

router = APIRouter()

@router.get("/", response_class=HTMLResponse)
async def login_page(request: Request):
    res = templates.TemplateResponse("login.html", {"request": request})
    return res

and template template/login.html,

{% extends "base.html" %}
{% set active_page = "upload" %}

{% block title %}H5 File Upload{% endblock %}

{% block head %}
{{ super() }}

{% endblock %}

{% block page_content %}

<div id="top">
      <h1>Please login</h1>
      <br>
      <form action="/api/v1/login/access-token" method="post">
        <input type="text" placeholder="Username" name="username" value="{{
          request.form.username }}">
         <input type="password" placeholder="Password" name="password" value="{{
          request.form.password }}">
        <input class="btn btn-default" type="submit" value="Login">
      </form>
      {% if error %}
        <p class="error"><strong>Error:</strong> {{ error }}
      {% endif %}
</div>

{% endblock %}

{% block scripts %}
{{ super() }}

{% endblock %}

When the submit button is clicked, what currently happens is that page refreshes and displays the JSON content of the response,

{
   "access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTA5ODU5MjYsInN1YiI6ImRhbmllbC5mYXJyZWxsQHRlcmF2aWV3LmNvbSJ9.tVJTo4zhuzi5JA8FGoJIJq4ZDcEeOvnKl3JnpxDKLZw",
   "token_type":"bearer"
}

What I would like to do is save the response and store the header information somewhere so that subsequent calls to the API always send the authentication token. Any pointers on how to do that?

shinokada commented 3 years ago

You can use Web storage or cookies to store information.

danieljfarrell commented 3 years ago

Maybe I should ask on Stack Overflow, thanks so much for the comment! I’m coming from native Desktop UI background so I’m not too sure where to start!