I would like to have a common auth entry point, such as get_authed_user, that loops through a configurable list of authentication dependencies, and the first one that is able to return a user does so. Something like the following:
from app.conf import settings # this is pydantic's BaseSettings
async def get_authed_user(request: Request, Session = Depends(get_session)):
for cls_name in settings.AUTHENTICATION_CLASSES:
method = import_class(cls_name)(auto_error=False)
user = method() # how to resolve dependencies here?
if user:
return user
raise HTTP401Error
When calling the authentication callables, is there a way to resolve the dependencies of those callables?
Related
I need help understanding how to process a user-supplied token in my FastApi app.
I have a simple app that takes a user-session key, this may be a jwt or not. I will then call a separate API to validate this token and proceed with the request or not.
Where should this key go in the request:
In the Authorization header as a basic token?
In a custom user-session header key/value?
In the request body with the rest of the required information?
I've been playing around with option 2 and have found several ways of doing it:
Using APIKey as described here:
async def create(api_key: APIKey = Depends(validate)):
Declaring it in the function as described in the docs here
async def create(user_session: str = Header(description="The Users session key")): and having a separate Depends in the router config,
The best approach is to build a custom dependency using any one of the already existing authentication dependencies as a reference.
Example:
class APIKeyHeader(APIKeyBase):
def __init__(
self,
*,
name: str,
scheme_name: Optional[str] = None,
description: Optional[str] = None,
auto_error: bool = True
):
self.model: APIKey = APIKey(
**{"in": APIKeyIn.header}, name=name, description=description
)
self.scheme_name = scheme_name or self.__class__.__name__
self.auto_error = auto_error
async def __call__(self, request: Request) -> Optional[str]:
api_key: str = request.headers.get(self.model.name)
# add your logic here, something like the one below
if not api_key:
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
)
else:
return None
return api_key
After that, just follow this from documentation to use your dependency.
I'm using opencensus-python to track requests to my python fastapi application running in production, and exporting the information to Azure AppInsights using the opencensus exporters. I followed the Azure Monitor docs and was helped out by this issue post which puts all the necessary bits in a useful middleware class.
Only to realize later on that requests that caused the app to crash, i.e. unhandled 5xx type errors, would never be tracked, since the call to execute the logic for the request fails before any tracing happens. The Azure Monitor docs only talk about tracking exceptions through the logs, but this is separate from the tracing of requests, unless I'm missing something. I certainly wouldn't want to lose out on failed requests, these are super important to track! I'm accustomed to using the "Failures" tab in app insights to monitor any failing requests.
I figured the way to track these requests is to explicitly handle any internal exceptions using try/catch and export the trace, manually setting the result code to 500. But I found it really odd that there seems to be no documentation of this, on opencensus or Azure.
The problem I have now is: this middleware function is expected to pass back a "response" object, which fastapi then uses as a callable object down the line (not sure why) - but in the case where I caught an exception in the underlying processing (i.e. at await call_next(request)) I don't have any response to return. I tried returning None but this just causes further exceptions down the line (None is not callable).
Here is my version of the middleware class - its very similar to the issue post I linked, but I'm try/catching over await call_next(request) rather than just letting it fail unhanded. Scroll down to the final 5 lines of code to see that.
import logging
from fastapi import Request
from opencensus.trace import (
attributes_helper,
execution_context,
samplers,
)
from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace import span as span_module
from opencensus.trace import tracer as tracer_module
from opencensus.trace import utils
from opencensus.trace.propagation import trace_context_http_header_format
from opencensus.ext.azure.log_exporter import AzureLogHandler
from starlette.types import ASGIApp
from src.settings import settings
HTTP_HOST = attributes_helper.COMMON_ATTRIBUTES["HTTP_HOST"]
HTTP_METHOD = attributes_helper.COMMON_ATTRIBUTES["HTTP_METHOD"]
HTTP_PATH = attributes_helper.COMMON_ATTRIBUTES["HTTP_PATH"]
HTTP_ROUTE = attributes_helper.COMMON_ATTRIBUTES["HTTP_ROUTE"]
HTTP_URL = attributes_helper.COMMON_ATTRIBUTES["HTTP_URL"]
HTTP_STATUS_CODE = attributes_helper.COMMON_ATTRIBUTES["HTTP_STATUS_CODE"]
module_logger = logging.getLogger(__name__)
module_logger.addHandler(AzureLogHandler(
connection_string=settings.appinsights_connection_string
))
class AppInsightsMiddleware:
"""
Middleware class to handle tracing of fastapi requests and exporting the data to AppInsights.
Most of the code here is copied from a github issue: https://github.com/census-instrumentation/opencensus-python/issues/1020
"""
def __init__(
self,
app: ASGIApp,
excludelist_paths=None,
excludelist_hostnames=None,
sampler=None,
exporter=None,
propagator=None,
) -> None:
self.app = app
self.excludelist_paths = excludelist_paths
self.excludelist_hostnames = excludelist_hostnames
self.sampler = sampler or samplers.AlwaysOnSampler()
self.propagator = (
propagator or trace_context_http_header_format.TraceContextPropagator()
)
self.exporter = exporter or AzureExporter(
connection_string=settings.appinsights_connection_string
)
async def __call__(self, request: Request, call_next):
# Do not trace if the url is in the exclude list
if utils.disable_tracing_url(str(request.url), self.excludelist_paths):
return await call_next(request)
try:
span_context = self.propagator.from_headers(request.headers)
tracer = tracer_module.Tracer(
span_context=span_context,
sampler=self.sampler,
exporter=self.exporter,
propagator=self.propagator,
)
except Exception:
module_logger.error("Failed to trace request", exc_info=True)
return await call_next(request)
try:
span = tracer.start_span()
span.span_kind = span_module.SpanKind.SERVER
span.name = "[{}]{}".format(request.method, request.url)
tracer.add_attribute_to_current_span(HTTP_HOST, request.url.hostname)
tracer.add_attribute_to_current_span(HTTP_METHOD, request.method)
tracer.add_attribute_to_current_span(HTTP_PATH, request.url.path)
tracer.add_attribute_to_current_span(HTTP_URL, str(request.url))
execution_context.set_opencensus_attr(
"excludelist_hostnames", self.excludelist_hostnames
)
except Exception: # pragma: NO COVER
module_logger.error("Failed to trace request", exc_info=True)
try:
response = await call_next(request)
tracer.add_attribute_to_current_span(HTTP_STATUS_CODE, response.status_code)
tracer.end_span()
return response
# Explicitly handle any internal exception here, and set status code to 500
except Exception as exception:
module_logger.exception(exception)
tracer.add_attribute_to_current_span(HTTP_STATUS_CODE, 500)
tracer.end_span()
return None
I then register this middleware class in main.py like so:
app.middleware("http")(AppInsightsMiddleware(app, sampler=samplers.AlwaysOnSampler()))
Explicitly handle any exception that may occur in processing the API request. That allows you to finish tracing the request, setting the status code to 500. You can then re-throw the exception to ensure that the application raises the expected exception.
try:
response = await call_next(request)
tracer.add_attribute_to_current_span(HTTP_STATUS_CODE, response.status_code)
tracer.end_span()
return response
# Explicitly handle any internal exception here, and set status code to 500
except Exception as exception:
module_logger.exception(exception)
tracer.add_attribute_to_current_span(HTTP_STATUS_CODE, 500)
tracer.end_span()
raise exception
I am new to flask, recently learned about flask_security/flask_login/flask_user.
I wish that somehow I could use flask_login along with flask-JWT, for the REST API.
Basically, I'd like to have the features like remember-me, forgot-password etc, from the flask_login
Upon searching, I found that it couldn't be done on the same flask view.
Could somebody guide me, how to do it?
Thanks.
flask-login provides the request_loader callback exactly for this purpose, for authenticating requests in a custom way.
In my case, I added this to my create_app function:
#login_manager.request_loader
def load_user_from_request(request):
auth_headers = request.headers.get('Authorization', '').split()
if len(auth_headers) != 2:
return None
try:
token = auth_headers[1]
data = jwt.decode(token, current_app.config['SECRET_KEY'])
user = User.by_email(data['sub'])
if user:
return user
except jwt.ExpiredSignatureError:
return None
except (jwt.InvalidTokenError, Exception) as e:
return None
return None
Otherwise, I followed this tutorial, so the token is created like this (in the login function):
token = jwt.encode({
'sub': user.email,
'iat':datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(minutes=30)},
current_app.config['SECRET_KEY'])
This way you can just use #login_required from flask-login instead of defining a custom decorator to protect views.
I used PyJWT instead of Flask-JWT since it seems Flask-JWT is discontinued.
I am having problems implementing HttpBuilder-NG basic authentication for a Cucumber feature step definition using Gradle, Groovy and Junit. I have sucessfully implemented this step definition using Behat/PHP. I have also verified the test using Postman.
Here is the build.gradle file
apply plugin: 'groovy'
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.12'
compile 'io.github.http-builder-ng:http-builder-ng-core:1.0.2'
testCompile 'junit:junit:4.12'
testCompile 'info.cukes:cucumber-groovy:1.2.5'
testCompile 'info.cukes:cucumber-junit:1.2.5'
}
The github API /user/repos path requires authentication to retrieve the user's repository information but the Get is returning an unAuthorized exception. If I leave out the path I get success but the base URL does not require authentication. Here is the Groovy code:
import static cucumber.api.groovy.EN.*
import cucumber.api.PendingException
import static groovyx.net.http.HttpBuilder.configure
import static groovyx.net.http.util.SslUtils.ignoreSslIssues
Given(~/^I am an authenticated user$/) { ->
def github = configure {
ignoreSslIssues execution
request.uri = 'https://api.github.com'
request.auth.basic('githubUser', 'githubPassword', false)
}.get {
request.uri.path = '/user/repos'
}
assert github != null
println github.dump()
}
And here is the exception I am getting (401):
groovyx.net.http.HttpException: Unauthorized
at groovyx.net.http.NativeHandlers.failure(NativeHandlers.java:69)
at groovyx.net.http.HttpConfigs$BaseHttpConfig$$Lambda$9/15235276.apply(Unknown Source)
at groovyx.net.http.HttpBuilder$ResponseHandlerFunction.apply(HttpBuilder.java:2305)
at groovyx.net.http.JavaHttpBuilder$Action.lambda$execute$2(JavaHttpBuilder.java:168)
at groovyx.net.http.JavaHttpBuilder$Action$$Lambda$56/33475769.call(Unknown Source)
at groovyx.net.http.JavaHttpBuilder$ThreadLocalAuth.with(JavaHttpBuilder.java:331)
at groovyx.net.http.JavaHttpBuilder$Action.execute(JavaHttpBuilder.java:122)
at groovyx.net.http.JavaHttpBuilder.createAndExecute(JavaHttpBuilder.java:374)
at groovyx.net.http.JavaHttpBuilder.doGet(JavaHttpBuilder.java:381)
at groovyx.net.http.HttpBuilder$$Lambda$25/32560218.apply(Unknown Source)
at groovyx.net.http.HttpObjectConfigImpl.nullInterceptor(HttpObjectConfigImpl.java:47)
at groovyx.net.http.HttpObjectConfigImpl$Exec$$Lambda$23/7279823.apply(Unknown Source)
at groovyx.net.http.HttpBuilder.get(HttpBuilder.java:346)
Gradle Test Executor 191 finished executing tests.
at groovyx.net.http.HttpBuilder.get(HttpBuilder.java:1297)
at groovyx.net.http.HttpBuilder$get$0.call(Unknown Source)
at repo-create_steps$_run_closure1.doCall(repo-create_steps.groovy:7)
at ?.Given I am an authenticated user(repo-create.feature:3)
It looks like GitHub does provide BASIC support (https://developer.github.com/v3/auth/) but it is non-standard and they suggest creating the Authorization header yourself, which would look something like this:
#Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.2')
import static groovyx.net.http.HttpBuilder.configure
import static groovyx.net.http.util.SslUtils.ignoreSslIssues
def username = 'blah'
def password = 'blah'
def creds = "$username:$password".bytes.encodeBase64()
def github = configure {
ignoreSslIssues execution
request.uri = 'https://api.github.com'
request.headers['Authorization'] = "Basic $creds"
}.get {
request.uri.path = '/user/repos'
response.failure { fs, obj->
println "Status: ${fs.statusCode}"
fs.headers.each { h->
println h
}
}
}
println github.dump()
However, this presents a problem which you may not have on your end. I have 2-factor authentication enabled on my account so I get the X-GitHub-OTP: required; :2fa-type header back (per the documentation linked above). If you do not have 2-factor you should have what you need.
I added the failure handler to get some additional information about the failure cases - it's not required for the solution.
I'm attempting to configure Flask-Security to send email asynchronously.
I have some code which send async email via Flask-Mail, but I'm having trouble integrating it with my application factory function so that it works in conjunction with Flask-Security.
Application factory:
mail = Mail()
db = SQLAlchemy()
security = Security()
from app.models import User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
def create_app(config_name):
# Config
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
# Initialize extensions
mail.init_app(app)
db.init_app(app)
security.init_app(app, user_datastore)
return app
In the Flask-Security documentation it says to use #security.send_mail_task to override the way the extension sends emails.
So where exactly do I implement this decorator? Seems like anywhere I put it inside the application factory, I get circular imports.
These are the async email functions I am trying to use, taken from this issue:
#async
def send_security_email(msg):
with app.app_context():
mail.send(msg)
#security.send_mail_task
def async_security_email(msg):
send_security_email(msg)
Where does this code need to be put in order to work with the app factory?
Thanks in advance.
I was able to achieve this like so:
mail = Mail()
db = SQLAlchemy()
security = Security()
from app.models import User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
def create_app(config_name):
# Config
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
# Initialize extensions
mail.init_app(app)
db.init_app(app)
security_ctx = security.init_app(app, user_datastore)
# Send Flask-Security emails asynchronously
#security_ctx.send_mail_task
def async_security_email(msg):
send_security_email(app, mail, msg)
return app