python类decode()的实例源码

views.py 文件源码 项目:cookiecutter-saas 作者: jayfk 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def clean_transactionDetails(self):
        details = self.cleaned_data["transactionDetails"]
        try:
            data = jwt.decode(details, settings.OCTOBAT_PRIVATE_KEY)
            customer = data["customer_id"]
            return data
        except DecodeError as e:
            logger.error("Unable to clean transactionDetails for data: {}".format(
                details
            ), exc_info=True)
            raise forms.ValidationError("transaction details could'nt be received")
        except KeyError as e:
            logger.error("Unable to clean transactionDetails for data: {}".format(
                details
            ), exc_info=True)
            raise forms.ValidationError("transaction details could'nt be received")
flask_jwt.py 文件源码 项目:opp 作者: openpassphrase 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _default_jwt_decode_handler(token):
    secret = current_app.config['SECRET_KEY']
    algorithm = current_app.config['JWT_ALGORITHM']
    leeway = current_app.config['JWT_LEEWAY']

    verify_claims = current_app.config['JWT_VERIFY_CLAIMS']
    required_claims = current_app.config['JWT_REQUIRED_CLAIMS']

    options = {
        'verify_' + claim: True
        for claim in verify_claims
    }

    options.update({
        'require_' + claim: True
        for claim in required_claims
    })

    return jwt.decode(token, secret, options=options,
                      algorithms=[algorithm], leeway=leeway)
secure.py 文件源码 项目:home-automation 作者: danionescu0 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def secure(method):
    def wrapper(self, *args, **kwargs):
        auth = self.request.headers.get('Authorization')
        if not auth:
            return invalid_auth(self, "Missing authorization")

        auth_header = auth.split()

        if auth_header[0].lower() != 'bearer' or len(auth_header) == 1:
            return invalid_auth(self, "Invalid authorization header")
        token = auth_header[1]
        try:
            jwt.decode(token, general.web_server['api_token_secret'], algorithm='HS256')
        except Exception as e:
            invalid_auth(self, "Invalid token")

        return method(self, *args, **kwargs)

    def invalid_auth(self, message):
        self.set_status(401)
        self.write(message)
        self.finish()

    return wrapper
auth.py 文件源码 项目:nanosphere 作者: walkr 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def decode_jwt(token, options=None):
    """ Authenticate via JSON Web Token

    Options: `secret`, `algorithms` """

    options = options or {}
    secret = options.get('secret', CONF and CONF.secret)
    algorithms = options.get('algorithms', CONF and CONF.algorithms)

    try:
        data = jwt.decode(token, secret, algorithms)
    except jwt.DecodeError:
        raise Exception('Cannot decode token')
    else:
        logging.debug('* Decoded data = {}'.format(data))
        return data
validators.py 文件源码 项目:territoriali-backend 作者: algorithm-ninja 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def _get_user_from_sso(jwt_token, token):
        try:
            data = jwt.decode(jwt_token, Config.jwt_secret, algorithms=['HS256'])
            username = data["username"]
            name = data.get("firstName", username)
            surname = data.get("lastName", "")
            if username != token:
                BaseHandler.raise_exc(Forbidden, "FORBIDDEN", "Use the same username from the SSO")
            if Database.get_user(username) is None:
                Database.begin()
                Database.add_user(username, name, surname, sso_user=True, autocommit=False)
                for task in Database.get_tasks():
                    Database.add_user_task(username, task["name"], autocommit=False)
                Database.commit()
                Logger.info("NEW_USER", "User %s created from SSO" % username)
            return Database.get_user(username)
        except jwt.exceptions.DecodeError:
            BaseHandler.raise_exc(Forbidden, "FORBIDDEN", "Please login at %s" % Config.sso_url)
user.py 文件源码 项目:jamdb 作者: CenterForOpenScience 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __init__(self, jwt_token, verify=True):
        if not jwt_token:
            self.id = None
            self.jwt = None
            self.uid = None
            self.type = None
            self.token = None
            self.granted = {}
            self.limited = False
            self.provider = None
            return
        self.token = jwt_token
        self.jwt = jwt.decode(jwt_token, settings.JWT_SECRET, verify=verify, option={'require_exp': True})
        self.uid = self.jwt['sub']
        self.limited = self.jwt['limit']
        self.granted = {k: Permissions(v) for k, v in self.jwt['granted'].items()}
        type_, provider, *parts = self.uid.split('-')

        self.type = type_ or None
        self.provider = provider or None
        self.id = '-'.join(parts) or None
jwt_auth.py 文件源码 项目:PythonSkillTree 作者: w4n9H 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def check_jwt(jwt_code):
    try:
        jwt_list = jwt_code.split('.')
        if len(jwt_list) == 3:
            h, p, s = jwt_list
            headers = base64.b64decode(h)
            crypt_type = json.loads(headers).get('alg', None)
            if crypt_type:
                payload = base64_url_decode(p)
                access_key = json.loads(payload).get('accesskey', None)
                if access_key:
                    secret_key = get_key(access_key)[0]
                    if secret_key:
                        payload = jwt.decode(jwt_code, secret_key, algorithms=crypt_type)
                        return True, payload
                    else:
                        return False, "jwt payload error key"
                else:
                    return False, 'jwt payload error'
            else:
                return False, 'jwt headers error'
        else:
            return False, 'jwt code error'
    except Exception as error:
        return False, str(error)
app.py 文件源码 项目:data-service 作者: Runnerly 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def authenticate(app, request):
    key = request.headers.get('Authorization')
    if key is None:
        return abort(401)

    key = key.split(' ')
    if len(key) != 2:
        return abort(401)

    if key[0].lower() != 'bearer':
        return abort(401)

    pub_key = app.config['pub_key']
    try:
        token = key[1]
        token = jwt.decode(token, pub_key, audience='runnerly.io')
    except Exception as e:
        return abort(401)

    # we have the token ~ copied into the globals
    g.jwt_token = token
session.py 文件源码 项目:paws 作者: funkybob 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __call__(self, request, *args, **kwargs):
        import jwt
        if self.cookie_name in request.cookies:
            try:
                value = request.cookies[self.cookie_name].value
                data = jwt.decode(value, self.secret)
                request.session = Session(data)
            except:
                pass
        else:
            request.session = Session()

        resp = self.func(request, *args, **kwargs)
        if not request.session.clean:
            data = dict(request.session)
            value = jwt.encode(request.session, self.secret, algorith=self.algorithm)
            resp.cookies[self.cookie_name] = value
        return resp
forms.py 文件源码 项目:bluebutton-web-server 作者: CMSgov 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def clean_jwt(self):
        # TODO: this part may be removed or updated
        # req = ('iss', 'iat', 'exp', 'client_name', 'redirect_uris', 'client_uri')
        jwtc = self.cleaned_data.get('jwt')

        try:
            decoded_payload = jwtl.decode(jwtc, verify=False)
        except Exception:
            msg = _('Invalid JWT.')
            raise forms.ValidationError(msg)

        if isinstance(decoded_payload, OrderedDict):
            msg = _('Invalid Payload.')
            raise forms.ValidationError(msg)
        # TODO: this part may be removed or updated
        # for r in req:
        #     if r not in decoded_payload:
        #         msg=_('Required value %s missing from payload' % (r))
        #         raise forms.ValidationError(msg)

        return jwtc
backends.py 文件源码 项目:django-realworld-example-app 作者: gothinkster 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def _authenticate_credentials(self, request, token):
        """
        Try to authenticate the given credentials. If authentication is
        successful, return the user and token. If not, throw an error.
        """
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
        except:
            msg = 'Invalid authentication. Could not decode token.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = User.objects.get(pk=payload['id'])
        except User.DoesNotExist:
            msg = 'No user matching this token was found.'
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = 'This user has been deactivated.'
            raise exceptions.AuthenticationFailed(msg)

        return (user, token)
_profile.py 文件源码 项目:azure-cli 作者: Azure 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def find_subscriptions_in_vm_with_msi(self, msi_port, identity_id=None):
        import jwt
        token, identity_id_type = Profile.get_msi_token(CLOUD.endpoints.active_directory_resource_id,
                                                        msi_port, identity_id, for_login=True)
        logger.info('MSI: token was retrieved. Now trying to initialize local accounts...')
        decode = jwt.decode(token, verify=False, algorithms=['RS256'])
        tenant = decode['tid']

        subscription_finder = SubscriptionFinder(self.auth_ctx_factory, None)
        subscriptions = subscription_finder.find_from_raw_token(tenant, token)
        if not subscriptions:
            raise CLIError('No access was configured for the VM, hence no subscriptions were found')
        base_name = '{}-{}'.format(identity_id_type, identity_id) if identity_id else identity_id_type
        user = 'userAssignedIdentity' if identity_id else 'systemAssignedIdentity'
        consolidated = Profile._normalize_properties(user, subscriptions, is_service_principal=True)
        for s in consolidated:
            # use a special name to trigger a special token acquisition
            s[_SUBSCRIPTION_NAME] = "{}@{}".format(base_name, msi_port)
        # key-off subscription name to allow accounts with same id(but under different identities)
        self._set_subscriptions(consolidated, key_name=_SUBSCRIPTION_NAME)
        return deepcopy(consolidated)
websocket_server.py 文件源码 项目:baselayer 作者: cesium-ml 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def authenticate(self, auth_token):
        try:
            token_payload = jwt.decode(auth_token, secret)
            username = token_payload['username']

            self.username = username
            self.authenticated = True
            self.auth_failures = 0
            self.send_json(action='AUTH OK')

            # If we are the first websocket connecting on behalf of
            # a given user, subscribe to the feed for that user
            if len(WebSocket.sockets[username]) == 0:
                WebSocket.subscribe(username)

            WebSocket.sockets[username].add(self)

        except jwt.DecodeError:
            self.send_json(action='AUTH FAILED')
        except jwt.ExpiredSignatureError:
            self.send_json(action='AUTH FAILED')
websocket_server.py 文件源码 项目:baselayer 作者: cesium-ml 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def broadcast(cls, data):
        username, payload = [d.decode('utf-8') for d in data]

        if username == '*':
            print('[WebSocket] Forwarding message to all users')

            all_sockets = [socket
                           for socket_list in cls.sockets.values()
                           for socket in socket_list]

            for socket in all_sockets:
                socket.write_message(payload)

        else:

            for socket in cls.sockets[username]:
                print(f'[WebSocket] Forwarding message to {username}')

                socket.write_message(payload)
jwt.py 文件源码 项目:contactista 作者: singingwolfboy 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def refresh_jwt_token(token):
    payload = jwt.decode(
        token,
        key=current_app.config['SECRET_KEY'],
        algorithms=[JWT_ALGORITHM],
    )
    user = User.query.get(payload['identity'])
    if not user.active:
        raise ValueError("User is inactive")
    orig_iat = payload.get('orig_iat')
    if not orig_iat:
        raise ValueError("`orig_iat` field is required")
    refresh_limit = orig_iat + int(JWT_REFRESH_EXPIRATION_DELTA.total_seconds())
    now_ts = datetime.datetime.utcnow().timestamp()
    if now_ts > refresh_limit:
        raise ValueError("Refresh has expired")
    new_payload = jwt_payload(user)
    new_payload["orig_iat"] = orig_iat
    token = jwt.encode(
        new_payload,
        key=current_app.config['SECRET_KEY'],
        algorithm=JWT_ALGORITHM,
    )
    return token, user
calls_test.py 文件源码 项目:son-cli 作者: sonata-nfv 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def user_login(username, password):
    import requests
    import json
    from base64 import b64encode, b64decode

    # Construct the POST login request
    creds = (str(username) + ':' + str(password)).encode("utf-8")
    # print(str(username) + ':' + str(password))
    print(creds)
    encoded_password = b64encode(creds)
    print(encoded_password)
    print(encoded_password.decode("utf-8"))
    headers = {'Authorization': 'Basic %s' % (encoded_password.decode("utf-8"))}

    url = "http://sp.int3.sonata-nfv.eu:5600/api/v1/login/user"

    response = requests.post(url, headers=headers, verify=False)
    if not response.status_code in (200, 201):
        return response.text
    token = json.loads(response.text)['access_token']
    return token
calls_test.py 文件源码 项目:son-cli 作者: sonata-nfv 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def sign():
    from Crypto.Hash import SHA256
    from Crypto.PublicKey import RSA
    key = RSA.generate(2048)
    public = key.publickey().exportKey('PEM').decode('ascii')
    private = key.exportKey('PEM').decode('ascii')

    text = 'abcdefgh'.encode('utf-8')
    hash = SHA256.new(text).digest()
    signature = key.sign(hash, '')
    print('signature=', signature)


# Verify
# Knowing the public key, it is easy to verify a message.
# The plain text is sent to the user along with the signature.
# The receiving side calculates the hash value and then uses the public key verify() method to validate its origin.
home.py 文件源码 项目:tokendealer 作者: Runnerly 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def create_token():
    key = current_app.config['priv_key']
    try:
        data = request.form
        if data.get('grant_type') != 'client_credentials':
            return _400('Wrong grant_type')

        client_id = data.get('client_id')
        client_secret = data.get('client_secret')
        aud = data.get('audience', '')

        if not is_authorized_app(client_id, client_secret):
            return abort(401)

        now = int(time.time())

        token = {'iss': 'https://tokendealer.example.com',
                 'aud': aud,
                 'iat': now,
                 'exp': now + 3600 * 24}
        token = jwt.encode(token, key, algorithm='RS512')
        return {'access_token': token.decode('utf8')}
    except Exception as e:
        return _400(str(e))
utils.py 文件源码 项目:drf-jwt-devices 作者: ArabellaTech 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def jwt_devices_decode_handler(token):
    options = {
        "verify_exp": rfj_settings.JWT_VERIFY_EXPIRATION,
    }
    # get user from token, BEFORE verification, to get user secret key
    unverified_payload = jwt.decode(token, None, False)
    return jwt.decode(
        token,
        jwt_devices_get_secret_key(unverified_payload),
        rfj_settings.JWT_VERIFY,
        options=options,
        leeway=rfj_settings.JWT_LEEWAY,
        audience=rfj_settings.JWT_AUDIENCE,
        issuer=rfj_settings.JWT_ISSUER,
        algorithms=[rfj_settings.JWT_ALGORITHM]
    )
views.py 文件源码 项目:mangaNotif 作者: Symphoria 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def is_authenticated(req):
    auth_token = req.headers.get('Authentication-Token')

    if auth_token:
        try:
            auth_token_payload = jwt.decode(auth_token, os.environ["JWT_SECRET"])
            user_id = int(auth_token_payload['user_id'])
            user = User.query.filter_by(id=user_id, is_active=True).first()

            if user:
                return user
            else:
                return False
        except jwt.ExpiredSignatureError:
            return False
    else:
        return False


问题


面经


文章

微信
公众号

扫码关注公众号