Пример #1
0
def token_validate(jwt):
    # create jwt instance and get all daily public keys
    jwt_object = JWT()
    pub_keys = get_microsoft_pub_keys()

    # get kid from header in jwt
    real_kid = get_kid(jwt)

    # default username and dec_msg
    username = None
    dec_msg = ValidationMsg.NO_KEY_FOUND

    # check every public key looking for one used for signing this jwt
    for p_key in pub_keys.get('keys'):
        if p_key.get('kid') == real_kid:
            # assemble jwk
            jwk_dict = {
                    'kty': p_key['kty'],
                    'e': p_key['e'],
                    'n': p_key['n']
                }
            jwk = jwk_from_dict(jwk_dict)

            try:
                # perform decoding of the jwt while verifying integrity, authenticity and expiration
                dec_payload = jwt_object.decode(jwt, jwk, do_time_check=True)
                dec_msg = ValidationMsg.SUCCESS
                username = dec_payload['preferred_username']
            except:
                # an error occurred while validating the jwt
                dec_msg = ValidationMsg.FAILED

    return username, dec_msg
Пример #2
0
 def get_keys(self):
     if self.last_time and self.keys and self.last_time + self.update_key_time >= datetime.utcnow(
     ):
         return self.keys
     self.keys = []
     self.last_time = datetime.utcnow()
     for provider, provider_info in self.providers.items():
         try:
             p_info = requests.get(
                 "{}/.well-known/openid-configuration/".format(
                     provider_info['url']),
                 verify=provider_info['cert'])
             if p_info.ok:
                 p_info = p_info.json()
                 key_url = p_info["jwks_uri"]
                 key_list = requests.get(
                     key_url, verify=provider_info['cert']).json()
                 for key in key_list['keys']:
                     self.keys.append({
                         "key": jwk_from_dict(key),
                         "iss": provider_info['url'],
                         "kid": key['kid']
                     })
             else:
                 pass
         except RequestException as e:
             pass
         except TypeError as e:
             pass
     if not self.keys:
         raise ProviderNotFoundException("No provider found")
     return self.keys
Пример #3
0
def jwk_from(file_read: bytes, read_as: str = 'json') -> AbstractJWKBase:
    # For PEM read
    if read_as == 'pem':
        return jwk_from_pem(file_read)

    else:
        return jwk_from_dict(json.loads(str(file_read)))
Пример #4
0
def get_keys():
    keys = base64.b64decode(os.environ['OKTA_KEYS'])
    jwks = json.loads(keys)
    for jwk in jwks['keys']:
        kid = jwk['kid']
        public_key = jwk_from_dict(jwk)
        public_keys[kid] = public_key
Пример #5
0
def jwk():
    """
    From the Amazon signin page, attempting to get jwk working
    """
    signing_key = jwk_from_dict({
        'kty': 'RSA',
        'e': 'AQAB',
        'n': 'gXXZV1VqZ6k_uQtyJNJy5q-qvKdqrXJNgKUO1aYc1UPBVqlhCP0GPxf-0GSo-LEtArgcbF8-j6_vSLSqztYxxF8og--rB8zAyZ8DXZaugX-UiJDQnoJL_HtXKuwIm9U7oEPoeD6H4ZDcfbsPj77xVn7UA2-a90N4aZqMC8EIfXIy1tqSbSPnxPOaiEmy8xGtG-L3RdCyc7TL0Swd_f0_DjRT6ip91IBlCmquoa-xJgZ9e44PVH4AwdyssiV4ZLEZ5yFcE0zcRb_62kx_TQptidbJ4nHocFVjmUW9YsrAWeKrBmOGZEjO4vbATYs1Yf4vgcH7Ix61EPR5sbDP4SlBWQ',
        'd': '...'})

    pprint.pprint(signing_key)
Пример #6
0
 def validate_access_token(self):
     error = ""
     instance = JWT()
     for key in self._openid_conf["signing_keys"]:
         try:
             # Validate token and return claims
             verifying_key = jwk_from_dict(key)
             return instance.decode(
                 self.token["access_token"], verifying_key, do_time_check=True
             )
         except JWTDecodeError as exc:
             error = str(exc)
     raise OAuth2Error(error)
def get_keys():
    data = json.loads(keys_json)
    keys = []
    for k in data['keys']:
        jwk = jwk_from_dict(k)
        print(
            jwk.keyobj.public_bytes(Encoding.PEM,
                                    PublicFormat.SubjectPublicKeyInfo))
        keys.append(jwk)

    print("Number of imported keys :" + str(len(keys)))
    print("Keys: {}".format(keys))
    return keys
Пример #8
0
def _get_keys_from_dex():
    resp = requests.get(urljoin(DEX_URL, "/dex/keys"), params=None)
    data = json.loads(resp.text)
    keys = []
    for k in data['keys']:
        jwk = jwk_from_dict(k)
        keys.append(jwk)
        logger.info("PEM {}".format(jwk.keyobj.
                                    public_bytes(Encoding.PEM,
                                                 PublicFormat.SubjectPublicKeyInfo)
                                    .decode('utf-8')))
    logger.info("Number of imported keys :" + str(len(keys)))
    return keys
    def get_system_user_ticket(self, sys_token, context_id):
        """
        returns Ticket credential string.

        Attributes
        ----------
        sys_token : str
        the tenant-specific system user token.

        context_id : str
        the customer identifier, i.e. Cust12345.
        """

        time_utc = datetime.utcnow()
        time_formatted = datetime.strftime(time_utc, "%Y%m%d%H%M")
        system_token = sys_token + '.' + time_formatted

        key = crypto.load_privatekey(crypto.FILETYPE_PEM, self.private_key)
        signature = crypto.sign(key, system_token, 'sha256')
        signed_system_token = system_token + "." + \
            b64encode(signature).decode('UTF-8')

        headers = OrderedDict([('ApplicationToken', self.application_token),
                               ('ContextIdentifier', context_id)])

        client = Client('file:%s' % self.wsdl_path)
        client.set_options(soapheaders=headers)
        client.set_options(
            location='https://{env}.superoffice.com/{endpoint}'.format(
                env=self.environment, endpoint=self.login_endpoint))

        token_type = client.factory.create('TokenType')['Jwt']

        response = client.service.Authenticate(signed_system_token, token_type)

        if response.IsSuccessful == True:
            jwt_token = response.Token
            print('Reponse: ' + str(response))
            jwt = JWT()
            jwksResponse = requests.get(
                'https://{env}.superoffice.com/login/.well-known/jwks'.format(
                    env=self.environment))
            jwks = json.loads(jwksResponse.text)
            verifying_key = jwk_from_dict(jwks['keys'][0])
            message_received = jwt.decode(jwt_token, verifying_key)

            return str(message_received[
                'http://schemes.superoffice.net/identity/ticket'])

        return 'Failed!'
def verify_token(token):
    region = 'eu-west-2'
    userpool_id = 'eu-west-2_6Mn0M2i9C'
    keys_url = 'https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json'.format(
        region, userpool_id)
    response = requests.get(keys_url).json()
    try:
        for key in response["keys"]:
            verifying_key = jwk_from_dict(key)
            jwt = JWT()
            return jwt.decode(token, verifying_key)
    except Exception as e:
        print(e)
        return None
Пример #11
0
 def get_task_token_objective(cls, token: str,
                              authorizer: Authorizer) -> str:
     jwk_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             'jwk.json')
     with open(jwk_path, 'r') as f:
         jwk = jwt.jwk_from_dict(json.load(f))
     decoded = jwt.JWT().decode(token, jwk)
     try:
         Schema({
             "sub": str,
             "objective": str,
             "exp": int,
             "iat": int
         }).validate(decoded)
     except SchemaError:
         raise InvalidException("The given task token is not valid")
     if authorizer.sub != decoded['sub']:
         raise ForbiddenException(
             "The given task token does not belong to this user")
     return decoded['objective']
Пример #12
0
    def generate_objective_token(cls,
                                 objective_key: str,
                                 authorizer: Authorizer,
                                 duration: timedelta = None):
        if duration is None:
            duration = timedelta(days=1)
        jwk_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                'jwk.json')
        with open(jwk_path, 'r') as f:
            jwk = jwt.jwk_from_dict(json.load(f))
        encoder = jwt.JWT()

        now = datetime.now(timezone.utc)
        payload = {
            'sub': authorizer.sub,
            "iat": get_int_from_datetime(now),
            "exp": get_int_from_datetime(now + duration),
            "objective": objective_key
        }
        return encoder.encode(payload, jwk)
Пример #13
0
def assertion_token(client_id, tenant_id, issuer, jwk):
    x5t = jwk['x5t']
    signing_key = jwk_from_dict(jwk)
    now = time.mktime(datetime.now().timetuple())

    headers = {
        'x5t': x5t
    }

    json_data = {
        'aud': issuer,
        'exp': now + 60,
        'iss': client_id,
        'jti': str(uuid.uuid4()),
        'nbf': now,
        'sub': client_id
    }

    instance = JWT()
    return instance.encode(json_data, signing_key, alg='RS256', optional_headers=headers)
Пример #14
0
    def generate_reward_token(cls,
                              authorizer: Authorizer,
                              static: RewardSet = None,
                              area: Optional[str] = None,
                              boxes: List[RewardSet] = None,
                              duration: timedelta = None,
                              reason: Enum = None) -> str:
        from core.services.beneficiaries import BeneficiariesService

        if duration is None:
            duration = timedelta(days=7)
        jwk_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                'jwk.json')

        with open(jwk_path, 'r') as f:
            jwk = jwt.jwk_from_dict(json.load(f))
        encoder = jwt.JWT()

        now = datetime.now(timezone.utc)
        token_index = int(BeneficiariesService.add_token_index(authorizer))
        payload = {
            "sub":
            authorizer.sub,
            "iat":
            get_int_from_datetime(now),
            "exp":
            get_int_from_datetime(now + duration),
            "static":
            static.to_map_list() if static is not None else [],
            "boxes":
            [box.to_map_list() for box in boxes] if boxes is not None else [],
            "index":
            token_index,
            "area":
            area,
            "reason":
            None if reason is None else reason.value
        }

        return encoder.encode(payload, jwk)
Пример #15
0
def get_key():
    with open('key.json', 'r') as fh:
        return jwk_from_dict(json.load(fh))
Пример #16
0
def _authenticate_fxa_jwt(jwt):
    private_relay_config = apps.get_app_config('privaterelay')
    for verifying_key_json in private_relay_config.fxa_verifying_keys:
        verifying_key = jwk_from_dict(verifying_key_json)
        return jwt_instance.decode(jwt, verifying_key)
Пример #17
0
    def claim_reward(cls, authorizer: Authorizer, reward_token: str, release: int, box_index: int = None) -> \
            List[Reward]:
        from core.services.beneficiaries import BeneficiariesService

        jwk_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                'jwk.json')
        with open(jwk_path, 'r') as f:
            jwk = jwt.jwk_from_dict(json.load(f))

        decoder = jwt.JWT()
        try:
            decoded = decoder.decode(reward_token, jwk)
        except JWTDecodeError as e:
            raise InvalidException(f'Invalid token: {e.args}')

        now = get_int_from_datetime(datetime.now())
        if now > decoded["exp"]:
            raise ForbiddenException("The reward token has expired")
        if authorizer.sub != decoded["sub"]:
            raise ForbiddenException(
                "This token does not belong to the claimer")
        BeneficiariesService.set_reward_index(authorizer, decoded['index'])

        boxes = decoded["boxes"]
        probabilities: List[RewardProbability] = [
            RewardProbability.from_map(reward) for reward in decoded["static"]
        ]
        if len(boxes) > 0:
            if box_index is None:
                raise InvalidException("A box must be chosen")
            if box_index >= len(boxes):
                raise InvalidException(
                    f"Box index out of range, it must be between 0 (inclusive) and {len(boxes)} (exclusive)"
                )
            probabilities += [
                RewardProbability.from_map(reward)
                for reward in boxes[box_index]
            ]
        rewards = [
            RewardsService.get_random(probability.type, release,
                                      probability.rarity)
            for probability in probabilities
        ]
        LogsService.batch_create(logs=[
            Log(sub=authorizer.sub,
                tag=join_key(LogTag.REWARD.name, rewards[reward_i].type.name,
                             rewards[reward_i].id),
                log='Won a reward',
                data=rewards[reward_i].to_api_map(),
                append_timestamp=rewards[reward_i].type != RewardType.AVATAR)
            for reward_i in range(len(rewards))
        ])

        area: Optional[str] = decoded.get('area')
        areas: List[str] = VALID_AREAS if area is None else [area]

        scores = {}
        for r in rewards:
            if r.type != RewardType.POINTS:
                continue
            total_score = r.description['amount']
            for a in areas:
                scores[a] = scores.get(a, 0) + (total_score / len(areas))

        for key in scores:
            scores[key] = math.ceil(scores[key])

        BeneficiariesService.add_score(authorizer.sub, scores)
        return rewards
Пример #18
0
 def __init__(self):
     self.verifying_key = jwk_from_dict({
         'kty': 'oct',
         'kid': 'HMAC key used in JWS A.1 example',
         'k': settings.SECRET_KEY
     })
Пример #19
0
import requests
from aiohttp import web
from jwt import JWT, jwk_from_dict
from util import load_yaml, rndstr, url_encode

AUTH_ENDPOINT = "https://id.twitch.tv/oauth2/authorize"
TOKEN_ENDPOINT = "https://id.twitch.tv/oauth2/token"

config = load_yaml("config.yaml")
jwt_instance = JWT()
jwt_key = jwk_from_dict(
    requests.get("https://id.twitch.tv/oauth2/keys").json()["keys"][0])

session = {}


async def login(request):
    session["state"] = rndstr()
    session["nonce"] = rndstr()
    args = {
        "client_id": config["client_id"],
        "response_type": "code",
        "scope": "openid",
        "nonce": session["nonce"],
        "redirect_uri": config["api_url"] + "/callback",
        "state": session["state"],
    }
    raise web.HTTPFound(AUTH_ENDPOINT + url_encode(args))


async def login_callback(request):
Пример #20
0
import time
from jwt import (
    JWT,
    jwk_from_dict,
    jwk_from_pem,
)
import os
from flask import Flask, jsonify, request
from flask_cors import CORS
import methods

app = Flask(__name__)
CORS(app)

instanceJWT = JWT()
key = jwk_from_dict({'kty': 'oct', 'k': 'biiirHospOn'})


@app.route('/')
def hello_world():
    return jsonify({"message": "Hello Heroku"})


@app.route('/auth', methods=['POST'])
def authorization():
    authType = request.args.get('by')
    content = request.json

    if authType == 'facebook':
        auth = request.headers['authorization']
        r = requests.get('https://graph.facebook.com/me?access_token=' +
Пример #21
0
PORT = os.environ.get("FILEDEPOT_PORT", 5000)
SALT = os.environ.get("FILEDEPOT_SALT", "OIT-FileDepot")

# Initilization of necessary tools
s3sh = S3sh(BUCKET, KEY_PREFIX)
db = boto3.resource("dynamodb").Table(TABLE_NAME)
application = Flask(__name__)
CORS(application)
api = Api(application)
jwt_lib = JWT()

# Retrieve JWKs of our designated issuer from the issuer's "well-known URL".
jwks = dict()
for jwk_dict in requests.get(JWT_ISSUER +
                             "/.well-known/jwks.json").json()["keys"]:
    jwks[(jwk_dict["kid"], jwk_dict["alg"])] = jwk_from_dict(jwk_dict)


# This function is used for extracting UID from the request, with the following steps:
# (1) It extracts the JWT string from the "FileDepot-jwt" field of the request header.
#       If the field doesn't exist, then responds with error 400: Bad request.
# (2) If the JWT is issued by our designated issuer, and is not expired, then
#       extract the username from "cognito:username".
#       Otherwise responds with error 401: Unauthorized.
# (3) Salt the username, then return its hash as the UID.
def get_uid(request):
    try:
        jwt_string = request.headers["FileDepot-jwt"]
        key_info = json.loads(
            str(b64decode(jwt_string.split(".")[0] + "="), "utf-8"))
        jwk = jwks[(key_info["kid"], key_info["alg"])]