API Reference
This page contains the documentation of all the members exported by mwoauth2.
Tools should use one of four classes depending on the other libraries they use:
Flask tools that use mwapi should use
MWOAuth2FlaskMWApi.Other Flask tools should use
MWOAuth2Flask.Non-Flask tools that use mwapi should use
MWOAuth2MWApi.Other tools should use
MWOAuth2.
- class mwoauth2.MWOAuth2(host: str, client_id: str, client_secret: str, get_oauth_state: Callable[[P], dict[str, Any] | None], set_oauth_state: Callable[[Concatenate[dict[str, Any], P]], None], pop_oauth_state: Callable[[P], dict[str, Any]], get_access_token: Callable[[P], dict[str, Any] | None], set_access_token: Callable[[Concatenate[dict[str, Any], P]], None], pop_access_token: Callable[[P], dict[str, Any]], user_agent: str, api_path: str = '/w/api.php')[source]
Base class managing OAuth 2 authentication against a MediaWiki wiki.
A single instance of this class can be used for multiple users, and is typically set up at tool initialization time. It contains the details of the client wiki, the OAuth credentials, and accessors for some kind of session store where the OAuth state is kept.
To start the authentication flow for a user, call
authorization_url()and send the user to the returned URL. Once they return, callfetch_token()with the request URL. Afterwards, you can useoauth2_session()to make authenticated requests. To check if the user is logged in or not, usehas_access_token().- Parameters:
host (str) – The host of the wiki, e.g.
https://en.wikipedia.org. Should include the protocol (scheme) and host name, but no path (useapi_pathif necessary).client_id (str) – The OAuth client ID, a string of 32 hexadecimal characters.
client_secret (str) – The OAuth client secret, a string of 40 hexadecimal characters. This should come from some kind of secret configuration source, e.g. a config file or environment variables.
get_oauth_state (Callable[P, dict[str, Any] | None]) – This, along with the next five parameters, represents the interface to the session store. This should be backed by some kind of user session, usually provided by your web framework, and is used to store the OAuth state (during login) and access token (subsequently). The type parameter
Pspecifies the parameters that are necessary to access the session store; these parameters are passed through from the other functions (fetch_token()etc.) to the session store accessors. Most of the time, this will be either a single “session” object (e.g. the Djangorequest.sessionor the FastAPI dependency-injectedsession) or no parameters at all (e.g. theflask.sessionproxy, seeMWOAuth2Flask). This function should return the OAuth state if it has been set, otherwiseNone.set_oauth_state (Callable[Concatenate[dict[str, Any], P], None]) – Set the OAuth state to the given value.
pop_oauth_state (Callable[P, dict[str, Any]]) – Return and remove the OAuth state, or raise a
KeyErrorif it has not been set.get_access_token (Callable[P, dict[str, Any] | None]) – Get the access token if it has been set, otherwise
None.set_access_token (Callable[Concatenate[dict[str, Any], P], None]) – Set the access token to the given value.
pop_access_token (Callable[P, dict[str, Any]]) – Return and remove the access token, or raise a
KeyErrorif it has not been set. This is the only one of the six functions that is useful for a tool to call directly: calling this will log the user out.user_agent (str) – The User-Agent string that should be sent with all requests, in accordance with the User-Agent Policy. Toolforge tools can get a suitable string from
toolforge.set_user_agent().api_path (str) – The path to the
api.phpendpoint, relative to thehost(see above). The default of/w/api.phpis suitable for all Wikimedia wikis and many other wikis as well.
- authorization_url(*args: P, **kwargs: P) str[source]
Generate a URL to start the login flow.
If the user is not logged in (according to
has_access_token()), call this function and redirect the user to the returned URL. When the user returns to your tool, callfetch_token()to complete the login.Calling this function multiple times with the same session store state will return the same URL, so there is no need to save the URL anywhere: just call
authorization_url()again each time the user wants to log in, regardless of whether a login is already pending or not.- Parameters:
args – Arguments passed through to the session store accessors.
kwargs – Likewise.
- fetch_token(request_url: str, *args: P, **kwargs: P) None[source]
Complete the login flow.
After the user has been redirected back to your tool by MediaWiki, call this function with the request URL, which should contain a
codeparameter. The resulting access token will be saved in the session store; afterwards,has_access_token()will return true, andoauth2_session()will return a non-Nonesession which you can use to make authenticated requests.OAuthLib insists that the request URL uses HTTPS (raising an
InsecureTransportErrorotherwise). In order to accommodate some common setups, this function will pretend thatlocalhostrequest URLs used HTTPS (as there is no risk of the token being intercepted on the network in this case), and will also coerce URLs under Wikimedia Cloud Services domains to HTTPS (under the assumption that HTTPS will have been enforced via HSTS Preloading, but the URL seen by your tool may be an HTTP URL because your tool has not been configured to trust the incomingX-Forwarded-Proto: httpsheader).- Parameters:
request_url (str) – The request URL with which your tool was called.
args – Arguments passed through to the session store accessors.
kwargs – Likewise.
- has_access_token(*args: P, **kwargs: P) bool[source]
Check whether the session store contains an access token.
If true, the user should be treated as logged in; if false, they are logged out, and
authorization_url()can be used to start the login flow.- Parameters:
args – Arguments passed through to the session store accessors.
kwargs – Likewise.
- has_well_formed_access_token(*args: P, **kwargs: P) bool[source]
Check whether the session store contains a well-formed access token.
This is useful for tools that migrated from OAuth 1.0a to OAuth 2, and stored the OAuth 1.0a in the session store under the same name as the OAuth 2 access token. In that case, merely checking
has_access_token()could be misleading, as it might indicate an outdated OAuth 1.0a access token. (Flask tools, see also thecheck_access_token_before_requestparameter ofMWOAuth2Flask.) Tools that never used OAuth 1.0a have no need for this method.- Parameters:
args – Arguments passed through to the session store accessors.
kwargs – Likewise.
- oauth2_session(*args: P, **kwargs: P) OAuth2Session | None[source]
Return an OAuth 2 session (if the user is logged in).
If
has_access_token()isFalse, this function returnsNone. Otherwise, it returns arequests.Session-like object which can be used to make authenticated requests.mwapi users will want to use
mwapi_session()instead.- Parameters:
args – Arguments passed through to the session store accessors.
kwargs – Likewise.
- class mwoauth2.MWOAuth2Flask(host: str, user_agent: str, app: Flask | None = None, check_access_token_before_request: bool = False, client_id: str | None = None, client_secret: str | None = None, get_oauth_state: Callable[[], dict[str, Any] | None] | None = None, set_oauth_state: Callable[[dict[str, Any]], None] | None = None, pop_oauth_state: Callable[[], dict[str, Any]] | None = None, get_access_token: Callable[[], dict[str, Any] | None] | None = None, set_access_token: Callable[[dict[str, Any]], None] | None = None, pop_access_token: Callable[[], dict[str, Any]] | None = None, api_path: str = '/w/api.php')[source]
Flask extension managing OAuth 2 authentication against a MediaWiki wiki.
A single instance of this class can be used for multiple users, and is typically set up at tool initialization (either passing the Flask app into the constructor or calling
init_app()later). It contains the details of the client wiki and (by default) uses the Flask configuration for OAuth credentials and the Flask session for the OAuth state.The Flask app’s configuration should contain an
OAUTHkey whose value is a dict with two members: the client ID (a string of 32 hexadecimal characters) inCLIENT_ID, and the client secret (a string of 40 hexadecimal characters) inCLIENT_SECRET. For instance, when usingfrom_prefixed_env()with the prefixTOOL, these would be set using the environment variablesTOOL_OAUTH__CLIENT_IDandTOOL_OAUTH__CLIENT_SECRET.To start the authentication flow for a user, call
authorization_url()and send the user to the returned URL. Once they return, callfetch_token(). Afterwards, you can useoauth2_session()to make authenticated requests. To check if the user is logged in or not, usehas_access_token().- Parameters:
host (str) – The host of the wiki, e.g.
https://en.wikipedia.org. Should include the protocol (scheme) and host name, but no path (useapi_pathif necessary).user_agent (str) – The User-Agent string that should be sent with all requests, in accordance with the User-Agent Policy. Toolforge tools can get a suitable string from
toolforge.set_user_agent().app (flask.Flask) – The Flask app. If this is not
None,init_app()will be called with it; otherwise, you should callinit_app()later. (Doing the init separately can be useful with the application factory pattern or to avoid circular import issues.)check_access_token_before_request (bool) – If
True, register abefore_request()handler to check if the access token is valid (according tohas_well_formed_access_token()). This is only useful for tools that migrated from OAuth 1.0a to OAuth 2, and which also stored the OAuth 1.0a access token in the Flask session under the keyoauth_access_token. In that case, enable this feature so that the outdated OAuth 1.0a access token will automatically be discarded (i.e. the user has to log in again), instead of trying to use it as an OAuth 2 access token and crashing. Disabled by default.client_id (str|None) – The OAuth client ID. By default, this is loaded from the app config as described above, so you normally do not need to specify this.
client_secret (str|None) – The OAuth client secret, likewise.
get_oauth_state – By default, this uses the Flask session and you do not need to specify it. (If you do want to change it, you will have to change all six session store accessor functions together; see the
MWOAuth2documentation in that case.)set_oauth_state – Likewise.
pop_oauth_state – Likewise.
get_access_token – Likewise.
set_access_token – Likewise.
pop_access_token – Likewise.
api_path (str) – The path to the
api.phpendpoint, relative to thehost(see above). The default of/w/api.phpis suitable for all Wikimedia wikis and many other wikis as well.
- has_access_token() bool
Check whether the session store contains an access token.
If true, the user should be treated as logged in; if false, they are logged out, and
authorization_url()can be used to start the login flow.
- has_well_formed_access_token() bool
Check whether the session store contains a well-formed access token.
You generally don’t need to call this directly – instead, see the
check_access_token_before_requestconstructor parameter. (For more information on this method, seeMWOAuth2.has_well_formed_access_token().)
- authorization_url() str
Generate a URL to start the login flow.
If the user is not logged in (according to
has_access_token()), call this function and redirect the user to the returned URL. When the user returns to your tool, callfetch_token()to complete the login.Calling this function multiple times with the same session store state will return the same URL, so there is no need to save the URL anywhere: just call
authorization_url()again each time the user wants to log in, regardless of whether a login is already pending or not.
- oauth2_session() requests_oauthlib.OAuth2Session | None
Return an OAuth 2 session (if the user is logged in).
If
has_access_token()isFalse, this function returnsNone. Otherwise, it returns arequests.Session-like object which can be used to make authenticated requests.mwapi users will want to use
mwapi_session()instead.
- fetch_token(request_url: str | None = None) None[source]
Complete the login flow.
After the user has been redirected back to your tool by MediaWiki, call this function. (The
request_urldefaults to the Flask request URL, so you can usually omit it.) The resulting access token will be saved in the session store; afterwards,has_access_token()will return true, andoauth2_session()will return a non-Nonesession which you can use to make authenticated requests.OAuthLib insists that the request URL uses HTTPS (raising an
InsecureTransportErrorotherwise). In order to accommodate some common setups, this function will pretend thatlocalhostrequest URLs used HTTPS (as there is no risk of the token being intercepted on the network in this case), and will also coerce URLs under Wikimedia Cloud Services domains to HTTPS (under the assumption that HTTPS will have been enforced via HSTS Preloading, but the URL seen by your tool may be an HTTP URL because your tool has not been configured to trust the incomingX-Forwarded-Proto: httpsheader).- Parameters:
request_url (str|None) – The request URL with which your tool was called, if you want to override the default Flask request URL.
- init_app(app: Flask) None[source]
Initialize using the given Flask app.
If you passed a Flask app into the constructor, this method will be called automatically. Otherwise, you should manually call it later. It reads the OAuth client ID and secret from the Flask configuration as described above, and also sets up the
check_access_token_before_requestfeature if enabled.
- class mwoauth2.MWOAuth2FlaskMWApi(host: str, user_agent: str, app: Flask | None = None, check_access_token_before_request: bool = False, client_id: str | None = None, client_secret: str | None = None, get_oauth_state: Callable[[], dict[str, Any] | None] | None = None, set_oauth_state: Callable[[dict[str, Any]], None] | None = None, pop_oauth_state: Callable[[], dict[str, Any]] | None = None, get_access_token: Callable[[], dict[str, Any] | None] | None = None, set_access_token: Callable[[dict[str, Any]], None] | None = None, pop_access_token: Callable[[], dict[str, Any]] | None = None, api_path: str = '/w/api.php')[source]
Flask extension managing OAuth 2 authentication against a MediaWiki wiki.
A single instance of this class can be used for multiple users, and is typically set up at tool initialization (either passing the Flask app into the constructor or calling
init_app()later). It contains the details of the client wiki and (by default) uses the Flask configuration for OAuth credentials and the Flask session for the OAuth state.The Flask app’s configuration should contain an
OAUTHkey whose value is a dict with two members: the client ID (a string of 32 hexadecimal characters) inCLIENT_ID, and the client secret (a string of 40 hexadecimal characters) inCLIENT_SECRET. For instance, when usingfrom_prefixed_env()with the prefixTOOL, these would be set using the environment variablesTOOL_OAUTH__CLIENT_IDandTOOL_OAUTH__CLIENT_SECRET.To start the authentication flow for a user, call
authorization_url()and send the user to the returned URL. Once they return, callfetch_token(). Afterwards, you can usemwapi_session()to make authenticated requests. To check if the user is logged in or not, usehas_access_token().- Parameters:
host (str) – The host of the wiki, e.g.
https://en.wikipedia.org. Should include the protocol (scheme) and host name, but no path (useapi_pathif necessary).user_agent (str) – The User-Agent string that should be sent with all requests, in accordance with the User-Agent Policy. Toolforge tools can get a suitable string from
toolforge.set_user_agent().app (flask.Flask) – The Flask app. If this is not
None,init_app()will be called with it; otherwise, you should callinit_app()later. (Doing the init separately can be useful with the application factory pattern or to avoid circular import issues.)check_access_token_before_request (bool) – If
True, register abefore_request()handler to check if the access token is valid (according tohas_well_formed_access_token()). This is only useful for tools that migrated from OAuth 1.0a to OAuth 2, and which also stored the OAuth 1.0a access token in the Flask session under the keyoauth_access_token. In that case, enable this feature so that the outdated OAuth 1.0a access token will automatically be discarded (i.e. the user has to log in again), instead of trying to use it as an OAuth 2 access token and crashing. Disabled by default.client_id (str|None) – The OAuth client ID. By default, this is loaded from the app config as described above, so you normally do not need to specify this.
client_secret (str|None) – The OAuth client secret, likewise.
get_oauth_state – By default, this uses the Flask session and you do not need to specify it. (If you do want to change it, you will have to change all six session store accessor functions together; see the
MWOAuth2documentation in that case.)set_oauth_state – Likewise.
pop_oauth_state – Likewise.
get_access_token – Likewise.
set_access_token – Likewise.
pop_access_token – Likewise.
api_path (str) – The path to the
api.phpendpoint, relative to thehost(see above). The default of/w/api.phpis suitable for all Wikimedia wikis and many other wikis as well.
- init_app(app: flask.Flask) None
Initialize using the given Flask app.
If you passed a Flask app into the constructor, this method will be called automatically. Otherwise, you should manually call it later. It reads the OAuth client ID and secret from the Flask configuration as described above, and also sets up the
check_access_token_before_requestfeature if enabled.
- has_access_token() bool
Check whether the session store contains an access token.
If true, the user should be treated as logged in; if false, they are logged out, and
authorization_url()can be used to start the login flow.
- has_well_formed_access_token() bool
Check whether the session store contains a well-formed access token.
You generally don’t need to call this directly – instead, see the
check_access_token_before_requestconstructor parameter. (For more information on this method, seeMWOAuth2.has_well_formed_access_token().)
- authorization_url() str
Generate a URL to start the login flow.
If the user is not logged in (according to
has_access_token()), call this function and redirect the user to the returned URL. When the user returns to your tool, callfetch_token()to complete the login.Calling this function multiple times with the same session store state will return the same URL, so there is no need to save the URL anywhere: just call
authorization_url()again each time the user wants to log in, regardless of whether a login is already pending or not.
- fetch_token(request_url: str | None = None) None
Complete the login flow.
After the user has been redirected back to your tool by MediaWiki, call this function. (The
request_urldefaults to the Flask request URL, so you can usually omit it.) The resulting access token will be saved in the session store; afterwards,has_access_token()will return true, andmwapi_session()will return a non-Nonesession which you can use to make authenticated requests.OAuthLib insists that the request URL uses HTTPS (raising an
InsecureTransportErrorotherwise). In order to accommodate some common setups, this function will pretend thatlocalhostrequest URLs used HTTPS (as there is no risk of the token being intercepted on the network in this case), and will also coerce URLs under Wikimedia Cloud Services domains to HTTPS (under the assumption that HTTPS will have been enforced via HSTS Preloading, but the URL seen by your tool may be an HTTP URL because your tool has not been configured to trust the incomingX-Forwarded-Proto: httpsheader).- Parameters:
request_url (str|None) – The request URL with which your tool was called, if you want to override the default Flask request URL.
- mwapi_session(host: str | None = None, api_path: str | None = None) mwapi.Session | None
Return an authenticated mwapi session (if the user is logged in).
If
has_access_token()isFalse, this function returnsNone. Otherwise, it returns anmwapi.Sessionwhich can be used to make authenticated requests.- Parameters:
host (str|None) – The host of the wiki, e.g.
https://en.wikipedia.org. Defaults to thehostparameter of the class, but can be changed, e.g. to authenticate againsthttps://meta.wikimedia.organd subsequently make requests tohttps://en.wikipedia.org,https://commons.wikimedia.orgetc., or more generally to target different wikis in a wiki farm with a central authentication system.api_path (str) – The path to the
api.phpendpoint, relative to thehost(see above). Defaults to theapi_pathparameter of the class.
- exception mwoauth2.MWOAuth2FlaskUninitializedException(class_name: str)[source]
Raised when OAuth has not been initialized.
MWOAuth2FlaskandMWOAuth2FlaskMWApisupport three ways to configure the OAuth client ID and client secret: a Flask app with['OAUTH']['CLIENT_ID']in theconfigmay be passed into the constructor, or such a Flask app may be passed intoinit_app()later, or the constructor may be called with explicitclient_idandclient_secretarguments. If none of these conditions is fulfilled and you try to use OAuth anyway, this exception is raised.
- class mwoauth2.MWOAuth2MWApi(host: str, client_id: str, client_secret: str, get_oauth_state: Callable[[P], dict[str, Any] | None], set_oauth_state: Callable[[Concatenate[dict[str, Any], P]], None], pop_oauth_state: Callable[[P], dict[str, Any]], get_access_token: Callable[[P], dict[str, Any] | None], set_access_token: Callable[[Concatenate[dict[str, Any], P]], None], pop_access_token: Callable[[P], dict[str, Any]], user_agent: str, api_path: str = '/w/api.php')[source]
Class managing OAuth 2 authentication against a MediaWiki wiki.
A single instance of this class can be used for multiple users, and is typically set up at tool initialization time. It contains the details of the client wiki, the OAuth credentials, and accessors for some kind of session store where the OAuth state is kept.
To start the authentication flow for a user, call
authorization_url()and send the user to the returned URL. Once they return, callfetch_token()with the request URL. Afterwards, you can usemwapi_session()to make authenticated requests. To check if the user is logged in or not, usehas_access_token().- Parameters:
host (str) – The host of the wiki, e.g.
https://en.wikipedia.org. Should include the protocol (scheme) and host name, but no path (useapi_pathif necessary). This is also used as the default formwapi_session().client_id (str) – The OAuth client ID, a string of 32 hexadecimal characters.
client_secret (str) – The OAuth client secret, a string of 40 hexadecimal characters. This should come from some kind of secret configuration source, e.g. a config file or environment variables.
get_oauth_state (Callable[P, dict[str, Any] | None]) – This, along with the next five parameters, represents the interface to the session store. This should be backed by some kind of user session, usually provided by your web framework, and is used to store the OAuth state (during login) and access token (subsequently). The type parameter
Pspecifies the parameters that are necessary to access the session store; these parameters are passed through from the other functions (fetch_token()etc.) to the session store accessors. Most of the time, this will be either a single “session” object (e.g. the Djangorequest.sessionor the FastAPI dependency-injectedsession) or no parameters at all (e.g. theflask.sessionproxy, seeMWOAuth2FlaskMWApi). This function should return the OAuth state if it has been set, otherwiseNone.set_oauth_state (Callable[Concatenate[dict[str, Any], P], None]) – Set the OAuth state to the given value.
pop_oauth_state (Callable[P, dict[str, Any]]) – Return and remove the OAuth state, or raise a
KeyErrorif it has not been set.get_access_token (Callable[P, dict[str, Any] | None]) – Get the access token if it has been set, otherwise
None.set_access_token (Callable[Concatenate[dict[str, Any], P], None]) – Set the access token to the given value.
pop_access_token (Callable[P, dict[str, Any]]) – Return and remove the access token, or raise a
KeyErrorif it has not been set. This is the only one of the six functions that is useful for a tool to call directly: calling this will log the user out.user_agent (str) – The User-Agent string that should be sent with all requests, in accordance with the User-Agent Policy. Toolforge tools can get a suitable string from
toolforge.set_user_agent(). This is also used inmwapi_session().api_path (str) – The path to the
api.phpendpoint, relative to thehost(see above). The default of/w/api.phpis suitable for all Wikimedia wikis and many other wikis as well. This is also used as the default formwapi_session().
- mwapi_session(host: str | None = None, api_path: str | None = None) Session | None[source]
Return an authenticated mwapi session (if the user is logged in).
If
has_access_token()isFalse, this function returnsNone. Otherwise, it returns anmwapi.Sessionwhich can be used to make authenticated requests.- Parameters:
host (str|None) – The host of the wiki, e.g.
https://en.wikipedia.org. Defaults to thehostparameter of the class, but can be changed, e.g. to authenticate againsthttps://meta.wikimedia.organd subsequently make requests tohttps://en.wikipedia.org,https://commons.wikimedia.orgetc., or more generally to target different wikis in a wiki farm with a central authentication system.api_path (str) – The path to the
api.phpendpoint, relative to thehost(see above). Defaults to theapi_pathparameter of the class.