Make sure to import HTTPBasicAuth and HTTPTokenAuth from APIFlask and use the
app.auth_required decorator to protect the views.
auth.current_user works just like auth.current_user(), but shorter.
Warning
Cookie authentication is currently not supported for “try it out” requests due to browser security restrictions in Swagger UI. See this issue for more information.
When using the HTTPBasicAuth, HTTPTokenAuth, and app.auth_required to implement
the authentication, APIFlask can generate the OpenAPI security spec automatically. When
you use the external authentication library, APIFlask still offers the way to set the
OpenAPI spec.
You can use the SECURITY_SCHEMES config or the app.security_schemes attribute to
set the OpenAPI security schemes:
app=APIFlask(__name__)app.security_schemes={# equals to use config SECURITY_SCHEMES'ApiKeyAuth':{'type':'apiKey','in':'header','name':'X-API-Key',}}
Then you can set the security scheme with the security parameter in app.doc() decorator:
@app.post('/pets')@my_auth_lib.protect# protect the view with the decorator provided by external authentication library@app.input(PetIn)@app.output(PetOut,status_code=201)@app.doc(security='ApiKeyAuth')defcreate_pet(json_data):pet_id=len(pets)data['id']=pet_idpets.append(json_data)returnpets[pet_id]
With APIFlask 1.0.2, when using the built-in auth support and external auth
library at the same time, the security schemes will be combined.
app.auth_required will generate the operation security automatically, if you use the @doc(security=...)
with a view that already used app.auth_required, then the value passed in @doc(security=...) will be used.