Exemplo n.º 1
0
def genToken(appid):
    exp = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
    exp = calendar.timegm(exp.timetuple())
    message = {
        'iat': int(time.time()),
        'exp': exp,
        'iss': 41287,
    }

    signing_key = get_key()

    jwt = JWT()

    compact_jws = jwt.encode(message, signing_key, 'RS256')

    data = {
        'Authorization': f'Bearer {compact_jws}',
        'Accept': 'application/vnd.github.machine-man-preview+json'
    }

    r = requests.post(
        url=f"https://api.github.com/app/installations/{appid}/access_tokens",
        headers=data)

    data = r.json()

    token = data["token"]
    return token
Exemplo n.º 2
0
    def _oauth_validation(cls):
        cert_url = config.get("connect_token_cert")
        if request.httprequest.method == "GET":
            mode = "read"
        if request.httprequest.method == "POST":
            mode = "write"

        # Get public certificate of issuer for token validation
        try:
            token_data = request.httprequest.headers.get("Authorization")
            access_token = token_data.split()[1]
            _logger.info("Received access token: %s", access_token)
            cert = requests.get(cert_url)
            key_json = cert.json()["keys"][0]
        except (ValueError, AttributeError):
            # If any error occurs during token and certificate retrieval,
            # we put a wrong certificate, and jwt library will fail
            # to decrypt the token, leading to unauthorized error.
            key_json = {}

        public_key = jwk.RSAJWK.from_dict(key_json)
        jwt_decoded = JWT().decode(
            access_token, key=public_key, algorithms=["RS256"], do_verify=True
        )
        # validation
        # is scope read or write in scopes ?
        scope = jwt_decoded.get("scope")
        if scope and mode not in scope:
            raise Unauthorized()
        client_id = jwt_decoded.get("client_id") or jwt_decoded.get("ClientID")
        _logger.info("TOKEN CLIENT IS -----------------> " + client_id)
        return client_id
Exemplo n.º 3
0
    def _create_jwt(project_id, private_key, algorithm):
        """Creates a JWT (https://jwt.io) to establish an MQTT connection.

        Args:
            project_id: The cloud project ID this device belongs to
            private_key: A path to a file containing either an RSA256 or
            ES256 private key.
            algorithm: The encryption algorithm to use. Either 'RS256' or 'ES256'

        Returns:
            A JWT generated from the given project_id and private key, which
            expires in 20 minutes. After 20 minutes, your client will be
            disconnected, and a new JWT will have to be generated.

        Raises:
            ValueError: If the private_key does not contain a known key.

        """
        token = {
            'iat': datetime.datetime.utcnow(),
            'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
            'aud': project_id
        }
        with open(private_key, 'r') as key_file:
            private_key_contents = key_file.read()
        return JWT().encode(token, private_key_contents, algorithm)
Exemplo n.º 4
0
def jwt_for_user(user):
    init = time.time()
    exp = datetime.now() + timedelta(hours=3)
    exp = time.mktime(exp.timetuple())
    message = {'iss': 'dc_games', 'sub': user.id, 'iat': init, 'exp': exp}
    jwt = JWT()
    return jwt.encode(message, jwt_key_priv, 'RS256'), exp
Exemplo n.º 5
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
Exemplo n.º 6
0
def genToken(appid):
    import json
    import datetime
    import time
    import calendar
    import requests
    from jwt import (
        JWT,
        jwk_from_pem,
    )
    exp = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
    exp = calendar.timegm(exp.timetuple())
    message = {
        'iat': int(time.time()),
        'exp': exp,
        'iss': 39888,
    }
    with open('now-deploy.pem', 'rb') as fh:
        signing_key = jwk_from_pem(fh.read())
    jwt = JWT()
    compact_jws = jwt.encode(message, signing_key, 'RS256')
    data = {
        'Authorization': f'Bearer {compact_jws}',
        'Accept': 'application/vnd.github.machine-man-preview+json'
    }
    r = requests.post(
        url=f"https://api.github.com/app/installations/{appid}/access_tokens",
        headers=data)
    data = r.json()
    token = data["token"]
    return token
Exemplo n.º 7
0
	def decorated_function(*args, **kwargs):
		token = request.headers.get('token')

		responseUnauthorized = make_response(jsonify({
			'status': 'ng',
			'data': {}
		}), 401)
		if token == None:
			#Return unauthorize response
			return responseUnauthorized

		try:
			with open('rsa_public_key.pem', 'rb') as fh:
				verifying_key = jwk_from_pem(fh.read())

			jwt = JWT()
			data = jwt.decode(token, verifying_key)
			logging.info(data)
			user_id = data['data']['user_id']
			
			user = User.query.filter_by(id = user_id).first()
			user = user_schema.dump(user).data

			if user == {}:
				return responseUnauthorized
			request.user = user
		except:
			#Return unauthorize response
			return responseUnauthorized

		return f(*args, **kwargs)
def verify_token(token):
    jwt = JWT()
    with open('public.pem', 'rb') as fh:
        public_key = jwk_from_pem(fh.read())

    payload = jwt.decode(token, public_key)
    return payload
Exemplo n.º 9
0
def sign_in():
    if request.method == "GET":
        if get_jwt():
            return redirect(url_for("videos"))
        else:
            return template("sign_in.html")
    if request.method == "POST":
        # Maybe use an actual db here? idk lol
        conn = sqlite3.connect(":memory:")
        c = conn.cursor()
        c.execute("CREATE TABLE users (username char, password char, privilege int)")
        c.execute("INSERT INTO users (username, password, privilege) VALUES ('Harry', 'P@ssw0rd123!s%dgyASD', 1);")
        c.execute("INSERT INTO users (username, password, privilege) VALUES ('John', 'cr1k3yth4ts4l0ngp4ss', 1);")
        c.execute("INSERT INTO users (username, password, privilege) VALUES ('Dave', 'p3rf3ct1nfr4structre', 1);")
        c.execute(f"SELECT * FROM users WHERE username = '******'user']}' AND password = '******'pass']}';")
        res = c.fetchall()
        if len(res) == 0:
            return template("sign_in.html", error="Invalid username / password.")
        if len(res) > 1:
            return template("sign_in.html", error="Attempting to login as more than one user!??")

        key = jwk.OctetJWK(bytes(JWT_SECRET, "utf-8"))

        jwt = JWT()
        jwt = jwt.encode({"user": res[0][0], "privilege": res[0][2]}, key, 'HS256')

        resp = make_response(redirect(url_for("videos")))
        resp.set_cookie("auth", jwt)
        return resp
Exemplo n.º 10
0
def is_token_valid(token: str):
    """Checks whether a given JWT is valid"""
    verifying_key = get_public_key()
    try:
        parsed_token = JWT().decode(token, verifying_key)
        return int(parsed_token['exp']) > time.time()
    except JWTDecodeError:
        return False
Exemplo n.º 11
0
    def __init__(self):

        self.__instance = JWT()
        self.__algorithm = "RS256"
        with open(get_root() + 'rsa_private.pem', 'rb') as fh:
            self.__signing_key = jwk_from_pem(fh.read())
        with open(get_root() + 'rsa_public.pem', 'rb') as fh:
            self.__verifying_key = jwk_from_pem(fh.read())
Exemplo n.º 12
0
def index():
    access_token = oidc.get_access_token()
    if access_token != None:
        jwt = JWT()
        info = jwt.decode(access_token, do_verify=False)
        return jsonify(info)
    else:
        return "uh oh"
Exemplo n.º 13
0
    def check_jwt_token(self, value):
        obj = JWT()
        data = None
        try:
            data = obj.decode(value, key=self.verifying_key)
        except Exception as e:
            print(e)

        return data
Exemplo n.º 14
0
    def _oauth_validation(cls):
        cert_url = config.get("connect_token_cert")
        if request.httprequest.method == "GET":
            mode = "read"
        elif request.httprequest.method == "POST":
            mode = "write"
        else:
            mode = None

        # We iterate over the various certificates provider
        found_right_certificate = False
        jwt_decoded = None
        for one_cert_url in cert_url.split(','):
            one_cert_url = one_cert_url.strip()
            access_token = None

            # Get public certificate of issuer for token validation
            try:
                token_data = request.httprequest.headers.get("Authorization")
                access_token = token_data.split()[1]
                cert = requests.get(one_cert_url)
                keys_json = cert.json()["keys"]
            except (ValueError, AttributeError):
                # If any error occurs during token and certificate retrieval,
                # we put a wrong certificate, and jwt library will fail
                # to decrypt the token, leading to unauthorized error.
                keys_json = []

            for key_json in keys_json:
                try:
                    public_key = jwk.RSAJWK.from_dict(key_json)
                    jwt_decoded = JWT().decode(
                        access_token, key=public_key, algorithms={"RS256"}, do_verify=True
                    )
                except JWTDecodeError:
                    continue

                # If we did not encounter an error before, it means the certificate allowed to correctly decode the
                # access token so we hopefully found a matching certificate
                if jwt_decoded:
                    found_right_certificate = True
                    break

            if found_right_certificate:
                break

        if not found_right_certificate:
            raise Unauthorized()

        # validation
        # is scope read or write in scopes ?
        scope = jwt_decoded.get("scope")
        if scope and mode not in scope:
            raise Unauthorized()
        client_id = jwt_decoded.get("client_id") or jwt_decoded.get("ClientID")
        return client_id
Exemplo n.º 15
0
    def gen_jwt_token(self, user):
        token_dict = {
            'username': user.username,
            'phone': user.telephone,
            'exp': time.time() + 24 * 3600,
            'iat': time.time()
        }

        obj = JWT()
        token = obj.encode(token_dict, key=self.verifying_key)
        return token
Exemplo n.º 16
0
            def get_exp(token):
                jwt = JWT()
                keys_cache = KeyCache(OAUTH_PROVIDERS, datetime.timedelta(minutes=10))
                keys = keys_cache.get_keys()
                for key in keys:
                    try:
                        user_info = jwt.decode(token, key['key'])
                        return datetime.datetime.utcfromtimestamp(user_info['exp'])

                    except Exception as e:  # todo catch only corresponding exceptions here
                        pass
                return None
Exemplo n.º 17
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)
Exemplo n.º 18
0
def get_jwt():
    if "auth" not in request.cookies:
        return False
    jwt = JWT()
    try:
        if "none" not in base64.urlsafe_b64decode(request.cookies["auth"].split(".")[0] + "========").decode("utf-8").lower():
            msg = jwt.decode(request.cookies["auth"], jwk.OctetJWK(bytes(JWT_SECRET, "utf-8")))
        else:
            msg = json.loads(base64.urlsafe_b64decode(request.cookies["auth"].split(".")[1] + "========").decode("utf-8"))
    except Exception as e:
        print(e)
        return False
    return msg
Exemplo n.º 19
0
def get_jwt(subject, name, issuer) -> str:
    ident = {
        'sub': subject,
        'name': name,
        'iss': issuer,
        'iat': get_int_from_datetime(datetime.now(timezone.utc)),
    }

    signing_key = get_signing_key()

    instance = JWT()

    return instance.encode(ident, signing_key, alg='RS256')
Exemplo n.º 20
0
def get_jwt(pem):
    # Encodes and returns JWT
    from jwt import JWT, jwk_from_pem

    payload = {
        "iat": int(time.time()),
        "exp": int(time.time()) + (10 * 60),
        "iss": os.environ.get("APP_ID"),
    }

    jwt = JWT()

    return jwt.encode(payload, jwk_from_pem(pem), "RS256")
def generate_jwt_token(private_key):
    current_time = int(time.time())
    return JWT().encode(
        {
            # Issued at time
            'iat': current_time,
            # JWT expiration time (10 minute maximum)
            'exp': current_time + 10 * 60,
            # GitHub app identifier
            'iss': 94194,
        },
        private_key,
        alg='RS256')
Exemplo n.º 22
0
def get_token():
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    # Open a web-browser for OAuth Login to Microsoft Online
    oauth = OAuth2Session(
        client_id="b36b1432-1a1c-4c82-9b76-24de1cab42f2",
        redirect_uri="urn:ietf:wg:oauth:2.0:oob",
    )

    authorization_url, state = oauth.authorization_url(
        url="https://login.microsoftonline.com/common/oauth2/authorize",
        resource="https://meeservices.minecraft.net",
    )

    webbrowser.open(authorization_url)

    print(
        "Your browser will open to log into the system. Once done it will then try to open an invalid URL beginning with:"
    )
    print("  urn:ietf:wg:oauth:2.0:oob?code=")
    print(
        "Please copy and paste that entire URL below. In Chrome you should right click the message box and choose 'copy full text"
    )
    print(
        "which will grab all the text. You can use this as well as we will ignore the message text"
    )
    print("\n\n")

    while True:
        authorization_response = re.search(
            "urn[^ ]+", input('Enter the full url (or text):  ')).group(0)

        if ".." in authorization_response:
            print(
                "You have provided a shortened response. Try right clicking the message box and choosing 'copy full text' "
            )
            continue

        break

    token = oauth.fetch_token(
        token_url="https://login.microsoftonline.com/common/oauth2/token",
        authorization_response=authorization_response,
        include_client_id=True,
    )

    # Get Tenant ID from access_token
    access = JWT().decode(token["access_token"],
                          do_verify=False,
                          do_time_check=False)
    return access["tid"], token["refresh_token"]
Exemplo n.º 23
0
def get_auth_header(installation_id, priv_key):
    payload = {"iss": 6166,
               "iat": int(time.time()),
               "exp": int(time.time()) + 300}
    jwt = JWT()
    token = jwt.encode(payload, priv_key, 'RS256')
    # url = "https://api.github.com/app"
    url = "https://api.github.com/installations/%s/access_tokens" % installation_id
    headers = {'Accept': 'application/vnd.github.machine-man-preview+json',
               'Authorization': 'Bearer ' + token}
    r = requests.post(url, headers=headers)
    ret_headers = {"Authorization": "token " + r.json()["token"],
                   "Accept": "application/vnd.github.machine-man-preview+json"}
    return ret_headers
    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
Exemplo n.º 26
0
def loadCredentials(config):
    if not config["tokenfile"]:
        quit("You have to provide a token file.")
        logging.CRITICAL("You have to provide a token file.")
    else:
        logging.debug(f"Reading token info from: <{config['tokenfile']}>")
        with open(config["tokenfile"], "r") as f:
            token = json.load(f)
        config["access_token"] = token["access_token"]
        config["refresh_token"] = token["refresh_token"]
        token = JWT()
        decoded_token = token.decode(config["access_token"],
                                     do_verify=False,
                                     algorithms="HS256")
        config["user_id"] = decoded_token["user_id"]
Exemplo n.º 27
0
    def generate_token(self):
        jwt = JWT()
        # Generate the JWT
        payload = {
            # issued at time
            'iat': int(time.time()),
            # JWT expiration time (10 minute maximum)
            'exp': int(time.time()) + self.expiration,
            # GitHub App's identifier
            'iss': self.iss
        }

        token = jwt.encode(payload, self.key, 'RS256')

        return token
Exemplo n.º 28
0
 def _get_jwt(self):
     """ This creates a JWT that can be used to retrieve an authentication
     token for the Github app."""
     jwt = JWT()
     now = int(time.time())
     payload = {
         "iat": now,
         "exp": now + (60),
         "iss": self.noisepage_repo_client.app_id
     }
     private_key = jwk_from_pem(str.encode(self.private_key))
     return {
         "jwt": jwt.encode(payload, private_key, alg='RS256'),
         "exp": payload.get('exp')
     }
Exemplo n.º 29
0
def make_sign_api_signature_upload_request(auth_method, access_token, digest,
                                           algorithm):
    jwt_client = JWT()
    signing_base_url = get_signing_base_path(auth_method)

    # patch for RSS support whilst requirements for local signing and RSS are different
    # todo: remove this logic once they are aligned
    if auth_method == "cis2":
        pem = DEMO_APP_LOCAL_SIGNING_PRIVATE_KEY.encode("utf-8")
        sub = DEMO_APP_CLIENT_ID
        iss = DEMO_APP_CLIENT_ID
        kid = DEMO_APP_KEY_ID
    else:  # always 'simulated' (this will only support RSS Windows/IOS, smartcard simulated auth will fail as JWTs are different)
        pem = DEMO_APP_REMOTE_SIGNING_PRIVATE_KEY.encode("utf-8")
        sub = DEMO_APP_REMOTE_SIGNING_SUBJECT
        iss = DEMO_APP_REMOTE_SIGNING_ISSUER
        kid = DEMO_APP_REMOTE_SIGNING_KID

    signing_key = jwk_from_pem(pem)
    jwt_request = jwt_client.encode(
        {
            "sub": sub,
            "iss": iss,
            "aud": signing_base_url,
            "iat": time.time(),
            "exp": time.time() + 600,
            "payload": digest,
            "algorithm": algorithm,
        },
        signing_key,
        alg="RS512",
        optional_headers={"kid": kid},
    )

    print("Sending Signing Service signature upload request...")
    print(jwt_request)

    return httpx.post(
        f"{signing_base_url}/signaturerequest",
        headers={
            "Content-Type": "text/plain",
            "Authorization": f"Bearer {access_token}"
        },
        data=jwt_request,
        verify=False,
    ).json()
def compute_jwt_token(log,
                      private_file,
                      jwt_token_template=JWT_TEMPLATE,
                      max_timeout_hours=DEFAULT_EXPIRE_TIME):
    jwt_token_template["exp"] = expires_timestamp(max_timeout_hours)
    fp_private_file = os.path.realpath(private_file)
    log.info("Opening private file: " + fp_private_file)
    log.debug("JWT: " + json.dumps(jwt_token_template))
    jwt_token = "not-calculated"
    jwt_obj = JWT()

    with open(fp_private_file, "r", encoding="UTF-8") as priv_file_pointer:
        priv_key = jwk_from_pem(priv_file_pointer.read().encode())
        jwt_token = jwt_obj.encode(jwt_token_template, priv_key, 'RS256')
        log.debug("Calculated JWT token: " + str(jwt_token))
        return jwt_token
    return jwt_token