OAuth2IdProvider
IdProvider based on OAuth2 protocol
- class DIRAC.Resources.IdProvider.OAuth2IdProvider.OAuth2IdProvider(**kwargs)
Bases:
DIRAC.Resources.IdProvider.IdProvider.IdProvider
,DIRAC.Resources.IdProvider.OAuth2IdProvider.OAuth2Session
Base class to describe the configuration of the OAuth2 client of the corresponding provider.
- DEFAULT_METADATA = {}
- EXTRA_AUTHORIZE_PARAMS = ('response_mode', 'nonce', 'prompt', 'login_hint')
- JWKS_REFRESH_RATE = 86400
- METADATA_REFRESH_RATE = 86400
- SESSION_REQUEST_PARAMS = ('allow_redirects', 'timeout', 'cookies', 'files', 'proxies', 'hooks', 'stream', 'verify', 'cert', 'json')
- __init__(**kwargs)
Initialization
- auth
Default Authentication tuple or object to attach to
Request
.
- cert
SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.
- client_auth(auth_method)
- client_auth_class
alias of
authlib.integrations.requests_client.oauth2_session.OAuth2ClientAuth
- close()
Closes all adapters and as such the session
- cookies
A CookieJar containing all currently outstanding cookies set on this session. By default it is a
RequestsCookieJar
, but may be any othercookielib.CookieJar
compatible object.
- create_authorization_url(url, state=None, code_verifier=None, **kwargs)
Generate an authorization URL and state.
- Parameters
url – Authorization endpoint url, must be HTTPS.
state – An optional state string for CSRF protection. If not given it will be generated for you.
code_verifier – An optional code_verifier for code challenge.
kwargs – Extra parameters to include.
- Returns
authorization_url, state
- delete(url, **kwargs)
Sends a DELETE request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- deviceAuthorization(group=None)
Authorizaion through DeviceCode flow
- ensure_active_token(token)
- exchangeToken(group=None, scope=None)
Get new tokens for group scope
- exchange_token(url, subject_token=None, subject_token_type=None, body='', refresh_token=None, access_token=None, auth=None, headers=None, **kwargs)
Exchange a new access token
- Parameters
url – Exchange Token endpoint, must be HTTPS.
subject_token (str) – subject_token
subject_token_type (str) – token type https://tools.ietf.org/html/rfc8693#section-3
body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
refresh_token (str) – refresh token
access_token (str) – access token
auth – An auth tuple or method as accepted by requests.
headers – Dict to default request headers with.
- Returns
A
OAuth2Token
object (a dict too).
- fetchToken(**kwargs)
Fetch token
- Returns
dict
- fetch_access_token(url=None, **kwargs)
Alias for fetch_token.
- fetch_metadata(**kwargs)
Fetch metada
- fetch_token(url=None, body='', method='POST', headers=None, auth=None, grant_type=None, state=None, **kwargs)
Generic method for fetching an access token from the token endpoint.
- Parameters
url – Access Token endpoint URL, if not configured,
authorization_response
is used to extract token from its fragment (implicit way).body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
method – The HTTP method used to make the request. Defaults to POST, but may also be GET. Other methods should be added as needed.
headers – Dict to default request headers with.
auth – An auth tuple or method as accepted by requests.
grant_type – Use specified grant_type to fetch token
- Returns
A
OAuth2Token
object (a dict too).
- get(url, **kwargs)
Sends a GET request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- getUserProfile()
Get user profile
- Returns
S_OK()/S_ERROR()
- get_adapter(url)
Returns the appropriate connection adapter for the given URL.
- Return type
requests.adapters.BaseAdapter
- get_redirect_target(resp)
Receives a Response. Returns a redirect URI or
None
- static handle_error(error_type, error_description)
- head(url, **kwargs)
Sends a HEAD request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- headers
A case-insensitive dictionary of headers to be sent on each
Request
sent from thisSession
.
- hooks
Event-handling hooks.
- introspect_token(url, token=None, token_type_hint=None, body=None, auth=None, headers=None, **kwargs)
Implementation of OAuth 2.0 Token Introspection defined via RFC7662.
- Parameters
url – Introspection Endpoint, must be HTTPS.
token – The token to be introspected.
token_type_hint – The type of the token that to be revoked. It can be “access_token” or “refresh_token”.
body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
auth – An auth tuple or method as accepted by requests.
headers – Dict to default request headers with.
- Returns
Introspection Response
- max_redirects
Maximum number of redirects allowed. If the request exceeds this limit, a
TooManyRedirects
exception is raised. This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is 30.
- merge_environment_settings(url, proxies, stream, verify, cert)
Check the environment and merge it with some settings.
- Return type
- mount(prefix, adapter)
Registers a connection adapter to a prefix.
Adapters are sorted in descending order by prefix length.
- options(url, **kwargs)
Sends a OPTIONS request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- params
Dictionary of querystring data to attach to each
Request
. The dictionary values may be lists for representing multivalued query parameters.
- parseAuthResponse(response, session=None)
Make user info dict:
- parseBasic(claimDict)
Parse basic claims
- Parameters
claimDict (dict) – claims
- Returns
S_OK(dict)/S_ERROR()
- parseEduperson(claimDict)
Parse eduperson claims
- Returns
dict
- parse_response_token(token)
- patch(url, data=None, **kwargs)
Sends a PATCH request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request
.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- post(url, data=None, json=None, **kwargs)
Sends a POST request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request
.json – (optional) json to send in the body of the
Request
.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- prepare_request(request)
Constructs a
PreparedRequest
for transmission and returns it. ThePreparedRequest
has settings merged from theRequest
instance and those of theSession
.- Parameters
request –
Request
instance to prepare with this session’s settings.- Return type
requests.PreparedRequest
- proxies
Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each
Request
.
- put(url, data=None, **kwargs)
Sends a PUT request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request
.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- rebuild_auth(prepared_request, response)
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
- rebuild_method(prepared_request, response)
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
- rebuild_proxies(prepared_request, proxies)
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).
This method also replaces the Proxy-Authorization header where necessary.
- Return type
- refreshToken(**kwargs)
Refresh token
- refresh_token(url, refresh_token=None, body='', auth=None, headers=None, **kwargs)
Fetch a new access token using a refresh token.
- Parameters
url – Refresh Token endpoint, must be HTTPS.
refresh_token – The refresh_token to use.
body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
auth – An auth tuple or method as accepted by requests.
headers – Dict to default request headers with.
- Returns
A
OAuth2Token
object (a dict too).
- register_client_auth_method(auth)
Extend client authenticate for token endpoint.
- Parameters
auth – an instance to sign the request
- register_compliance_hook(hook_type, hook)
Register a hook for request/response tweaking.
Available hooks are:
access_token_response: invoked before token parsing.
refresh_token_request: invoked before refreshing token.
refresh_token_response: invoked before refresh token parsing.
protected_request: invoked before making a request.
revoke_token_request: invoked before revoking a token.
introspect_token_request: invoked before introspecting a token.
- request(method, url, withhold_token=False, auth=None, **kwargs)
Send request with auto refresh token feature (if available).
- researchGroup(payload=None, token=None)
Research group
- resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)
Receives a Response. Returns a generator of Responses or Requests.
- revokeToken(token=None, token_type_hint='refresh_token')
Revoke token
- revoke_token(url, token=None, token_type_hint=None, body=None, auth=None, headers=None, **kwargs)
Revoke token method defined via RFC7009.
- Parameters
url – Revoke Token endpoint, must be HTTPS.
token – The token to be revoked.
token_type_hint – The type of the token that to be revoked. It can be “access_token” or “refresh_token”.
body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
auth – An auth tuple or method as accepted by requests.
headers – Dict to default request headers with.
- Returns
Revocation Response
- send(request, **kwargs)
Send a given PreparedRequest.
- Return type
requests.Response
- setParameters(parameters)
Set parameters
- Parameters
parameters (dict) – parameters of the identity Provider
- should_strip_auth(old_url, new_url)
Decide whether Authorization header should be removed when redirecting
- stream
Stream response content default.
- submitDeviceCodeAuthorizationFlow(group=None)
Submit authorization flow
- Returns
S_OK(dict)/S_ERROR() – dictionary with device code flow response
- submitNewSession(pkce=True)
Submit new authorization session
- Parameters
pkce (bool) – use PKCE
- Returns
S_OK(str)/S_ERROR()
- property token
- token_auth_class
alias of
authlib.integrations.requests_client.oauth2_session.OAuth2Auth
- token_from_fragment(authorization_response, state=None)
- trust_env
Trust environment settings for proxy configuration, default authentication and similar.
- updateJWKs(**kwargs)
Update JWKs
- verify
SSL Verification default. Defaults to True, requiring requests to verify the TLS certificate at the remote end. If verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to False for testing.
- verifyToken(accessToken=None, jwks=None)
Verify access token
- waitFinalStatusOfDeviceCodeAuthorizationFlow(deviceCode, interval=5, timeout=300)
Submit waiting loop process, that will monitor current authorization session status
- class DIRAC.Resources.IdProvider.OAuth2IdProvider.OAuth2Session(client_id=None, client_secret=None, token_endpoint_auth_method=None, revocation_endpoint_auth_method=None, scope=None, state=None, redirect_uri=None, token=None, token_placement='header', update_token=None, **kwargs)
Bases:
authlib.integrations.requests_client.oauth2_session.OAuth2Session
Authlib does not yet know about the token exchange flow: https://github.com/lepture/authlib/tree/master/authlib/oauth2/rfc8693
so we will add auxiliary methods to implement this flow.
- EXTRA_AUTHORIZE_PARAMS = ('response_mode', 'nonce', 'prompt', 'login_hint')
- SESSION_REQUEST_PARAMS = ('allow_redirects', 'timeout', 'cookies', 'files', 'proxies', 'hooks', 'stream', 'verify', 'cert', 'json')
- __init__(client_id=None, client_secret=None, token_endpoint_auth_method=None, revocation_endpoint_auth_method=None, scope=None, state=None, redirect_uri=None, token=None, token_placement='header', update_token=None, **kwargs)
- auth
Default Authentication tuple or object to attach to
Request
.
- cert
SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.
- client_auth(auth_method)
- client_auth_class
alias of
authlib.integrations.requests_client.oauth2_session.OAuth2ClientAuth
- close()
Closes all adapters and as such the session
- cookies
A CookieJar containing all currently outstanding cookies set on this session. By default it is a
RequestsCookieJar
, but may be any othercookielib.CookieJar
compatible object.
- create_authorization_url(url, state=None, code_verifier=None, **kwargs)
Generate an authorization URL and state.
- Parameters
url – Authorization endpoint url, must be HTTPS.
state – An optional state string for CSRF protection. If not given it will be generated for you.
code_verifier – An optional code_verifier for code challenge.
kwargs – Extra parameters to include.
- Returns
authorization_url, state
- delete(url, **kwargs)
Sends a DELETE request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- ensure_active_token(token)
- exchange_token(url, subject_token=None, subject_token_type=None, body='', refresh_token=None, access_token=None, auth=None, headers=None, **kwargs)
Exchange a new access token
- Parameters
url – Exchange Token endpoint, must be HTTPS.
subject_token (str) – subject_token
subject_token_type (str) – token type https://tools.ietf.org/html/rfc8693#section-3
body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
refresh_token (str) – refresh token
access_token (str) – access token
auth – An auth tuple or method as accepted by requests.
headers – Dict to default request headers with.
- Returns
A
OAuth2Token
object (a dict too).
- fetch_access_token(url=None, **kwargs)
Alias for fetch_token.
- fetch_token(url=None, body='', method='POST', headers=None, auth=None, grant_type=None, state=None, **kwargs)
Generic method for fetching an access token from the token endpoint.
- Parameters
url – Access Token endpoint URL, if not configured,
authorization_response
is used to extract token from its fragment (implicit way).body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
method – The HTTP method used to make the request. Defaults to POST, but may also be GET. Other methods should be added as needed.
headers – Dict to default request headers with.
auth – An auth tuple or method as accepted by requests.
grant_type – Use specified grant_type to fetch token
- Returns
A
OAuth2Token
object (a dict too).
- get(url, **kwargs)
Sends a GET request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- get_adapter(url)
Returns the appropriate connection adapter for the given URL.
- Return type
requests.adapters.BaseAdapter
- get_redirect_target(resp)
Receives a Response. Returns a redirect URI or
None
- static handle_error(error_type, error_description)
- head(url, **kwargs)
Sends a HEAD request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- headers
A case-insensitive dictionary of headers to be sent on each
Request
sent from thisSession
.
- hooks
Event-handling hooks.
- introspect_token(url, token=None, token_type_hint=None, body=None, auth=None, headers=None, **kwargs)
Implementation of OAuth 2.0 Token Introspection defined via RFC7662.
- Parameters
url – Introspection Endpoint, must be HTTPS.
token – The token to be introspected.
token_type_hint – The type of the token that to be revoked. It can be “access_token” or “refresh_token”.
body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
auth – An auth tuple or method as accepted by requests.
headers – Dict to default request headers with.
- Returns
Introspection Response
- max_redirects
Maximum number of redirects allowed. If the request exceeds this limit, a
TooManyRedirects
exception is raised. This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is 30.
- merge_environment_settings(url, proxies, stream, verify, cert)
Check the environment and merge it with some settings.
- Return type
- mount(prefix, adapter)
Registers a connection adapter to a prefix.
Adapters are sorted in descending order by prefix length.
- options(url, **kwargs)
Sends a OPTIONS request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- params
Dictionary of querystring data to attach to each
Request
. The dictionary values may be lists for representing multivalued query parameters.
- parse_response_token(token)
- patch(url, data=None, **kwargs)
Sends a PATCH request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request
.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- post(url, data=None, json=None, **kwargs)
Sends a POST request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request
.json – (optional) json to send in the body of the
Request
.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- prepare_request(request)
Constructs a
PreparedRequest
for transmission and returns it. ThePreparedRequest
has settings merged from theRequest
instance and those of theSession
.- Parameters
request –
Request
instance to prepare with this session’s settings.- Return type
requests.PreparedRequest
- proxies
Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each
Request
.
- put(url, data=None, **kwargs)
Sends a PUT request. Returns
Response
object.- Parameters
url – URL for the new
Request
object.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request
.**kwargs – Optional arguments that
request
takes.
- Return type
requests.Response
- rebuild_auth(prepared_request, response)
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
- rebuild_method(prepared_request, response)
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
- rebuild_proxies(prepared_request, proxies)
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).
This method also replaces the Proxy-Authorization header where necessary.
- Return type
- refresh_token(url, refresh_token=None, body='', auth=None, headers=None, **kwargs)
Fetch a new access token using a refresh token.
- Parameters
url – Refresh Token endpoint, must be HTTPS.
refresh_token – The refresh_token to use.
body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
auth – An auth tuple or method as accepted by requests.
headers – Dict to default request headers with.
- Returns
A
OAuth2Token
object (a dict too).
- register_client_auth_method(auth)
Extend client authenticate for token endpoint.
- Parameters
auth – an instance to sign the request
- register_compliance_hook(hook_type, hook)
Register a hook for request/response tweaking.
Available hooks are:
access_token_response: invoked before token parsing.
refresh_token_request: invoked before refreshing token.
refresh_token_response: invoked before refresh token parsing.
protected_request: invoked before making a request.
revoke_token_request: invoked before revoking a token.
introspect_token_request: invoked before introspecting a token.
- request(method, url, withhold_token=False, auth=None, **kwargs)
Send request with auto refresh token feature (if available).
- resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)
Receives a Response. Returns a generator of Responses or Requests.
- revoke_token(url, token=None, token_type_hint=None, body=None, auth=None, headers=None, **kwargs)
Revoke token method defined via RFC7009.
- Parameters
url – Revoke Token endpoint, must be HTTPS.
token – The token to be revoked.
token_type_hint – The type of the token that to be revoked. It can be “access_token” or “refresh_token”.
body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
auth – An auth tuple or method as accepted by requests.
headers – Dict to default request headers with.
- Returns
Revocation Response
- send(request, **kwargs)
Send a given PreparedRequest.
- Return type
requests.Response
- should_strip_auth(old_url, new_url)
Decide whether Authorization header should be removed when redirecting
- stream
Stream response content default.
- property token
- token_auth_class
alias of
authlib.integrations.requests_client.oauth2_session.OAuth2Auth
- token_from_fragment(authorization_response, state=None)
- trust_env
Trust environment settings for proxy configuration, default authentication and similar.
- verify
SSL Verification default. Defaults to True, requiring requests to verify the TLS certificate at the remote end. If verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to False for testing.