| 1 |
""" |
| 2 |
flask_security.oauth_provider |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
Class and methods to create providers for oauth_glue. |
| 6 |
Example providers for github and google. |
| 7 |
|
| 8 |
:copyright: (c) 2024-2024 by J. Christopher Wagner (jwag). |
| 9 |
:license: MIT, see LICENSE for more details. |
| 10 |
|
| 11 |
""" |
| 12 |
|
| 13 |
from __future__ import annotations |
| 14 |
import collections.abc as cabc |
| 15 |
|
| 16 |
try: |
| 17 |
from authlib.integrations.flask_client import OAuth |
| 18 |
from authlib.integrations.base_client.errors import ( |
| 19 |
OAuthError, |
| 20 |
) |
| 21 |
except ImportError: # pragma: no cover |
| 22 |
pass |
| 23 |
|
| 24 |
import typing as t |
| 25 |
|
| 26 |
from flask import redirect |
| 27 |
|
| 28 |
from .utils import ( |
| 29 |
config_value as cv, |
| 30 |
do_flash, |
| 31 |
get_message, |
| 32 |
get_url, |
| 33 |
url_for_security, |
| 34 |
) |
| 35 |
|
| 36 |
if t.TYPE_CHECKING: # pragma: no cover |
| 37 |
from flask.typing import ResponseValue |
| 38 |
|
| 39 |
OauthCbType = cabc.Callable[["OAuth", t.Any], tuple[str, t.Any]] |
| 40 |
|
| 41 |
|
| 42 |
class FsOAuthProvider: |
| 43 |
""" |
| 44 |
Subclass this or instantiate to add new OAuth providers. |
| 45 |
|
| 46 |
Subclassing allows for customizing additional aspects of the OAuth flow |
| 47 |
in particular - a custom error path for OAuth flow state mismatches and |
| 48 |
other errors thrown by authlib. |
| 49 |
|
| 50 |
Call security.oauthglue.register_provider_ext(myproviderclass("myprovider")) |
| 51 |
|
| 52 |
:param name: a name for provider - must match what was passed if this |
| 53 |
is already registered with OAuth. |
| 54 |
:param registration_info: This dict is passed directly to OAuth as |
| 55 |
part of registration - not needed if provider already registered with |
| 56 |
Oauth |
| 57 |
:param fetch_identity_cb: Call back from response to oauth flow. |
| 58 |
""" |
| 59 |
|
| 60 |
def __init__( |
| 61 |
self, |
| 62 |
name: str, |
| 63 |
registration_info: dict[str, t.Any] | None = None, |
| 64 |
fetch_identity_cb: OauthCbType | None = None, |
| 65 |
): |
| 66 |
self.name = name |
| 67 |
self._registration_info = registration_info or {} |
| 68 |
self._fetch_identity_cb = fetch_identity_cb |
| 69 |
|
| 70 |
def authlib_config(self) -> dict[str, t.Any]: |
| 71 |
"""Return dict with authlib configuration. |
| 72 |
This is called as part of provider registration.""" |
| 73 |
return self._registration_info |
| 74 |
|
| 75 |
def fetch_identity_cb(self, oauth: OAuth, token: t.Any) -> tuple[str, t.Any]: |
| 76 |
"""This callback is called when the oauth |
| 77 |
redirect happens. It must take the response from the provider and return |
| 78 |
a tuple of <user_model_field_name, value> - which will be used |
| 79 |
to look up the user in the datastore.""" |
| 80 |
if not self._fetch_identity_cb: # pragma no cover |
| 81 |
raise NotImplementedError |
| 82 |
return self._fetch_identity_cb(oauth, token) |
| 83 |
|
| 84 |
def oauth_response_failure(self, error_view: str, e: OAuthError) -> ResponseValue: |
| 85 |
"""Called if authlib authorize_access_token throws an error. |
| 86 |
|
| 87 |
N.B. flashing doesn't seem to work in some cases - if the session |
| 88 |
cookie has samesite='strict' and it is the first registration. |
| 89 |
""" |
| 90 |
m, c = get_message( |
| 91 |
"OAUTH_HANDSHAKE_ERROR", exerror=e.error, exdesc=e.description |
| 92 |
) |
| 93 |
if cv("REDIRECT_BEHAVIOR") == "spa": |
| 94 |
return redirect(get_url(cv(error_view), qparams={c: m})) |
| 95 |
do_flash(m, c) |
| 96 |
return redirect(url_for_security("login")) |
| 97 |
|
| 98 |
|
| 99 |
class GitHubFsOauthProvider(FsOAuthProvider): |
| 100 |
def authlib_config(self): |
| 101 |
return dict( |
| 102 |
access_token_url="https://github.com/login/oauth/access_token", |
| 103 |
access_token_params=None, |
| 104 |
authorize_url="https://github.com/login/oauth/authorize", |
| 105 |
authorize_params=None, |
| 106 |
api_base_url="https://api.github.com/", |
| 107 |
client_kwargs={"scope": "user:email"}, |
| 108 |
) |
| 109 |
|
| 110 |
def fetch_identity_cb(self, oauth, token): |
| 111 |
resp = oauth.github.get("user", token=token) |
| 112 |
profile = resp.json() |
| 113 |
return "email", profile["email"] |
| 114 |
|
| 115 |
|
| 116 |
class GoogleFsOauthProvider(FsOAuthProvider): |
| 117 |
def authlib_config(self): |
| 118 |
return dict( |
| 119 |
server_metadata_url="https://accounts.google.com/" |
| 120 |
".well-known/openid-configuration", |
| 121 |
client_kwargs={"scope": "openid email profile"}, |
| 122 |
) |
| 123 |
|
| 124 |
def fetch_identity_cb(self, oauth, token): # pragma no cover |
| 125 |
profile = token["userinfo"] |
| 126 |
return "email", profile["email"] |