Implements authentication and authorization as FastAPI dependencies

Overview

FastAPI Security

Implements authentication and authorization as dependencies in FastAPI.

Features

  • Authentication via JWT-based OAuth 2 access tokens and via Basic Auth
  • Pydantic-based User model for authenticated and anonymous users
  • Sub-classable UserPermission dependency to check against the permissions attribute returned in OAuth 2 access tokens
  • Able to extract user info from access tokens via OpenID Connect

Limitations

  • Only supports validating access tokens using public keys from a JSON Web Key Set (JWKS) endpoint. I.e. for use with external identity providers such as Auth0 and ORY Hydra.
  • Permissions can only be picked up automatically from OAuth2 tokens, from the non-standard permissions list attribute (Auth0 provides this, maybe other identity providers as well). For all other use cases, permission_overrides must be used. For example if there's a basic auth user called user1 you can set permission_overrides={"user1": ["*"]} to give the user access to all permissions, or permission_overrides={"user1": ["products:create"]} to only assign user1 with the permission products:create.

Installation

pip install fastapi-security

Usage examples

Examples on how to use can be found here.

TODO

  • Write more tests
Comments
  • Server with *only* basic auth configured returns WWW-Authenticate

    Server with *only* basic auth configured returns WWW-Authenticate "Bearer" whereas it should probably return "Basic"

    Hi!

    First off, thank you for a nice and useful package! Please find a bug report below.

    Repro

    • any fastapi app
    • fastapi security configured with:
    from fastapi_security import FastAPISecurity
    security = FastAPISecurity()
    security.init_basic_auth(settings.BASIC_AUTH_CREDENTIALS)
    
    • request:
    $ curl localhost:8080/api/v1/ -v
    

    Expected Behaviour

    Response contains WWW-Authenticate: Basic header, as it is the only supported authentication method.

    Actual Behaviour:

    $ curl localhost:8080/api/v1/ -v
    *   Trying 127.0.0.1:8080...
    * TCP_NODELAY set
    * Connected to localhost (127.0.0.1) port 8080 (#0)
    > GET /api/v1/ HTTP/1.1
    > Host: localhost:8080
    > User-Agent: curl/7.68.0
    > Accept: */*
    > 
    * Mark bundle as not supporting multiuse
    < HTTP/1.1 401 Unauthorized
    < date: Thu, 03 Jun 2021 10:34:20 GMT
    < server: uvicorn
    < www-authenticate: Bearer
    < content-length: 43
    < content-type: application/json
    < 
    * Connection #0 to host localhost left intact
    {"detail":"Could not validate credentials"}
    

    There's a section of code that is responsible for www-authenticate header, https://github.com/jmagnusson/fastapi-security/blob/main/fastapi_security/api.py#L212-L215, that is only returning "Basic" if there is a valid Authorization: Basic ... header, which seems like it is not needed.

    According to https://datatracker.ietf.org/doc/html/rfc7235#section-4.1, a WWW-Authenticate header may contain multiple challenges,

    image,

    so it should be possible to return both Basic and Bearer if they are initialized.

    opened by immerrr 2
  • chore(main): release 0.5.0

    chore(main): release 0.5.0

    :robot: I have created a release beep boop

    0.5.0 (2022-03-11)

    ⚠ BREAKING CHANGES

    • Make oauth2 dependencies optional

    Bug Fixes

    • Make oauth2 dependencies optional (e0db0f4)

    Documentation

    • Document new extra for oauth2 support (73e1696)
    • Update changelog to conform to release-please format (c9bfb16)

    This PR was generated with Release Please. See documentation.

    autorelease: tagged 
    opened by github-actions[bot] 1
  • CI: macos, windows jobs run on ubuntu, not on the respective OS

    CI: macos, windows jobs run on ubuntu, not on the respective OS

    Problem

    By declaring ubuntu-latest on the workflows.ci like so:

    jobs:
      ci:
        runs-on: ubuntu-latest
    

    the following happens:

    bug-example (screenshot taken from the latest CI action of this project)

    However, given that the purpose of the CI is to test multiple python versions on multiple OS environments, this is not correct. Instead, the above should declare something like:

    expected (screenshot taken from another open-source project)

    Proposed Solution

    We could replace the above code snippet with a parameterized version of it:

    jobs:
      ci:
        runs-on: ${{ matrix.os }}
    
    opened by ilias-ant 0
  • Make audiences nullable in Oauth2JwtAccessTokenValidator

    Make audiences nullable in Oauth2JwtAccessTokenValidator

    Sometimes it's not required to check for aud. Previously, this library didn't allow that, requiring a list of audiences to check the JWT token against. A simple change of logic allows now allows doing so.

    opened by irdkwmnsb 0
  • Add a way to configure basic auth without storing passwords in plaintext in settings

    Add a way to configure basic auth without storing passwords in plaintext in settings

    This PR's goal is to enable storing password digests (instead of plaintext) to increase security.

    It is admittedly a very early version aimed mostly at collecting feedback. I tried to introduce this with as little change as possible to the existing functionality to maintain backward compat, althought it is probably possible to add this to the basic_auth class directly.

    I'm open to suggestions, and I have enabled edits by maintainers if you feel like applying some minor changes directly. Also, feel free to take this as a proof-of-concept, and implement it in a completely independent branch, that's absolutely fine by me.

    opened by immerrr 6
Releases(v0.5.0)
Owner
Jacob Magnusson
Jacob Magnusson
Authentication testing framework

What is this This is a framework designed to test authentication for web applications. While web proxies like ZAProxy and Burpsuite allow authenticate

DigeeX 140 Jul 06, 2022
Auth-Starters - Different APIs using Django & Flask & FastAPI to see Authentication Service how its work

Auth-Starters Different APIs using Django & Flask & FastAPI to see Authentication Service how its work, and how to use it. This Repository based on my

Yasser Tahiri 7 Apr 22, 2022
Authentication with fastapi and jwt cd realistic

Authentication with fastapi and jwt cd realistic Dependencies bcrypt==3.1.7 data

Fredh Macau 1 Jan 04, 2022
A recipe sharing API built using Django rest framework.

Recipe Sharing API This is the backend API for the recipe sharing platform at https://mesob-recipe.netlify.app/ This API allows users to share recipes

Hannah 21 Dec 30, 2022
An open source Flask extension that provides JWT support (with batteries included)!

Flask-JWT-Extended Features Flask-JWT-Extended not only adds support for using JSON Web Tokens (JWT) to Flask for protecting views, but also many help

Landon Gilbert-Bland 1.4k Jan 04, 2023
OpenConnect auth creditials collector.

OCSERV AUTH CREDS COLLECTOR V1.0 Зачем Изначально было написано чтобы мониторить какие данные вводятся в интерфейс ханипота в виде OpenConnect server.

0 Sep 23, 2022
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

Welcome to django-allauth! Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (soc

Raymond Penners 7.7k Jan 03, 2023
it's a Django application to register and authenticate users using phone number.

django-phone-auth It's a Django application to register and authenticate users using phone number. CustomUser model created using AbstractUser class.

MsudD 4 Nov 29, 2022
Flask Implementation of a login page and some basic functionality.

login_page Flask Implementation of a login page and some basic functionality. How to Run $ chmod +x run.sh setup.sh $ # run setup.sh only if the datab

3 Jun 03, 2021
Skit-auth - Authorization for skit.ai's platform

skit-auth This is a simple authentication library for Skit's platform. Provides

Skit 3 Jan 08, 2022
Django Auth Protection This package logout users from the system by changing the password in Simple JWT REST API.

Django Auth Protection Django Auth Protection This package logout users from the system by changing the password in REST API. Why Django Auth Protecti

Iman Karimi 5 Oct 26, 2022
Customizable User Authorization & User Management: Register, Confirm, Login, Change username/password, Forgot password and more.

Flask-User v1.0 Attention: Flask-User v1.0 is a Production/Stable version. The previous version is Flask-User v0.6. User Authentication and Management

Ling Thio 997 Jan 06, 2023
Strong, Simple, and Precise security for Flask APIs (using jwt)

flask-praetorian Strong, Simple, and Precise security for Flask APIs API security should be strong, simple, and precise like a Roman Legionary. This p

Tucker Beck 321 Dec 18, 2022
Beihang University Network Authentication Login

北航自动网络认证使用说明 主文件 gw_buaa.py # @file gw_buaa.py # @author Dong # @date 2022-01-25 # @email windcicada 0 Jul 22, 2022

Ready to use and customizable Authentications and Authorisation management for FastAPI ⚡

AuthenticationX 💫 Ready-to-use and customizable Authentications and Oauth2 management for FastAPI ⚡ Source Code: https://github.com/yezz123/AuthX Doc

Yasser Tahiri 404 Dec 27, 2022
CheckList-Api - Created with django rest framework and JWT(Json Web Tokens for Authentication)

CheckList Api created with django rest framework and JWT(Json Web Tokens for Aut

shantanu nimkar 1 Jan 24, 2022
Script that provides your TESLA access_token and refresh_token

TESLA tokens This script helps you get your TESLA access_token and refresh_token in order to connect to third party applications (Teslamate, TeslaFi,

Bun-Ny TAN 3 Apr 28, 2022
Simple extension that provides Basic, Digest and Token HTTP authentication for Flask routes

Flask-HTTPAuth Simple extension that provides Basic and Digest HTTP authentication for Flask routes. Installation The easiest way to install this is t

Miguel Grinberg 1.1k Jan 05, 2023
Crie seus tokens de autenticação com o AScrypt.

AScrypt tokens O AScrypt é uma forma de gerar tokens de autenticação para sua aplicação de forma rápida e segura. Todos os tokens que foram, mesmo que

Jaedson Silva 0 Jun 24, 2022
OAuth2 goodies for the Djangonauts!

Django OAuth Toolkit OAuth2 goodies for the Djangonauts! If you are facing one or more of the following: Your Django app exposes a web API you want to

Jazzband 2.7k Dec 31, 2022