本文整理匯總了Python中jwkest.jws.JWS屬性的典型用法代碼示例。如果您正苦於以下問題:Python jws.JWS屬性的具體用法?Python jws.JWS怎麽用?Python jws.JWS使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類jwkest.jws
的用法示例。
在下文中一共展示了jws.JWS屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_keyset
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def _get_keyset(self, kid=None):
"""
Get keyset from available sources.
If using a RSA key, forcefully set the key id
to match the one from the JWT token.
"""
keyset = []
if self.keyset_url:
# TODO: Improve support for keyset handling, handle errors.
keyset.extend(load_jwks_from_url(self.keyset_url))
if self.public_key and kid:
# Fill in key id of stored key.
# This is needed because if the JWS is signed with a
# key with a kid, pyjwkest doesn't match them with
# keys without kid (kid=None) and fails verification
self.public_key.kid = kid
# Add to keyset
keyset.append(self.public_key)
return keyset
示例2: encode_and_sign
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def encode_and_sign(self, message, expiration=None):
"""
Encode and sign JSON with RSA key
"""
if not self.key:
raise exceptions.RsaKeyNotSet()
_message = copy.deepcopy(message)
# Set iat and exp if expiration is set
if expiration:
_message.update({
"iat": int(round(time.time())),
"exp": int(round(time.time()) + expiration),
})
# The class instance that sets up the signing operation
# An RS 256 key is required for LTI 1.3
_jws = JWS(_message, alg="RS256", cty="JWT")
# Encode and sign LTI message
return _jws.sign_compact([self.key])
示例3: _consent_registration
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def _consent_registration(self, consent_args):
"""
Register a request at the consent service
:type consent_args: dict
:rtype: str
:param consent_args: All necessary parameters for the consent request
:return: Ticket received from the consent service
"""
jws = JWS(json.dumps(consent_args), alg=self.signing_key.alg).sign_compact([self.signing_key])
request = "{}/creq/{}".format(self.api_url, jws)
res = requests.get(request)
if res.status_code != 200:
raise UnexpectedResponseError("Consent service error: %s %s", res.status_code, res.text)
return res.text
示例4: test_existing_account_linking_with_known_known_uuid
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def test_existing_account_linking_with_known_known_uuid(self, account_linking_config, internal_response, context):
uuid = "uuid"
data = {
"idp": internal_response.auth_info.issuer,
"id": internal_response.subject_id,
"redirect_endpoint": self.account_linking.base_url + "/account_linking/handle_account_linking"
}
key = RSAKey(key=rsa_load(account_linking_config["sign_key"]), use="sig", alg="RS256")
jws = JWS(json.dumps(data), alg=key.alg).sign_compact([key])
responses.add(
responses.GET,
"%s/get_id?jwt=%s" % (account_linking_config["api_url"], jws),
status=200,
body=uuid,
content_type="text/html",
match_querystring=True
)
self.account_linking.process(context, internal_response)
assert internal_response.subject_id == uuid
示例5: test_authorization_code
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def test_authorization_code(self):
"""
We MUST validate the signature of the ID Token according to JWS
using the algorithm specified in the alg Header Parameter of
the JOSE Header.
"""
SIGKEYS = self._get_keys()
code = self._create_code()
post_data = self._auth_code_post_data(code=code.code)
response = self._post_request(post_data)
response_dic = json.loads(response.content.decode('utf-8'))
id_token = JWS().verify_compact(response_dic['id_token'].encode('utf-8'), SIGKEYS)
token = Token.objects.get(user=self.user)
self.assertEqual(response_dic['access_token'], token.access_token)
self.assertEqual(response_dic['refresh_token'], token.refresh_token)
self.assertEqual(response_dic['token_type'], 'bearer')
self.assertEqual(response_dic['expires_in'], 720)
self.assertEqual(id_token['sub'], str(self.user.id))
self.assertEqual(id_token['aud'], self.client.client_id)
示例6: test_idtoken_sign_validation
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def test_idtoken_sign_validation(self):
"""
We MUST validate the signature of the ID Token according to JWS
using the algorithm specified in the alg Header Parameter of
the JOSE Header.
"""
SIGKEYS = self._get_keys()
RSAKEYS = [k for k in SIGKEYS if k.kty == 'RSA']
code = self._create_code()
post_data = self._auth_code_post_data(code=code.code)
response = self._post_request(post_data)
response_dic = json.loads(response.content.decode('utf-8'))
JWS().verify_compact(response_dic['id_token'].encode('utf-8'), RSAKEYS)
示例7: create_jwt
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def create_jwt(self, user):
"""
Creates a signed (JWS) ID token.
Returns:
str: JWS
"""
key = SYMKey(key=self.site.siteconfiguration.oauth_settings['SOCIAL_AUTH_EDX_OAUTH2_SECRET'])
now = datetime.datetime.utcnow()
expiration_datetime = now + datetime.timedelta(seconds=3600)
issue_datetime = now
payload = {
'iss': self.site.siteconfiguration.lms_url_root,
'administrator': False,
'iat': timegm(issue_datetime.utctimetuple()),
'sub': str(uuid.uuid4()),
'preferred_username': user.username,
'aud': self.site.siteconfiguration.oauth_settings['SOCIAL_AUTH_EDX_OAUTH2_KEY'],
'exp': timegm(expiration_datetime.utctimetuple()),
}
access_token = JWS(payload, jwk=key, alg='HS512').sign_compact()
return access_token
示例8: generate_jws
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def generate_jws(self, **kwargs):
return JWS(self.generate_jws_dict(**kwargs), jwk=self.key, alg='RS256').sign_compact()
示例9: test_cannot_validate_an_id_token_with_multiple_audiences_but_no_authorized_party
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def test_cannot_validate_an_id_token_with_multiple_audiences_but_no_authorized_party(self):
jws_dict = self.generate_jws_dict()
jws_dict['aud'] = [oidc_rp_settings.CLIENT_ID, '2']
jws_dict.pop('azp')
jws = JWS(jws_dict, jwk=self.key, alg='RS256').sign_compact()
with pytest.raises(SuspiciousOperation):
validate_and_return_id_token(jws)
示例10: _get_jwks_keys
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def _get_jwks_keys(shared_key):
""" Returns JWKS keys used to decrypt id_token values. """
# The OpenID Connect Provider (OP) uses RSA keys to sign/enrypt ID tokens and generate public
# keys allowing to decrypt them. These public keys are exposed through the 'jwks_uri' and should
# be used to decrypt the JWS - JSON Web Signature.
jwks_keys = KEYS()
jwks_keys.load_from_url(oidc_rp_settings.PROVIDER_JWKS_ENDPOINT)
# Adds the shared key (which can correspond to the client_secret) as an oct key so it can be
# used for HMAC signatures.
jwks_keys.add({'key': smart_bytes(shared_key), 'kty': 'oct'})
return jwks_keys
示例11: validate_and_decode
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def validate_and_decode(self, token):
"""
Check if a message sent by the tool is valid.
From https://www.imsglobal.org/spec/security/v1p0/#using-oauth-2-0-client-credentials-grant:
The authorization server decodes the JWT and MUST validate the values for the
iss, sub, exp, aud and jti claims.
"""
try:
# Get KID from JWT header
jwt = JWT().unpack(token)
# Verify message signature
message = JWS().verify_compact(
token,
keys=self._get_keyset(
jwt.headers.get('kid')
)
)
# If message is valid, check expiration from JWT
if 'exp' in message and message['exp'] < time.time():
raise exceptions.TokenSignatureExpired()
# TODO: Validate other JWT claims
# Else returns decoded message
return message
except NoSuitableSigningKeys:
raise exceptions.NoSuitableKeys()
except BadSyntax:
raise exceptions.MalformedJwtToken()
except WrongNumberOfParts:
raise exceptions.MalformedJwtToken()
示例12: _decode_token
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def _decode_token(self, token):
"""
Checks for a valid signarute and decodes JWT signed LTI message
This also tests the public keyset function.
"""
public_keyset = self.lti_consumer.get_public_keyset()
key_set = load_jwks(json.dumps(public_keyset))
return JWS().verify_compact(token, keys=key_set)
示例13: _decode_token
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def _decode_token(self, token):
"""
Checks for a valid signarute and decodes JWT signed LTI message
This also touches the public keyset method.
"""
public_keyset = self.key_handler.get_public_jwk()
key_set = load_jwks(json.dumps(public_keyset))
return JWS().verify_compact(token, keys=key_set)
示例14: get_jwt_claims
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def get_jwt_claims(self, auth_token):
"""Decodes the auth_token into JWT claims represented as a JSON object.
This method first tries to look up the cache and returns the result
immediately in case of a cache hit. When cache misses, the method tries to
decode the given auth token, verify its signature, and check the existence
of required JWT claims. When successful, the decoded JWT claims are loaded
into the cache and then returned.
Args:
auth_token: the auth token to be decoded.
Returns:
The decoded JWT claims.
Raises:
UnauthenticatedException: When the signature verification fails, or when
required claims are missing.
"""
def _decode_and_verify():
jwt_claims = jwt.JWT().unpack(auth_token).payload()
_verify_required_claims_exist(jwt_claims)
issuer = jwt_claims[u"iss"]
keys = self._jwks_supplier.supply(issuer)
try:
return jws.JWS().verify_compact(auth_token, keys)
except (jwkest.BadSignature, jws.NoSuitableSigningKeys,
jws.SignerAlgError) as exception:
raise suppliers.UnauthenticatedException(u"Signature verification failed",
exception)
return self._cache.get_or_create(auth_token, _decode_and_verify)
示例15: generate_auth_token
# 需要導入模塊: from jwkest import jws [as 別名]
# 或者: from jwkest.jws import JWS [as 別名]
def generate_auth_token(payload, keys, alg=u"ES256", kid=None):
json_web_signature = jws.JWS(json.dumps(payload), alg=alg, kid=kid)
return json_web_signature.sign_compact(keys=keys)