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


Python jwt.encode方法代码示例

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


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

示例1: issue

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def issue(self, subject, expires=2592000, **claims):
        """
        Issue a signed token.

        The subject is mandatory and sets the JWT "sub" claim.  The expiration
        time can be None (no expiration) or a time in seconds from the issue
        time after which the token will expire.  The default is 30 days
        (2592000 seconds).
        """
        data = claims
        data['iat'] = int(time.time())
        data['iss'] = nexus.core.info.pdid
        data['sub'] = subject
        if expires is not None:
            data['exp'] = int(time.time()) + expires
        return jwt.encode(data, self.secret, algorithm='HS256') 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:18,代码来源:token_manager.py

示例2: encode_jwt

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def encode_jwt(payload, headers=None):
    """
    :type payload: dict
    :type headers: dict, None
    :rtype: str
    """
    # RS256 in default, because hardcoded legacy
    algorithm = getattr(settings, 'JWT_ENC_ALGORITHM', 'RS256')

    private_key_name = 'JWT_PRIVATE_KEY_{}'.format(payload['iss'].upper())
    private_key = getattr(settings, private_key_name, None)
    if not private_key:
        raise ImproperlyConfigured('Missing setting {}'.format(
            private_key_name))
    encoded = jwt.encode(payload, private_key, algorithm=algorithm,
                         headers=headers)
    return encoded.decode("utf-8") 
开发者ID:Humanitec,项目名称:django-oauth-toolkit-jwt,代码行数:19,代码来源:utils.py

示例3: create_jwt

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def create_jwt(self, expiration=60):
        """
        Creates a signed JWT, valid for 60 seconds by default.
        The expiration can be extended beyond this, to a maximum of 600 seconds.

        :param expiration: int
        :return:
        """
        now = int(time.time())
        payload = {
            "iat": now,
            "exp": now + expiration,
            "iss": self.integration_id
        }
        encrypted = jwt.encode(
            payload,
            key=self.private_key,
            algorithm="RS256"
        )

        if atLeastPython3:
            encrypted = encrypted.decode('utf-8')

        return encrypted 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:26,代码来源:MainClass.py

示例4: generate_authorization_code

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def generate_authorization_code(client_id, redirect_url):
  #f = Fernet(KEY)
  authorization_code = f.encrypt(json.dumps({
    "client_id": client_id,
    "redirect_url": redirect_url,
  }).encode())

  authorization_code = base64.b64encode(authorization_code, b'-_').decode().replace('=', '')

  expiration_date = time.time() + CODE_LIFE_SPAN

  authorization_codes[authorization_code] = {
    "client_id": client_id,
    "redirect_url": redirect_url,
    "exp": expiration_date
  }

  return authorization_code 
开发者ID:michaelawyu,项目名称:auth-server-sample,代码行数:20,代码来源:auth.py

示例5: make_auth_header

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def make_auth_header(installation_id):
    utcnow = datetime.utcnow() + timedelta(seconds=-5)
    duration = timedelta(seconds=30)
    payload = {
        "iat": utcnow,
        "exp": utcnow + duration,
        "iss": 2510
    }
    pem = get_private_pem()
    encoded = jwt.encode(payload, pem, "RS256")
    headers = {
        "Authorization": "Bearer " + encoded.decode("utf-8"),
        "Accept": "application/vnd.github.machine-man-preview+json"
        }
    
    auth_url = "https://api.github.com/installations/{}/access_tokens".format(installation_id)
    r = requests.post(auth_url, headers=headers)

    if not r.ok:
        print(r.json()["message"])
        r.raise_for_status()
    token = r.json()["token"]
    return {
        "Authorization": "token {}".format(token)
    } 
开发者ID:chakki-works,项目名称:typot,代码行数:27,代码来源:env.py

示例6: _jwt_for_user

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def _jwt_for_user(user_id: int):
        """
        Gets the HS256-encoded JWT for a Discord user ID.

        :param int user_id: The Discord user ID.
        :returns str: The JWT.
        """
        now = int(time.time())

        jwt_body = {
            "external_user_id": str(user_id),
            "iat": now,
            "exp": now + EXPIRY_SECONDS,
            "aud": AUDIENCE,
            "iss": ISSUER
        }

        return jwt.encode(jwt_body, MY_SECRET, algorithm='HS256').decode()  # return as a str, not bytes 
开发者ID:avrae,项目名称:avrae,代码行数:20,代码来源:ddb.py

示例7: generate_password_reset_token

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def generate_password_reset_token(username):
    delta = timedelta(hours=config.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
    now = datetime.utcnow()
    expires = now + delta
    exp = expires.timestamp()
    encoded_jwt = jwt.encode(
        {
            "exp": exp,
            "nbf": now,
            "sub": password_reset_jwt_subject,
            "username": username,
        },
        config.SECRET_KEY,
        algorithm="HS256",
    )
    return encoded_jwt 
开发者ID:tiangolo,项目名称:full-stack-fastapi-couchbase,代码行数:18,代码来源:utils.py

示例8: generate_access_token

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def generate_access_token(self, client_id, client_secret, code):
        """
        GenerateAccessToken will exchange the authorization code for an access token and refresh tokens.
        :param client_id: DocuSign OAuth Client Id(AKA Integrator Key)
        :param client_secret: The secret key you generated when you set up the integration in DocuSign Admin console.
        :param code: The authorization code
        :return: OAuthToken object
        """
        if not client_id or not client_secret or not code:
            raise ArgumentException
        url = "https://{0}/oauth/token".format(self.oauth_host_name)
        integrator_and_secret_key = b"Basic " + base64.b64encode(str.encode("{}:{}".format(client_id, client_secret)))
        headers = {
            "Authorization": integrator_and_secret_key.decode("utf-8"),
            "Content-Type": "application/x-www-form-urlencoded",
        }
        post_params = self.sanitize_for_serialization({
            "grant_type": "authorization_code",
            "code": code
        })
        response = self.rest_client.POST(url, headers=headers, post_params=post_params)

        return self.deserialize(response=response, response_type=OAuthToken) 
开发者ID:docusign,项目名称:docusign-python-client,代码行数:25,代码来源:api_client.py

示例9: _encode_jwt

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def _encode_jwt(additional_token_data, expires_delta, secret, algorithm,
                json_encoder=None, headers=None):
    uid = _create_csrf_token()
    now = datetime.datetime.utcnow()
    token_data = {
        'iat': now,
        'nbf': now,
        'jti': uid,
    }
    # If expires_delta is False, the JWT should never expire
    # and the 'exp' claim is not set.
    if expires_delta:
        token_data['exp'] = now + expires_delta
    token_data.update(additional_token_data)
    encoded_token = jwt.encode(token_data, secret, algorithm,
                               json_encoder=json_encoder, headers=headers).decode('utf-8')
    return encoded_token 
开发者ID:vimalloc,项目名称:flask-jwt-extended,代码行数:19,代码来源:tokens.py

示例10: encode_TFA_token

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def encode_TFA_token(self, valid_days=1):
        """
        Generates the Auth Token for TFA
        :return: string
        """
        try:

            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=valid_days, seconds=30),
                'iat': datetime.datetime.utcnow(),
                'id': self.id
            }

            return jwt.encode(
                payload,
                current_app.config['SECRET_KEY'],
                algorithm='HS256'
            )
        except Exception as e:
            return e 
开发者ID:teamsempo,项目名称:SempoBlockchain,代码行数:22,代码来源:user.py

示例11: encode_auth_token

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def encode_auth_token(self):
        """
        Generates the Auth Token
        :return: string
        """
        try:

            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7, seconds=0),
                'iat': datetime.datetime.utcnow(),
                'id': self.id,
                'roles': self.roles
            }

            return jwt.encode(
                payload,
                current_app.config['SECRET_KEY'],
                algorithm='HS256'
            )
        except Exception as e:
            return e 
开发者ID:teamsempo,项目名称:SempoBlockchain,代码行数:23,代码来源:user.py

示例12: test_04_check_jwt_username_in_audit

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def test_04_check_jwt_username_in_audit(self):
        # Here we check, if the username from the trusted JWT appears in the audit log.
        # This means that the username is read in the correct way from the JWT and
        # also used in the correct way for policy handling.
        with open("tests/testdata/jwt_sign.key", "r") as f:
            key = f.read()

        auth_token = jwt.encode(payload={"role": "user", "username": "userA", "realm": "realm1",
                                         "resolver": "resolverX"},
                                key=key,
                                algorithm="RS256")

        # The authenticated but non-existing user tries for fetch his tokens
        with self.app.test_request_context('/token/',
                                           method='GET',
                                           headers={"Authorization": auth_token}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 400, res)

        # We see the user from the trusted JWT in the audit log.
        ae = self.find_most_recent_audit_entry(action="GET /token/")
        self.assertEqual(ae.get("user"), u"userA") 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:24,代码来源:test_api_lib_utils.py

示例13: get_app_jwt

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def get_app_jwt(self) -> str:
        """Returns JWT authenticating as this app"""
        now = int(time.time())
        expires, token = self._jwt
        if not expires or expires < now + 60:
            expires = now + self.JWT_RENEW_PERIOD
            payload = {
                'iat': now,
                'exp': expires,
                'iss': self.app_id,
            }
            token_utf8 = jwt.encode(payload, self.app_key, algorithm="RS256")
            token = token_utf8.decode("utf-8")
            self._jwt = (expires, token)
            msg = "Created new"
        else:
            msg = "Reusing"

        logger.debug("%s JWT valid for %i minutes", msg, (expires - now)/60)
        return token 
开发者ID:bioconda,项目名称:bioconda-utils,代码行数:22,代码来源:githubhandler.py

示例14: issue_token

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def issue_token(user_identifier: str) -> str:
    """签发指定用户名的JWT token"""
    from everyclass.server.utils.config import get_config
    config = get_config()

    payload = {"username": user_identifier}
    token = jwt.encode(payload, config.JWT_PRIVATE_KEY, algorithm='RS256')

    return token.decode('utf8') 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:11,代码来源:service.py

示例15: test_valid_token_header

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import encode [as 别名]
def test_valid_token_header(self):
        claims = {'iss': 'https://domain.com/token',
                  'aud': 'aud1',
                  'sub': '0123456789abcdef01234567'}
        token = jwt.encode(claims, 'secret')
        auth = [('Authorization', 'Bearer {}'.format(token.decode('utf-8')))]
        r = self.test_client.get('/foo', headers=auth)
        self.assertEqual(r.status_code, 200) 
开发者ID:rs,项目名称:eve-auth-jwt,代码行数:10,代码来源:test.py


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