All Projects → MushroomMaula → Fastapi_login

MushroomMaula / Fastapi_login

Licence: mit
FastAPI-Login tries to provide similar functionality as Flask-Login does.

Programming Languages

python
139335 projects - #7 most used programming language
python3
1442 projects

Labels

Projects that are alternatives of or similar to Fastapi login

Pkhex Plugins
Plugins for PKHeX
Stars: ✭ 118 (-4.07%)
Mutual labels:  plugin
Mattermost Plugin Remind
a mattermost plugin that sets reminders for users and channels.
Stars: ✭ 121 (-1.63%)
Mutual labels:  plugin
Gradle Maven Plugin
Gradle 5.x Maven Publish Plugin to deploy artifacts
Stars: ✭ 124 (+0.81%)
Mutual labels:  plugin
Jetty Runner
A plugin that allows you to run Jetty from IntelliJ
Stars: ✭ 119 (-3.25%)
Mutual labels:  plugin
Hyperdrive
This repository has moved to:
Stars: ✭ 120 (-2.44%)
Mutual labels:  plugin
Xcode Build Times
This BitBar/SwiftBar plugin shows the time you spend waiting for Xcode to do your builds
Stars: ✭ 122 (-0.81%)
Mutual labels:  plugin
Changeskin
Allows your players to change their skin by command
Stars: ✭ 118 (-4.07%)
Mutual labels:  plugin
Sportspress
An open source league statistics plugin for WordPress created by ThemeBoy.
Stars: ✭ 124 (+0.81%)
Mutual labels:  plugin
Vite ruby
⚡️ Vite.js in Ruby, bringing joy to your JavaScript experience
Stars: ✭ 112 (-8.94%)
Mutual labels:  plugin
Axbaseplugin
Android Plugin Framework
Stars: ✭ 122 (-0.81%)
Mutual labels:  plugin
Activity Log
Get aware of any activities that are taking place on your dashboard! Imagine it like a black-box for your WordPress site.
Stars: ✭ 119 (-3.25%)
Mutual labels:  plugin
Nvim Lspconfig
Quickstart configurations for the Nvim LSP client
Stars: ✭ 3,410 (+2672.36%)
Mutual labels:  plugin
Figma Theme Ui
Convert a Theme UI config to Figma Styles
Stars: ✭ 122 (-0.81%)
Mutual labels:  plugin
Tfsnotificationrelay
An extensible plugin for TFS that sends notifications to Slack, HipChat and IRC
Stars: ✭ 120 (-2.44%)
Mutual labels:  plugin
Rabbitmq Prometheus
A minimalistic Prometheus exporter of core RabbitMQ metrics
Stars: ✭ 124 (+0.81%)
Mutual labels:  plugin
Plug.kak
Plugin manager for Kakoune
Stars: ✭ 119 (-3.25%)
Mutual labels:  plugin
Vim Qfreplace
Perform the replacement in quickfix.
Stars: ✭ 121 (-1.63%)
Mutual labels:  plugin
Http Request Plugin
This plugin does a request to an url with some parameters.
Stars: ✭ 124 (+0.81%)
Mutual labels:  plugin
Uppload
📁 JavaScript image uploader and editor, no backend required
Stars: ✭ 1,673 (+1260.16%)
Mutual labels:  plugin
Next Optimized Images
🌅 next-optimized-images automatically optimizes images used in next.js projects (jpeg, png, svg, webp and gif).
Stars: ✭ 1,870 (+1420.33%)
Mutual labels:  plugin

FastAPI-Login

FastAPI-Login tries to provide similar functionality as Flask-Login does.

Documentation

In-depth documentation can but found at fastapi-login.readthedocs.io

Installation

$ pip install fastapi-login

Usage

To begin we have to setup our FastAPI app:

from fastapi import FastAPI

SECRET = "your-secret-key"

app = FastAPI()

To obtain a suitable secret key you can run import os; print(os.urandom(24).hex()).

Now we can import and setup the LoginManager, which will handle the process of encoding and decoding our Json Web Tokens.

from fastapi_login import LoginManager
manager = LoginManager(SECRET, tokenUrl='/auth/token')

For the example we will use a dictionary to represent our user database. In your application this could also be a real database like sqlite or Postgres. It does not matter as you have to provide the function which retrieves the user.

fake_db = {'[email protected]': {'password': 'hunter2'}}

Now we have to provide the LoginManager with a way to load our user. The user_loader callback should either return your user object or None

@manager.user_loader
def load_user(email: str):  # could also be an asynchronous function
    user = fake_db.get(email)
    return user

Now we have to define a way to let the user login in our app. Therefore we will create a new route:

from fastapi import Depends
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_login.exceptions import InvalidCredentialsException

@app.post('/auth/token')
def login(data: OAuth2PasswordRequestForm = Depends()):
    email = data.username
    password = data.password

    user = load_user(email)  # we are using the same function to retrieve the user
    if not user:
        raise InvalidCredentialsException  # you can also use your own HTTPException
    elif password != user['password']:
        raise InvalidCredentialsException
    
    access_token = manager.create_access_token(
        data=dict(sub=email)
    )
    return {'access_token': access_token, 'token_type': 'bearer'}

Now whenever you want your user to be logged in to use a route, you can simply use your LoginManager instance as a dependency.

@app.get('/protected')
def protected_route(user=Depends(manager)):
    ...

If you also want to handle a not authenticated error, you can add your own subclass of Exception to the LoginManager.

from starlette.responses import RedirectResponse

class NotAuthenticatedException(Exception):
    pass

# these two argument are mandatory
def exc_handler(request, exc):
    return RedirectResponse(url='/login')

manager.not_authenticated_exception = NotAuthenticatedException
# You also have to add an exception handler to your app instance
app.add_exception_handler(NotAuthenticatedException, exc_handler)

To change the expiration date of the token use the expires_delta argument of the create_access_token method with a timedelta. The default is set 15 min. Please be aware that setting a long expiry date is not considered a good practice as it would allow an attacker with the token to use your application as long as he wants.

from datetime import timedelta

data = dict(sub=user.email)

# expires after 15 min
token = manager.create_access_token(
    data=data
)
# expires after 12 hours
long_token = manager.create_access_token(
    data=data, expires=timedelta(hours=12)
)

Usage with cookies

Instead of checking the header for the token. fastapi-login also support access using cookies.

from fastapi_login import LoginManager
manager = LoginManager(SECRET, tokenUrl='/auth/token', use_cookie=True)

Now the manager will check the requests cookies the headers for the access token. The name of the cookie can be set using manager.cookie_name. If you only want to check the requests cookies you can turn the headers off using the use_header argument

For convenience the LoginManager also includes the set_cookie method which sets the cookie to your response, with the recommended HTTPOnly flag and the manager.cookie_name as the key.

from fastapi import Depends
from starlette.responses import Response


@app.get('/auth')
def auth(response: Response, user=Depends(manager)):
    token = manager.create_access_token(
        data=dict(sub=user.email)
    )
    manager.set_cookie(response, token)
    return response
    
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].