本文整理汇总了Python中oic.oic.provider.Provider.id_token_as_signed_jwt方法的典型用法代码示例。如果您正苦于以下问题:Python Provider.id_token_as_signed_jwt方法的具体用法?Python Provider.id_token_as_signed_jwt怎么用?Python Provider.id_token_as_signed_jwt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oic.oic.provider.Provider
的用法示例。
在下文中一共展示了Provider.id_token_as_signed_jwt方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestProvider
# 需要导入模块: from oic.oic.provider import Provider [as 别名]
# 或者: from oic.oic.provider.Provider import id_token_as_signed_jwt [as 别名]
class TestProvider(object):
@pytest.fixture(autouse=True)
def create_provider(self):
self.provider = Provider("pyoicserv", SessionDB(SERVER_INFO["issuer"]),
CDB,
AUTHN_BROKER, USERINFO,
AUTHZ, verify_client, SYMKEY, urlmap=URLMAP,
keyjar=KEYJAR)
self.provider.baseurl = self.provider.name
self.cons = Consumer({}, CONSUMER_CONFIG, CLIENT_CONFIG,
server_info=SERVER_INFO, )
self.cons.behaviour = {
"request_object_signing_alg": DEF_SIGN_ALG["openid_request_object"]}
self.cons.keyjar[""] = KC_RSA
def test_authorization_endpoint(self):
bib = {"scope": ["openid"],
"state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
"redirect_uri": "http://localhost:8087/authz",
"response_type": ["code"],
"client_id": "a1b2c3",
"nonce": "Nonce"}
arq = AuthorizationRequest(**bib)
resp = self.provider.authorization_endpoint(request=arq.to_urlencoded())
parsed = parse_qs(urlparse(resp.message).query)
assert parsed["scope"] == ["openid"]
assert parsed["state"][0] == "id-6da9ca0cc23959f5f33e8becd9b08cae"
assert "code" in parsed
def test_authorization_endpoint_request(self):
bib = {"scope": ["openid"],
"state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
"redirect_uri": "http://localhost:8087/authz",
"response_type": ["code", "id_token"],
"client_id": "a1b2c3",
"nonce": "Nonce",
"prompt": ["none"]}
req = AuthorizationRequest(**bib)
# want to be someone else !
ic = {"sub": {"value": "userX"}}
_keys = self.provider.keyjar.get_signing_key(key_type="RSA")
req["request"] = make_openid_request(req, _keys, idtoken_claims=ic,
request_object_signing_alg="RS256")
with pytest.raises(FailedAuthentication):
self.provider.authorization_endpoint(request=req.to_urlencoded())
def test_authorization_endpoint_id_token(self):
bib = {"scope": ["openid"],
"state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
"redirect_uri": "http://localhost:8087/authz",
"response_type": ["code", "id_token"],
"client_id": "a1b2c3",
"nonce": "Nonce",
"prompt": ["none"]}
req = AuthorizationRequest(**bib)
areq = AuthorizationRequest(response_type="code",
client_id="client_1",
redirect_uri="http://example.com/authz",
scope=["openid"], state="state000")
sdb = self.provider.sdb
ae = AuthnEvent("userX", "salt")
sid = sdb.create_authz_session(ae, areq)
sdb.do_sub(sid, "client_salt")
_info = sdb[sid]
# All this is jut removed when the id_token is constructed
# The proper information comes from the session information
_user_info = IdToken(iss="https://foo.example.om", sub="foo",
aud=bib["client_id"],
exp=epoch_in_a_while(minutes=10),
acr="2", nonce=bib["nonce"])
idt = self.provider.id_token_as_signed_jwt(_info,
access_token="access_token",
user_info=_user_info)
req["id_token"] = idt
query_string = req.to_urlencoded()
# client_id not in id_token["aud"] so login required
resp = self.provider.authorization_endpoint(request=query_string,
cookie="FAIL")
parsed_resp = parse_qs(urlparse(resp.message).fragment)
assert parsed_resp["error"][0] == "login_required"
req["client_id"] = "client_1"
query_string = req.to_urlencoded()
# client_id is in id_token["aud"] so no login required
resp = self.provider.authorization_endpoint(request=query_string,
cookie="FAIL")
assert resp.message.startswith("http://localhost:8087/authz")
#.........这里部分代码省略.........
示例2: TestOICProvider
# 需要导入模块: from oic.oic.provider import Provider [as 别名]
# 或者: from oic.oic.provider.Provider import id_token_as_signed_jwt [as 别名]
class TestOICProvider(object):
def setup_class(self):
self.server = Provider("pyoicserv", SessionDB(SERVER_INFO["issuer"]), CDB,
AUTHN_BROKER, USERINFO,
AUTHZ, verify_client, SYMKEY, urlmap=URLMAP,
keyjar=KEYJAR)
self.cons = Consumer({}, CONSUMER_CONFIG, CLIENT_CONFIG,
server_info=SERVER_INFO, )
self.cons.behaviour = {"request_object_signing_alg": DEF_SIGN_ALG["openid_request_object"]}
self.cons.debug = True
self.cons.keyjar[""] = KC_RSA
def test_server_init(self):
assert self.server
assert self.server.authn_broker == AUTHN_BROKER
print self.server.urlmap
assert self.server.urlmap["client_1"] == ["https://example.com/authz"]
def test_server_authorization_endpoint(self):
bib = {"scope": ["openid"],
"state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
"redirect_uri": "http://localhost:8087/authz",
"response_type": ["code"],
"client_id": "a1b2c3",
"nonce": "Nonce"}
arq = AuthorizationRequest(**bib)
resp = self.server.authorization_endpoint(request=arq.to_urlencoded())
print resp.message
assert resp.message
def test_server_authorization_endpoint_request(self):
bib = {"scope": ["openid"],
"state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
"redirect_uri": "http://localhost:8087/authz",
"response_type": ["code", "id_token"],
"client_id": "a1b2c3",
"nonce": "Nonce",
"prompt": ["none"]}
req = AuthorizationRequest(**bib)
# want to be someone else !
ic = {"sub": {"value": "userX"}}
_keys = self.server.keyjar.get_signing_key(key_type="RSA")
req["request"] = make_openid_request(req, _keys, idtoken_claims=ic,
request_object_signing_alg="RS256")
try:
resp = self.server.authorization_endpoint(request=req.to_urlencoded())
except FailedAuthentication:
pass
else:
assert False
def test_server_authorization_endpoint_id_token(self):
bib = {"scope": ["openid"],
"state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
"redirect_uri": "http://localhost:8087/authz",
"response_type": ["code", "id_token"],
"client_id": "a1b2c3",
"nonce": "Nonce",
"prompt": ["none"]}
req = AuthorizationRequest(**bib)
areq = AuthorizationRequest(response_type="code",
client_id="client_1",
redirect_uri="http://example.com/authz",
scope=["openid"], state="state000")
sdb = self.server.sdb
ae = AuthnEvent("userX")
sid = sdb.create_authz_session(ae, areq)
sdb.do_sub(sid)
_info = sdb[sid]
# All this is jut removed when the id_token is constructed
# The proper information comes from the session information
_user_info = IdToken(iss="https://foo.example.om", sub="foo",
aud=bib["client_id"], exp=epoch_in_a_while(minutes=10),
acr="2", nonce=bib["nonce"])
print self.server.keyjar.issuer_keys
print _user_info.to_dict()
idt = self.server.id_token_as_signed_jwt(_info, access_token="access_token",
user_info=_user_info)
req["id_token"] = idt
query_string = req.to_urlencoded()
# client_id not in id_token["aud"] so login required
resp = self.server.authorization_endpoint(request=query_string, cookie="FAIL")
print resp
assert "error=login_required" in resp.message
req["client_id"] = "client_1"
query_string = req.to_urlencoded()
#.........这里部分代码省略.........
示例3: InAcademiaOpenIDConnectFrontend
# 需要导入模块: from oic.oic.provider import Provider [as 别名]
# 或者: from oic.oic.provider.Provider import id_token_as_signed_jwt [as 别名]
class InAcademiaOpenIDConnectFrontend(object):
def __init__(self, base_url, client_metadata_func):
# Read OP configuration from file
with open("conf/op_config.json", "r") as f:
op_capabilities = json.load(f)
for key, value in op_capabilities.iteritems():
if isinstance(value, basestring):
op_capabilities[key] = value.format(base=base_url) # replace placeholder with the actual base name
self.OP = Provider(base_url, {}, client_metadata_func, None, None, None, None, None,
capabilities=op_capabilities)
self.OP.baseurl = op_capabilities["issuer"]
# Setup up keys for signing and encrypting
self.OP.keyjar = KeyJar()
kb = keybundle_from_local_file("inAcademia", "RSA", ["sig", "enc"])
self.OP.keyjar.add_kb("", kb)
try:
file_name = "static/jwks.json"
dump_jwks([kb], file_name)
self.OP.jwks_uri.append("{}/{}".format(base_url, file_name))
except Exception as e:
logger.exception("Signing and encryption keys could not be written to jwks.json.")
raise
def id_token(self, released_claims, idp_entity_id, transaction_id, transaction_session):
"""Make a JWT encoded id token and pass it to the redirect URI.
:param released_claims: dictionary containing the following
user_id: identifier for the user (as delivered by the IdP, dependent on whether transient or persistent
id was requested)
auth_time: time of the authentication reported from the IdP
idp_entity_id: entity id of the selected IdP
:param transaction_id:
:return: raises cherrypy.HTTPRedirect.
"""
identifier = released_claims["Identifier"]
auth_time = released_claims["Authentication time"]
# have to convert text representation into seconds since epoch
_time = time.mktime(str_to_time(auth_time))
# construct the OIDC response
transaction_session["sub"] = identifier
extra_claims = {k.lower(): released_claims[k] for k in ["Country", "Domain"] if k in released_claims}
_jwt = self.OP.id_token_as_signed_jwt(transaction_session, loa="", auth_time=_time, exp={"minutes": 30},
extra_claims=extra_claims)
_elapsed_transaction_time = get_timestamp() - transaction_session["start_time"]
log_transaction_complete(logger, cherrypy.request, transaction_id,
transaction_session["client_id"],
idp_entity_id, _time, _elapsed_transaction_time,
extra_claims, _jwt)
try:
_state = transaction_session["state"]
except KeyError:
_state = None
authzresp = AuthorizationResponse(state=_state, id_token=_jwt)
if "redirect_uri" in transaction_session:
_ruri = transaction_session["redirect_uri"]
else:
_error_msg = _("We could not complete your validation because an error occurred while "
"handling your request. Please return to the service which initiated the "
"validation request and try again.")
try:
cinfo = self.OP.cdb[transaction_session["client_id"]]
_ruri = cinfo["redirect_uris"][0]
except KeyError as e:
abort_with_enduser_error(transaction_id, transaction_session["client_id"], cherrypy.request, logger,
_error_msg,
"Unknown RP client id '{}': '{}'.".format(transaction_session["client_id"],
str(e)))
location = authzresp.request(_ruri, True)
logger.debug("Redirected to: '{}' ({})".format(location, type(location)))
raise cherrypy.HTTPRedirect(location)
def _verify_scope(self, scope, client_id):
"""Verifies the scope received from the RP.
Only one affiliation request is allowed to be specified, and if 'persistent' is specified 'transient'
is not allowed. In addition, the requested scope is verified against the clients permissions.
:param scope: requested scope from the RP
:return: True if the values in scope are valid, otherwise False.
"""
# Malformed scope requesting validation of more than one affiliation type
requested_affiliations = [a for a in AFFILIATIONS if a in scope]
if len(requested_affiliations) != 1:
return False
# Malformed scope containing both 'persistent' and 'transient'
if PERSISTENT_NAMEID in scope and TRANSIENT_NAMEID in scope:
return False
#.........这里部分代码省略.........