当前位置: 首页>>代码示例>>Python>>正文


Python security.safe_str_cmp方法代码示例

本文整理汇总了Python中werkzeug.security.safe_str_cmp方法的典型用法代码示例。如果您正苦于以下问题:Python security.safe_str_cmp方法的具体用法?Python security.safe_str_cmp怎么用?Python security.safe_str_cmp使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在werkzeug.security的用法示例。


在下文中一共展示了security.safe_str_cmp方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: decode_cookie

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def decode_cookie(cookie):
    '''
    This decodes a cookie given by `encode_cookie`. If verification of the
    cookie fails, ``None`` will be implicitly returned.

    :param cookie: An encoded cookie.
    :type cookie: str
    '''
    try:
        payload, digest = cookie.rsplit(u'|', 1)
        if hasattr(digest, 'decode'):
            digest = digest.decode('ascii')  # pragma: no cover
    except ValueError:
        return

    if safe_str_cmp(_cookie_digest(payload), digest):
        return payload 
开发者ID:jpush,项目名称:jbox,代码行数:19,代码来源:flask_login.py

示例2: authenticate

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def authenticate(username, password):
    user = username_table.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user 
开发者ID:mattupstate,项目名称:flask-jwt,代码行数:6,代码来源:app.py

示例3: _check_password

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def _check_password(input_, stored):
    return safe_str_cmp(_hash_password(input_), stored) 
开发者ID:huskar-org,项目名称:huskar,代码行数:4,代码来源:user.py

示例4: reset_password

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def reset_password(username, token, new_password):
    key = _PASSWORD_RESET_KEY.format(username=username)
    expected_token = _redis_client.get(key)
    if expected_token and safe_str_cmp(token.hex, expected_token):
        _redis_client.delete(key)
        user = User.get_by_name(username)
        if user is None or user.is_application:
            abort(404, u'user {0} not found'.format(username))
        user.change_password(new_password)
    else:
        abort(403, u'token is expired')
    return user


# TODO deprecate 
开发者ID:huskar-org,项目名称:huskar,代码行数:17,代码来源:user.py

示例5: authenticate

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def authenticate(self):
        if self.header not in request.headers:
            raise errors.Unauthorized(messages.missing_auth_token)

        token = request.headers[self.header]

        for key, app_name in self.keys.items():
            if safe_str_cmp(str(token), key):
                g.authenticated_app_name = app_name
                break
        else:
            raise errors.Unauthorized(messages.invalid_auth_token) 
开发者ID:plangrid,项目名称:flask-rebar,代码行数:14,代码来源:header_api_key.py

示例6: check_csrf_token

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def check_csrf_token(self):
        cookie_name = settings.XSRF_COOKIE_NAME
        token = request.headers.get('X-XSRF-TOKEN', '')
        if not token:
            return False
        return safe_str_cmp(token, session.get(cookie_name, '')) 
开发者ID:lyft,项目名称:confidant,代码行数:8,代码来源:userauth.py

示例7: unserialize

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def unserialize(cls, string, secret_key):
        """Load the secure cookie from a serialized string.

        :param string: the cookie value to unserialize.
        :param secret_key: the secret key used to serialize the cookie.
        :return: a new :class:`SecureCookie`.
        """
        if isinstance(string, text_type):
            string = string.encode('utf-8', 'replace')
        if isinstance(secret_key, text_type):
            secret_key = secret_key.encode('utf-8', 'replace')
        try:
            base64_hash, data = string.split(b'?', 1)
        except (ValueError, IndexError):
            items = ()
        else:
            items = {}
            mac = hmac(secret_key, None, cls.hash_method)
            for item in data.split(b'&'):
                mac.update(b'|' + item)
                if b'=' not in item:
                    items = None
                    break
                key, value = item.split(b'=', 1)
                # try to make the key a string
                key = url_unquote_plus(key.decode('ascii'))
                try:
                    key = to_native(key)
                except UnicodeError:
                    pass
                items[key] = value

            # no parsing error and the mac looks okay, we can now
            # sercurely unpickle our cookie.
            try:
                client_hash = base64.b64decode(base64_hash)
            except TypeError:
                items = client_hash = None
            if items is not None and safe_str_cmp(client_hash, mac.digest()):
                try:
                    for key, value in iteritems(items):
                        items[key] = cls.unquote(value)
                except UnquoteError:
                    items = ()
                else:
                    if '_expires' in items:
                        if time() > items['_expires']:
                            items = ()
                        else:
                            del items['_expires']
            else:
                items = ()
        return cls(items, secret_key, False) 
开发者ID:jpush,项目名称:jbox,代码行数:55,代码来源:securecookie.py

示例8: validate_csrf

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def validate_csrf(data, secret_key=None, time_limit=None):
    """Check if the given data is a valid csrf token.

    :param data: The csrf token value to be checked.
    :param secret_key: A secret key for mixing in the token,
                       default is Flask.secret_key.
    :param time_limit: Check if the csrf token is expired.
                       default is True.
    """
    if not data or '##' not in data:
        return False

    try:
        expires, hmac_csrf = data.split('##', 1)
    except ValueError:
        return False  # unpack error

    if time_limit is None:
        time_limit = current_app.config.get('WTF_CSRF_TIME_LIMIT', 3600)

    if time_limit:
        try:
            expires = int(expires)
        except ValueError:
            return False

        now = int(time.time())
        if now > expires:
            return False

    if not secret_key:
        secret_key = current_app.config.get(
            'WTF_CSRF_SECRET_KEY', current_app.secret_key
        )

    if 'csrf_token' not in session:
        return False

    csrf_build = '%s%s' % (session['csrf_token'], expires)
    hmac_compare = hmac.new(
        to_bytes(secret_key),
        to_bytes(csrf_build),
        digestmod=hashlib.sha1
    ).hexdigest()

    return safe_str_cmp(hmac_compare, hmac_csrf) 
开发者ID:jpush,项目名称:jbox,代码行数:48,代码来源:csrf.py

示例9: decode_jwt

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def decode_jwt(encoded_token, secret, algorithms, identity_claim_key,
               user_claims_key, csrf_value=None, audience=None,
               leeway=0, allow_expired=False, issuer=None):
    """
    Decodes an encoded JWT

    :param encoded_token: The encoded JWT string to decode
    :param secret: Secret key used to encode the JWT
    :param algorithms: Algorithms allowed to decode the token
    :param identity_claim_key: expected key that contains the identity
    :param user_claims_key: expected key that contains the user claims
    :param csrf_value: Expected double submit csrf value
    :param audience: expected audience in the JWT
    :param issuer: expected issuer in the JWT
    :param leeway: optional leeway to add some margin around expiration times
    :param allow_expired: Options to ignore exp claim validation in token
    :return: Dictionary containing contents of the JWT
    """
    options = {}
    if allow_expired:
        options['verify_exp'] = False

    # This call verifies the ext, iat, nbf, and aud claims
    data = jwt.decode(encoded_token, secret, algorithms=algorithms, audience=audience,
                      leeway=leeway, options=options, issuer=issuer)

    # Make sure that any custom claims we expect in the token are present
    if 'jti' not in data:
        data['jti'] = None
    if identity_claim_key not in data:
        raise JWTDecodeError("Missing claim: {}".format(identity_claim_key))
    if 'type' not in data:
        data['type'] = 'access'
    if data['type'] not in ('refresh', 'access'):
        raise JWTDecodeError("Missing or invalid claim: type")
    if data['type'] == 'access':
        if 'fresh' not in data:
            data['fresh'] = False
    if user_claims_key not in data:
        data[user_claims_key] = {}
    if csrf_value:
        if 'csrf' not in data:
            raise JWTDecodeError("Missing claim: csrf")
        if not safe_str_cmp(data['csrf'], csrf_value):
            raise CSRFError("CSRF double submit tokens do not match")
    return data 
开发者ID:vimalloc,项目名称:flask-jwt-extended,代码行数:48,代码来源:tokens.py

示例10: validate_csrf

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def validate_csrf(data, secret_key=None, time_limit=None, token_key=None):
    """Check if the given data is a valid CSRF token. This compares the given
    signed token to the one stored in the session.

    :param data: The signed CSRF token to be checked.
    :param secret_key: Used to securely sign the token. Default is
        ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
    :param time_limit: Number of seconds that the token is valid. Default is
        ``WTF_CSRF_TIME_LIMIT`` or 3600 seconds (60 minutes).
    :param token_key: Key where token is stored in session for comparision.
        Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.

    :raises ValidationError: Contains the reason that validation failed.

    .. versionchanged:: 0.14
        Raises ``ValidationError`` with a specific error message rather than
        returning ``True`` or ``False``.
    """

    secret_key = _get_config(
        secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
        message='A secret key is required to use CSRF.'
    )
    field_name = _get_config(
        token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
        message='A field name is required to use CSRF.'
    )
    time_limit = _get_config(
        time_limit, 'WTF_CSRF_TIME_LIMIT', 3600, required=False
    )

    if not data:
        raise ValidationError('The CSRF token is missing.')

    if field_name not in session:
        raise ValidationError('The CSRF session token is missing.')

    s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')

    try:
        token = s.loads(data, max_age=time_limit)
    except SignatureExpired:
        raise ValidationError('The CSRF token has expired.')
    except BadData:
        raise ValidationError('The CSRF token is invalid.')

    if not safe_str_cmp(session[field_name], token):
        raise ValidationError('The CSRF tokens do not match.') 
开发者ID:liantian-cn,项目名称:RSSNewsGAE,代码行数:50,代码来源:csrf.py

示例11: unserialize

# 需要导入模块: from werkzeug import security [as 别名]
# 或者: from werkzeug.security import safe_str_cmp [as 别名]
def unserialize(cls, string, secret_key):
        """Load the secure cookie from a serialized string.

        :param string: the cookie value to unserialize.
        :param secret_key: the secret key used to serialize the cookie.
        :return: a new :class:`SecureCookie`.
        """
        if isinstance(string, text_type):
            string = string.encode('utf-8', 'replace')
        if isinstance(secret_key, text_type):
            secret_key = secret_key.encode('utf-8', 'replace')
        try:
            base64_hash, data = string.split(b'?', 1)
        except (ValueError, IndexError):
            items = ()
        else:
            items = {}
            mac = hmac(secret_key, None, cls.hash_method)
            for item in data.split(b'&'):
                mac.update(b'|' + item)
                if not b'=' in item:
                    items = None
                    break
                key, value = item.split(b'=', 1)
                # try to make the key a string
                key = url_unquote_plus(key.decode('ascii'))
                try:
                    key = to_native(key)
                except UnicodeError:
                    pass
                items[key] = value

            # no parsing error and the mac looks okay, we can now
            # sercurely unpickle our cookie.
            try:
                client_hash = base64.b64decode(base64_hash)
            except TypeError:
                items = client_hash = None
            if items is not None and safe_str_cmp(client_hash, mac.digest()):
                try:
                    for key, value in iteritems(items):
                        items[key] = cls.unquote(value)
                except UnquoteError:
                    items = ()
                else:
                    if '_expires' in items:
                        if time() > items['_expires']:
                            items = ()
                        else:
                            del items['_expires']
            else:
                items = ()
        return cls(items, secret_key, False) 
开发者ID:chalasr,项目名称:Flask-P2P,代码行数:55,代码来源:securecookie.py


注:本文中的werkzeug.security.safe_str_cmp方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。