Saravanan666/pypi-org huggingface dataset:
Package: fastapi-jwk-auth
Fastapi JWKS Auth(Validator)OverviewFastAPI JWK Auth is a Python package designed to enhanceFastAPIapplications with easy and secure JSON Web Token (JWT) validation using JSON Web Key Sets (JWKS). It simplifies the integration of JWT-based authentication in your FastAPI project when JWKS URLs are employed for key retrieval.FeaturesJWKS-Based JWT Validation:Seamlessly validate JWTs using JWKS obtained from configured URLs.FastAPI Middleware Integration:Integrate the providedJWTMiddlewareclass into your FastAPI application middleware likeapp.add_middleware(JWTMiddleware)to secure your routes with JWT validation.Fastapi Router dependency:Integrate the providedjwk_validatorfunction into your FastAPI router likeapp.include_router(auth_app.router, dependencies=[Depends(jwk_validator)])to secure your product with JWT validationEfficient JWK Handling:Retrieve and utilize JSON Web Key Sets efficiently in your FastAPI routes with thefetch_jwksfunction.Exception Handling:Easily manage JWT validation exceptions using FastAPI's HTTPException.InstallationInstall the package using pip:pipinstallfastapi-jwk-authUsageFastAPI Middleware IntegrationfromfastapiimportFastAPI,Dependsfromfastapi_jwk_auth.jwks_authimportjwk_validator,JWKMiddlewareapp=FastAPI()# Include the JWT Middlewareapp.add_middleware(JWTMiddleware)FastAPI Route JWT ValidationfromfastapiimportFastAPI,Dependsfromfastapi_jwk_auth.jwks_authimportjwk_validator,JWKMiddlewareapp=FastAPI()app.include_router(auth_app.router,dependencies=[Depends(jwk_validator)])ConfigurationSet the following environment variable to the JSON Web Key Set (JWKS) URI:exportJWK_HOST="https://your-identity-server"ContributingFeel free to open PR/Issues.LicenseThis project is licensed under the MIT License.ContactFor questions or feedback, feel free to contact us at [omkardarves@gmail.com].
Package: fastapi-jwt
fastapi-jwtFastAPI native extension, easy and simple JWT authDocumentation:k4black.github.io/fastapi-jwtSource Code:github.com/k4black/fastapi-jwtFeaturesOpenAPI schema generationNative integration with FastAPIAccess/Refresh JWTJTICookie settingInstallationYou can access packagefastapi-jwt in pypipipinstallfastapi-jwtUsageThis library made in fastapi style, so it can be used as standard security featuresfromfastapiimportFastAPI,Security,Responsefromfastapi_jwtimportJwtAuthorizationCredentials,JwtAccessBearerapp=FastAPI()access_security=JwtAccessBearer(secret_key="secret_key",auto_error=True)@app.post("/auth")defauth():subject={"username":"username","role":"user"}return{"access_token":access_security.create_access_token(subject=subject)}@app.post("/auth_cookie")defauth(response:Response):subject={"username":"username","role":"user"}access_token=access_security.create_access_token(subject=subject)access_security.set_access_cookie(response,access_token)return{"access_token":access_token}@app.get("/users/me")defread_current_user(credentials:JwtAuthorizationCredentials=Security(access_security),):return{"username":credentials["username"],"role":credentials["role"]}For more examples see usage docsAlternativesFastAPI docs suggestwriting it manually, butcode duplicationopportunity for bugsThere is nicefastapi-jwt-auth, butpoorly supportednot "FastAPI-style" (not native functions parameters)FastAPI IntegrationThere it is open and maintainedPull Request #3305to thefastapirepo. Currently, not considered.Requirementsfastapipython-jose[cryptography]LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-jwt-auth
FastAPI JWT AuthDocumentation:https://indominusbyte.github.io/fastapi-jwt-authSource Code:https://github.com/IndominusByte/fastapi-jwt-authFeaturesFastAPI extension that provides JWT Auth support (secure, easy to use and lightweight), if you were familiar with flask-jwt-extended this extension suitable for you, cause this extension inspired by flask-jwt-extended 😀Access tokens and refresh tokensFreshness TokensRevoking TokensSupport for WebSocket authorizationSupport for adding custom claims to JSON Web TokensStoring tokens in cookies and CSRF protectionInstallationThe easiest way to start working with this extension with pippipinstallfastapi-jwt-authIf you want to use asymmetric (public/private) key signing algorithms, include theasymmetricextra requirements.pipinstall'fastapi-jwt-auth[asymmetric]'LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-jwt-auth2
FastAPI JWT Auth 2Proyect forked fromIndominusByte'sfastapi-jwt-auth. Since it seems to be no longer maintained (last commit was on Nov 11, 2020) I decide to fork the repo and add support forpydantic==2.X. If this isn't the appropiate way to fix the dependencies problem, please contact me so I can do it in the proper way. Thanks!Documentation:https://alejorodriguez96.github.io/fastapi-jwt-authSource Code:https://github.com/alejorodriguez96/fastapi-jwt-authFeaturesFastAPI extension that provides JWT Auth support (secure, easy to use and lightweight), if you were familiar with flask-jwt-extended this extension suitable for you, cause this extension inspired by flask-jwt-extended 😀Access tokens and refresh tokensFreshness TokensRevoking TokensSupport for WebSocket authorizationSupport for adding custom claims to JSON Web TokensStoring tokens in cookies and CSRF protectionInstallationThe easiest way to start working with this extension with pippipinstallfastapi-jwt-authIf you want to use asymmetric (public/private) key signing algorithms, include theasymmetricextra requirements.pipinstall'fastapi-jwt-auth[asymmetric]'LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-jwt-auth-v2
FastAPI JWT Auth V2Source Code:https://github.com/DanielChico/fastapi-jwt-auth-v2FeaturesFastAPI extension that provides JWT Auth support (secure, easy to use and lightweight), if you were familiar with flask-jwt-extended this extension suitable for you, cause this extension inspired by flask-jwt-extended 😀Access tokens and refresh tokensFreshness TokensRevoking TokensSupport for WebSocket authorizationSupport for adding custom claims to JSON Web TokensStoring tokens in cookies and CSRF protectionInstallationThe easiest way to start working with this extension with pippipinstallfastapi-jwt-auth-v2LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-jwt-extended
fastapi-jwtFastAPI native extension, easy and simple JWT authDocumentation:k4black.github.io/fastapi-jwtSource Code:github.com/k4black/fastapi-jwtFeaturesOpenAPI schema generationNative integration with FastAPIAccess/Refresh JWTJTICookie settingInstallationYou can access packagefastapi-jwt in pypipipinstallfastapi-jwtUsageThis library made in fastapi style, so it can be used as standard security featuresfromfastapiimportFastAPI,Security,Responsefromfastapi_jwtimportJwtAuthorizationCredentials,JwtAccessBearerapp=FastAPI()access_security=JwtAccessBearer(secret_key="secret_key",auto_error=True)@app.post("/auth")defauth():subject={"username":"username","role":"user"}return{"access_token":access_security.create_access_token(subject=subject)}@app.post("/auth_cookie")defauth(response:Response):subject={"username":"username","role":"user"}access_token=access_security.create_access_token(subject=subject)access_security.set_access_cookie(response,access_token)return{"access_token":access_token}@app.get("/users/me")defread_current_user(credentials:JwtAuthorizationCredentials=Security(access_security),):return{"username":credentials["username"],"role":credentials["role"]}For more examples see usage docsAlternativesFastAPI docs suggestwriting it manually, butcode duplicationopportunity for bugsThere is nicefastapi-jwt-auth, butpoorly supportednot "FastAPI-style" (not native functions parameters)FastAPI IntegrationThere it is open and maintainedPull Request #3305to thefastapirepo. Currently, not considered.Requirementsfastapipython-jose[cryptography]LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-key-auth
FastAPI-key-authSecure your FastAPI endpoints using API keys.Report Bug·Request FeatureTable of ContentsAbout The ProjectBuilt WithGetting StartedInstallationUsageLicenseContactAbout The ProjectOn deployment inject API keys authorized to use your service. Every call to a private
endpoint of your service has to include aheader['x-api-key']attribute that is
validated against the API keys in your environment.
If it is present, a request is authorized. If it is not FastAPI return401 Unauthorized.
Use this either as a middleware, or as Dependency.Built WithstarlettefastapiGetting StartedInstallationClone and installgitclonehttps://github.com/iwpnd/fastapi-key-auth.git
poetryinstallInstall with pippipinstallfastapi-key-authInstall with poetrypoetryaddfastapi-key-authUsageAs Middleware:fromfastapiimportFastAPIfromfastapi_key_authimportAuthorizerMiddlewareapp=FastAPI()app.add_middleware(AuthorizerMiddleware,public_paths=["/ping"],key_pattern="API_KEY_")# optional use regex startswithapp.add_middleware(AuthorizerMiddleware,public_paths=["/ping","^/users"])As DependencyfromfastapiimportFastAPI,Dependsfromfastapi_key_authimportAuthorizerDependencyauthorizer=AuthorizerDependency(key_pattern="API_KEY_")# either globally or in a routerapp=FastAPI(dependencies=[Depends(authorizer)])LicenseDistributed under the MIT License. SeeLICENSEfor more information.ContactBenjamin Ramser -@imwithpanda-ahoi@iwpnd.pwProject Link:https://github.com/iwpnd/fastapi-key-auth
Package: fastapi-keycloack
FastAPI KeycloackKeycloack plugin for FastApi.Your aplication receives the claims decoded from the access token.UsageRun keycloak on port 8080 and configure your keycloack server:dockerrun-p8080:8080-eKEYCLOAK_USER=admin-eKEYCLOAK_PASSWORD=adminquay.io/keycloak/keycloak:15.0.2Install dependenciespipinstallfastapifastapi-keycloackuvicornCreate the main.py modulefromfastapiimportDepends,FastAPI,Securityfromfastapi_keycloackimportJwtDecodeOptions,FastApiKeycloack,GrantTypeapp=FastAPI()decode_options=JwtDecodeOptions(verify_aud=False)allowed_grant_types=[GrantType.IMPLICIT,GrantType.PASSWORD,GrantType.AUTHORIZATION_CODE,GrantType.CLIENT_CREDENTIALS,]auth_scheme=FastApiKeycloack(url="http://localhost:8080/auth/realms/master",scheme_name="Keycloak",jwt_decode_options=decode_options,allowed_grant_types=allowed_grant_types,)defget_current_user(claims:dict=Security(auth_scheme)):returnclaims@app.get("/users/me")defread_current_user(claims:dict=Depends(get_current_user)):returnclaimsRun the applicationuvicornmain:app
Package: fastapi_keycloak
FastAPI Keycloak IntegrationNotice - 📢 LOOKING FOR MAINTAINERS 📢We created this as an open-source project in order to share our code with other people. Unfortunately we decided to abandon Keycloak in our project due to its unreliability in API compatibility and the general maintenance overhead. Therefore, we are no longer able to frequently update this library. We are searching for someone or a group of people to maintain this repository actively, as we do not have the capacity but think that keycloak still is a highly relevant IDP solution. If you or your team want to take over the responsibility, please mail us atadmin@code-specialist.comIntroductionWelcome tofastapi-keycloak. This projects goal is to ease the integration of Keycloak (OpenID Connect) with Python, especially FastAPI. FastAPI is not necessary but is
encouraged due to specific features. Currently, this package supports only thepasswordand theauthorization_code. However, theget_current_user()method accepts any JWT
that was signed using Keycloak´s private key.DocsDocs are available athttps://fastapi-keycloak.code-specialist.com/.TLDRFastAPI Keycloak enables you to do the following things without writing a single line of additional code:Verify identities and roles of users with KeycloakGet a list of available identity providersCreate/read/delete usersCreate/read/delete rolesCreate/read/delete/assign groups (recursive). Thanks to @fabiothzAssign/remove roles from usersImplement thepasswordor theauthorization_codeflow (login/callback/logout)ContributionsWe would like encourage anyone using this package to contribute to its improvement, if anything isn't working as expected or isn't well enough documented, please open an issue or a
pull request. Please note that for any code contribution tests are required.TestingTests are stored and executed in./tests. To test the package, it is necessary to use thestart_infra.shscript upfront, to set up Keycloak and Postgres. We do this to avoid
artificial testing conditions that occur by mocking all the keycloak requests. The issue here is that we currently see no way to offer public testing opportunities without
significant security issues, which is why you have to run these tests locally and provide atest_coverage.xmlfile. The test coverage is configured in thepytest.iniand will
be created once the tests finished running (locally).
Package: fastapi-keycloak-extended
FastAPI Keycloak IntegrationWelcome tofastapi-keycloak. This projects goal is to ease the integration of Keycloak (OpenID Connect) with Python, especially FastAPI. FastAPI is not necessary but is
encouraged due to specific features. Currently, this package supports only thepasswordand theauthorization_code. However, theget_current_user()method accepts any JWT
that was signed using Keycloak´s private key.DocsRefer tohttps://fastapi-keycloak.code-specialist.com/.Adding some features:KeycloakToken with more datas (refresh token, expires_in, etc.)KeycloakRefreshToken represents the response after refresh tokenKeycloakGroup with fieldattributesFunction to retrieve groups by attributeUpdate call api GET (for users and groups) with param briefRepresentation as false. This allows to get the full representation of the object.Update create_user and create_groupFunction to refresh tokenOverride user_login to take an account more detailsUpdate OIDCUser to add field from attributesThis exposes all fastapi_keycloak features under fastapi_keycloak_extended.Keycloak versionModule tested with version of keycloak:16.0 (server uri must end with /auth )22.0Build and publishRefer tohttps://packaging.python.org/en/latest/tutorials/packaging-projects/Step:python -m buildpython -m twine upload --repository pypi dist/*
Package: fastapi-keycloak-middleware
FastAPI Keycloak MiddlewareFull documentationisavailable at Read The DocsThis package provides a middleware forFastAPIthat
simplifies integrating withKeycloakfor
authentication and authorization. It supports OIDC and supports validating access
tokens, reading roles and basic authentication. In addition it provides several
decorators and dependencies to easily integrate into your FastAPI application.It relies on thepython-keycloakpackage,
which is the only dependency outside of the FastAPI ecosystem which would be installed
anyway. Shoutout to the author offastapi-auth-middlewarewhich served as inspiration for this package and some of its code.In the future, I plan to add support for fine grained authorization using Keycloak
Authorization services.MotivationUsing FastAPI and Keycloak quite a lot, and keeping to repeat myself quite a lot when
it comes to authentiating users, I decided to create this library to help with this.There is a clear separation between the authentication and authorization:Authenticationis about verifying the identity of the user
(who they are). This is done by an authentication backend
that verifies the users access token obtained from the
identity provider (Keycloak in this case).Authorizationis about deciding which resources can be
accessed. This package providers convenience decoraters to
enforce certain roles or permissions on FastAPI endpoints.InstallationInstall the package using poetry:poetryaddfastapi-keycloak-middlewareorpip:pipinstallfastapi-keycloak-middlewareFeaturesThe package helps with:An easy to use middleware that validates the request for an access tokenValidation can done in one of two ways:Validate locally using the public key obtained from KeycloakValidate using the Keycloak token introspection endpointUsing Starlette authentication mechanisms to store both the user object as well as the authorization scopes in the Request objectAbility to provide custom callback functions to retrieve the user object (e.g. from your database) and to provide an arbitrary mapping to authentication scopes (e.g. roles to permissions)A decorator to use previously stored information to enforce certain roles or permissions on FastAPI endpointsConvenience dependencies to retrieve the user object or the authorization result after evaluation within the FastAPI endpointAcknowledgementsThis package is heavily inspired byfastapi-auth-middlewarewhich provides some of the same functionality but without the direct integration
into Keycloak. Thanks for writing and providing this great piece of software!DevelopmentThis project is usingActto handle local development tasks. It is used
to work locally and also to test Github actions before deploying them.
Package: fastapi-kit
fastapi_kit认证fromfastapiimportFastAPIfromfastapi_kit.authimportregister_authapp=FastAPI(...)register_auth(app)完成以上操作，即可在request中拿到user异常内置异常：ExistException对于已经存在的异常NoPermissionException对于无权限操作的异常NotFoundException对于不存在的异常OverLimitException对于超出限制的异常对于自定义的业务报错，可以继承CustomException直接在业务处抛错。注意：自定义异常类，需要使用app.add_exception_handler来注册。fromfastapi_kit.exceptionimporterror_exception_handlerapp.add_exception_handler(自定义异常类,error_exception_handler)权限直接在路由定义处设置权限fromfastapiimportAPIRouter,Requestfromfastapi_kit.permissionimportpermissionrouter=APIRouter()@router.post('/subscribe')@permission('bidding_subscribe_create')asyncdefsubscribe(request:Request):""" 创建用户订阅器 """通用schema返回对于正常的数据返回，使用RestfulResponse对于具有翻页的数据返回，使用RestfulPageResponseRestfulResponsefromfastapi_kit.schemaimportRestfulResponse@router.post('/subscribe',response_model=RestfulResponse[对象的schema])asyncdefsubscribe(request):""" 创建用户订阅器 """returndict(data=对象)RestfulPageResponse(常用于列表)fromfastapi_kit.schemaimportRestfulPageResponse@router.get('/subscribe',response_model=RestfulPageResponse[List[对象的schema]])asyncdefsubscribe(request):""" 获取用户订阅器 """returnRestfulPageResponse(data=对象)
Package: fastapi-lazy
Fastapi-lazy 🦥Utilities that you use in various projects made in FastAPI.Source Code:https://github.com/yezz123/fastapi-lazyInstall the project:pip install fastapi-lazyFeatures 🎉Use the data contained in the JWTUse the username contained in the JWT and fetch data.Create User Models based on Pydantic.Multi Database Support:Creates the dependency to be used to connect to the Postgresql.Creates the dependency to be used to connect to the MongoDB.Create the dependency to be used to connect to the SQlite using SQLAlchemy.Support Redis Cache:Creates apickleof the object passed as a parameter and saves it in the Redis which is also passed as a parameter.Read thepickleof the object saved in RedisDB and return it as Python object.Support UUID generator:Create a custom UUID4 using the current timestamp.Create a JWT token creator & verifier.Create a simple Password hash usinghashlib.Create an Email Validator.Provide a Token Creator for login after adding a new packagepasslib.Add A simple Crud file for MongoDB Provider.Soon will be added for Postgresql Provider, & SQLite Provider.Development 🚧You should create a virtual environment and activate it:python-mvenvvenv/sourcevenv/bin/activateAnd then install the development dependencies:pipinstall-rrequirements.dev.txtFormat the code 💅Execute the following command to applypre-commitformatting:makelintLicense 🍻This project is licensed under the terms of the MIT license.
Package: fastapi-lifespan-manager
Fastapi LifespanManagerfastapi-lifespan-manageris a Python library that provides a lifespan manager for FastAPI applications.TheLifespanManagerinfastapi-lifespan-managerallows you to have multiple lifespan in one
application.This library is particularly useful for managing background tasks, such as starting and stopping a database
connection or managing a cache, as well as for performing cleanup tasks, such as closing open file
handles or shutting down running processes.To usefastapi-lifespan-manager, simply install it via pip:pipinstallfastapi-lifespan-managerUsage Example:fromtypingimportAsyncIteratorfromfastapiimportFastAPIfromredis.asyncioimportRedisfromsqlalchemy.ext.asyncioimportcreate_async_enginefromfastapi_lifespan_managerimportLifespanManager,Statemanager=LifespanManager()@manager.addasyncdefsetup_db(app:FastAPI)->AsyncIterator[State]:engine=awaitcreate_async_engine("postgresql+asyncpg://user:password@localhost/db")yield{"db":engine}awaitengine.dispose()@manager.addasyncdefsetup_cache(app:FastAPI)->AsyncIterator[State]:redis=awaitRedis.from_url("redis://localhost:6379/0")yield{"cache":redis}awaitredis.close()awaitredis.wait_closed()app=FastAPI(lifespan=manager)
Package: fastapi-limiter
fastapi-limiterIntroductionFastAPI-Limiter is a rate limiting tool forfastapiroutes with lua script.RequirementsredisInstallJust install from pypi>pipinstallfastapi-limiterQuick StartFastAPI-Limiter is simple to use, which just provide a dependencyRateLimiter, the following example allow2times
request per5seconds in route/.importredis.asyncioasredisimportuvicornfromfastapiimportDepends,FastAPIfromfastapi_limiterimportFastAPILimiterfromfastapi_limiter.dependsimportRateLimiterapp=FastAPI()@app.on_event("startup")asyncdefstartup():redis_connection=redis.from_url("redis://localhost",encoding="utf-8",decode_responses=True)awaitFastAPILimiter.init(redis_connection)@app.get("/",dependencies=[Depends(RateLimiter(times=2,seconds=5))])asyncdefindex():return{"msg":"Hello World"}if__name__=="__main__":uvicorn.run("main:app",debug=True,reload=True)UsageThere are some config inFastAPILimiter.init.redisTheredisinstance ofaioredis.prefixPrefix of redis key.identifierIdentifier of route limit, default isip, you can override it such asuseridand so on.asyncdefdefault_identifier(request:Request):forwarded=request.headers.get("X-Forwarded-For")ifforwarded:returnforwarded.split(",")[0]returnrequest.client.host+":"+request.scope["path"]callbackCallback when access is forbidden, default is raiseHTTPExceptionwith429status code.asyncdefdefault_callback(request:Request,response:Response,pexpire:int):"""default callback when too many requests:param request::param pexpire: The remaining milliseconds:param response::return:"""expire=ceil(pexpire/1000)raiseHTTPException(HTTP_429_TOO_MANY_REQUESTS,"Too Many Requests",headers={"Retry-After":str(expire)})Multiple limitersYou can use multiple limiters in one route.@app.get("/multiple",dependencies=[Depends(RateLimiter(times=1,seconds=5)),Depends(RateLimiter(times=2,seconds=15)),],)asyncdefmultiple():return{"msg":"Hello World"}Not that you should note the dependencies orders, keep lower of result ofseconds/timesat the first.Rate limiting within a websocket.While the above examples work with rest requests, FastAPI also allows easy usage
of websockets, which require a slightly different approach.Because websockets are likely to be long lived, you may want to rate limit in
response to data sent over the socket.You can do this by rate limiting within the body of the websocket handler:@app.websocket("/ws")asyncdefwebsocket_endpoint(websocket:WebSocket):awaitwebsocket.accept()ratelimit=WebSocketRateLimiter(times=1,seconds=5)whileTrue:try:data=awaitwebsocket.receive_text()awaitratelimit(websocket,context_key=data)# NB: context_key is optionalawaitwebsocket.send_text(f"Hello, world")exceptWebSocketRateLimitException:# Thrown when rate limit exceeded.awaitwebsocket.send_text(f"Hello again")Lua scriptThe lua script used.localkey=KEYS[1]locallimit=tonumber(ARGV[1])localexpire_time=ARGV[2]localcurrent=tonumber(redis.call('get',key)or"0")ifcurrent>0thenifcurrent+1>limitthenreturnredis.call("PTTL",key)elseredis.call("INCR",key)return0endelseredis.call("SET",key,1,"px",expire_time)return0endLicenseThis project is licensed under theApache-2.0License.