An authentication library for Starlette and FastAPI.
Imia (belarussian for "a name") is an authentication library for Starlette and FastAPI (python 3.8+).
The library is considered in "beta" state thus may contain bugs or security issues, but I actively use it in production.
Install imia using PIP or poetry:
pip install imia
# or
poetry add imiaIf you are too lazy to read this doc, take a look into examples/ directory. There you will find several files demoing
various parts of this library.
Here are all moving parts:
imia.UserLike protocol.request.auth with UserToken.When a HTTP request reaches your application, an imia.AuthenticationMiddleware will start handling it. The middleware
iterates over configured authenticators and stops on the first one that returns non-None value. At this point the
request is considered authenticated. If no authenticators return user model then the middleware will create anonymous
user token. The user token available in request.auth property. Use user_token.is_authenticated token property to
make sure that user is authenticated.
imia.UserLike protocol.imia.UserProvider that corresponds to your user storage. Feel free to create your own.imia.AuthenticationMiddleware to your Starlette applicationAt this point you are done.
Here is a brief example that uses in-memory provider for demo purpose. For production environment you should use
database backed providers like SQLAlchemyORMUserProvider or SQLAlchemyCoreUserProvider. Also, for simplicity reason
we will not implement login/logout flow and will authenticate requests using API keys.
…Now save the file to myapp.py and run it with uvicorn application server:
uvicorn myapp:appOpen http://127.0.0.1:8000/ and see that your request is not authenticated and user is anonymous. Let's pass API key
via query parameters to make the configured APIKeyAuthenticator to load user. This time
open http://127.0.0.1:8000/[email protected] in your browser. Now the request is fully authenticated as User1
user.
For more details refer to the doc sections below.
See examples/ directory.
No open issues yet, or sync has not completed.