REST framework JWT Auth 【翻译版】

REST framework JWT Auth

JSON Web Token Authentication support for Django REST Framework

【对Django REST框架的JSON Web令牌身份验证支持】


Overview

This package provides JSON Web Token Authentication support for Django REST framework.

If you want to know more about JWT, check out the following resources:

【这个包为Django REST框架提供JSON Web令牌身份验证支持。

如果您想更多地了解JWT,请查看以下参考资料:】

Requirements【 要求】

  • Python (2.7, 3.3, 3.4, 3.5)
  • Django (1.8, 1.9, 1.10)
  • Django REST Framework (3.0, 3.1, 3.2, 3.3, 3.4, 3.5)

Security【安全】

Unlike some more typical uses of JWTs, this module only generates authentication tokens that will verify the user who is requesting one of your DRF protected API resources. The actual request parameters themselves are not included in the JWT claims which means they are not signed and may be tampered with. You should only expose your API endpoints over SSL/TLS to protect against content tampering and certain kinds of replay attacks.

【与一些更典型的JWTs使用不同,这个模块只生成身份验证令牌,用于验证请求DRF受保护的API资源的用户。JWT声明中没有包含实际的请求参数本身,这意味着它们没有签名,可能会被篡改。您应该只在SSL/TLS上公开API端点,以防止内容篡改和某些类型的重播攻击。】

Installation【安装】

Install using pip

$ pip install djangorestframework-jwt

Usage【使用】

In your settings.py, add JSONWebTokenAuthentication to Django REST framework’s DEFAULT_AUTHENTICATION_CLASSES.

【在你的设置。py,将JSONWebTokenAuthentication添加到Django REST框架的DEFAULT_AUTHENTICATION_CLASSES中。】

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

In your urls.py add the following URL route to enable obtaining a token via a POST included the user’s username and password.

【py在URL .py中添加以下URL路由,以允许通过包含用户用户名和密码的POST获取令牌。】

from rest_framework_jwt.views import obtain_jwt_token
#...

urlpatterns = [
    '',
    # ...

    url(r'^api-token-auth/', obtain_jwt_token),
]

You can easily test if the endpoint is working by doing the following in your terminal, if you had a user created with the username admin and password password123.

【如果您的用户名是admin,密码是password123,那么您可以通过在终端中执行以下操作轻松地测试端点是否工作。】

$ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/

Alternatively, you can use all the content types supported by the Django REST framework to obtain the auth token. For example:

【或者,您可以使用Django REST框架支持的所有内容类型来获得认证令牌。例如:】

$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/

Now in order to access protected api urls you must include the Authorization: JWT <your_token> header.

【现在,为了访问受保护的api url,您必须包含授权:JWT <your_token> header。】

$ curl -H "Authorization: JWT <your_token>" http://localhost:8000/protected-url/

Refresh Token【刷新令牌】

If JWT_ALLOW_REFRESH is True, non-expired tokens can be “refreshed” to obtain a brand new token with renewed expiration time. Add a URL pattern like this:

【如果JWT_ALLOW_REFRESH为真,则可以“刷新”未过期的令牌,以获得具有更新过期时间的全新令牌。添加这样的URL模式:】

    from rest_framework_jwt.views import refresh_jwt_token
    #  ...

    urlpatterns = [
        #  ...
        url(r'^api-token-refresh/', refresh_jwt_token),
    ]

Pass in an existing token to the refresh endpoint as follows: {"token": EXISTING_TOKEN}. Note that only non-expired tokens will work. The JSON response looks the same as the normal obtain token endpoint {"token": NEW_TOKEN}.

【将一个现有的令牌传递给刷新端点,如下所示:{“token”: EXISTING_TOKEN}。请注意,只有未过期的令牌才能工作。JSON响应看起来与普通的获取令牌端点{“token”:NEW_TOKEN}相同。】

$ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-refresh/

Refresh with tokens can be repeated (token1 -> token2 -> token3), but this chain of token stores the time that the original token (obtained with username/password credentials), as orig_iat. You can only keep refreshing tokens up to JWT_REFRESH_EXPIRATION_DELTA.

【可以重复使用令牌进行刷新(令牌1 ->令牌2 ->令牌3),但是这个令牌链将原始令牌(通过用户名/密码凭证获得)的时间存储为orig_iat。您只能将刷新令牌保持到JWT_REFRESH_EXPIRATION_DELTA。】

A typical use case might be a web app where you’d like to keep the user “logged in” the site without having to re-enter their password, or get kicked out by surprise before their token expired. Imagine they had a 1-hour token and are just at the last minute while they’re still doing something. With mobile you could perhaps store the username/password to get a new token, but this is not a great idea in a browser. Each time the user loads the page, you can check if there is an existing non-expired token and if it’s close to being expired, refresh it to extend their session. In other words, if a user is actively using your site, they can keep their “session” alive.

【典型的用例可能是web应用程序,您希望让用户“登录”站点,而不需要重新输入密码,或者在令牌过期之前被意外踢出站点。假设他们有一个1小时的令牌,并且在最后一刻还在做某事。使用移动设备,您也许可以存储用户名/密码以获得新的令牌,但在浏览器中这不是一个好主意。每次用户加载页面时,您可以检查是否存在现有的未过期令牌,如果该令牌接近过期,则刷新该令牌以扩展其会话。换句话说,如果用户正在积极使用您的站点,他们可以保持其“会话”活动。】

Verify Token【验证令牌】

In some microservice architectures, authentication is handled by a single service. Other services delegate the responsibility of confirming that a user is logged in to this authentication service. This usually means that a service will pass a JWT received from the user to the authentication service, and wait for a confirmation that the JWT is valid before returning protected resources to the user.

【在一些微服务体系结构中,身份验证由单个服务处理。其他服务委托确认用户登录到此身份验证服务的责任。这通常意味着服务将从用户接收到的JWT传递给身份验证服务,并在将受保护的资源返回给用户之前等待JWT有效的确认。】

This setup is supported in this package using a verification endpoint. Add the following URL pattern:

【此包使用验证端点支持此设置。添加以下URL模式:】

    from rest_framework_jwt.views import verify_jwt_token

    #...

    urlpatterns = [
        #  ...
        url(r'^api-token-verify/', verify_jwt_token),
    ]

Passing a token to the verification endpoint will return a 200 response and the token if it is valid. Otherwise, it will return a 400 Bad Request as well as an error identifying why the token was invalid.

【将一个令牌传递给验证端点将返回一个200响应,如果该令牌有效,则返回该令牌。否则,它将返回一个400错误的请求以及一个错误,该错误标识令牌无效的原因。】

$ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-verify/

Additional Settings【附加的设置】

There are some additional settings that you can override similar to how you’d do it with Django REST framework itself. Here are all the available defaults.

【还有一些额外的设置可以覆盖,类似于使用Django REST框架本身所做的设置。以下是所有可用的默认值。】

JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
    'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
    'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
    'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_RESPONSE_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_response_payload_handler',

    'JWT_SECRET_KEY': settings.SECRET_KEY,
    'JWT_GET_USER_SECRET_KEY': None,
    'JWT_PUBLIC_KEY': None,
    'JWT_PRIVATE_KEY': None,
    'JWT_ALGORITHM': 'HS256',
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
    'JWT_AUDIENCE': None,
    'JWT_ISSUER': None,

    'JWT_ALLOW_REFRESH': False,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_AUTH_COOKIE': None,

}

This packages uses the JSON Web Token Python implementation, PyJWT and allows to modify some of it’s available options.

【这个包使用JSON Web Token Python实现PyJWT,并允许修改它的一些可用选项。】

JWT_SECRET_KEY【JWT密钥】

This is the secret key used to sign the JWT. Make sure this is safe and not shared or public.

Default is your project’s settings.SECRET_KEY.

【这是用于签署JWT的密钥。确保这是安全的,不被共享或公开。

默认值是项目的settings.SECRET_KEY。】

JWT_GET_USER_SECRET_KEY【JWT获取用户密钥】

This is more robust version of JWT_SECRET_KEY. It is defined per User, so in case token is compromised it can be easily changed by owner. Changing this value will make all tokens for given user unusable. Value should be a function, accepting user as only parameter and returning it’s secret key.

Default is None.

【这是JWT_SECRET_KEY的更健壮版本。它是为每个用户定义的,因此如果令牌受到损害,可以很容易地由所有者进行更改。更改此值将使给定用户的所有令牌不可用。值应该是一个函数,只接受user作为参数并返回它的secret key。

默认是没有的。】

JWT_PUBLIC_KEY【JWT公钥】

This is an object of type cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey. It will be used to verify the signature of the incoming JWT. Will override JWT_SECRET_KEY when set. Read the documentation for more details. Please note that JWT_ALGORITHMmust be set to one of RS256, RS384, or RS512.

Default is None.

【这是一个类型为cryptography.hazmat. elements .asymmetric.rsa. rsapublickey的对象。它将用于验证传入JWT的签名。将在设置时覆盖JWT_SECRET_KEY。请注意,JWT_ALGORITHMmust被设置为RS256、RS384或RS512之一。

默认是没有的。】

JWT_PRIVATE_KEY【JWT私钥】

This is an object of type cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey. It will be used to sign the signature component of the JWT. Will override JWT_SECRET_KEY when set. Read the documentation for more details. Please note that JWT_ALGORITHM must be set to one of RS256, RS384, or RS512.

Default is None.

【这是一个类型为cryptography.hazmat. elements .asymmetric.rsa. rsaprivatekey的对象。它将用于对JWT的签名组件进行签名。将在设置时覆盖JWT_SECRET_KEY。请注意,JWT_ALGORITHM必须设置为RS256、RS384或RS512之一。

默认是没有的。】

JWT_ALGORITHM【JWT算法】

Possible values are any of the supported algorithms for cryptographic signing in PyJWT.

Default is "HS256".

【可能的值是PyJWT中支持的任何加密签名算法。

默认设置是“HS256”。】

JWT_VERIFY【JWT验证】

If the secret is wrong, it will raise a jwt.DecodeError telling you as such. You can still get at the payload by setting the JWT_VERIFY to False.

Default is True.

【如果这个秘密是错误的,它将产生一个jwt。DecodeError是这样告诉你的。您仍然可以通过将JWT_VERIFY设置为False来获得有效负载。

默认是正确的。】

JWT_VERIFY_EXPIRATION【JWT核实过期】

You can turn off expiration time verification by setting JWT_VERIFY_EXPIRATION to False. Without expiration verification, JWTs will last forever meaning a leaked token could be used by an attacker indefinitely.

Default is True.

【您可以通过将JWT_VERIFY_EXPIRATION设置为False来关闭过期时间验证。如果没有过期验证,JWTs将永远存在,这意味着泄漏的令牌可能会被攻击者无限期地使用。

默认是正确的。】

JWT_LEEWAY【JWT余地】

This allows you to validate an expiration time which is in the past but not very far. For example, if you have a JWT payload with an expiration time set to 30 seconds after creation but you know that sometimes you will process it after 30 seconds, you can set a leeway of 10 seconds in order to have some margin.

Default is 0 seconds.

【这允许您验证过期时间,这是在过去,但不是很远。例如,如果您有一个JWT有效负载,它的过期时间设置为创建后30秒,但是您知道有时您将在30秒后处理它,那么您可以设置10秒的回旋余地以获得一些余量。

默认是0秒。】

JWT_EXPIRATION_DELTA【JWT过期δ】

This is an instance of Python’s datetime.timedelta. This will be added to datetime.utcnow() to set the expiration time.

Default is datetime.timedelta(seconds=300)(5 minutes).

【这是Python的datetime.timedelta的一个实例。这将添加到datetime.utcnow()中以设置过期时间。

默认值是datetime.timedelta(秒=300)(5分钟)。】

JWT_AUDIENCE【JWT观众】

This is a string that will be checked against the aud field of the token, if present.

Default is None(fail if aud present on JWT).

【如果存在,将根据令牌的aud字段检查这个字符串。

无违约(若JWT上存在aud则失败)。】

JWT_ISSUER【JWT发行人】

This is a string that will be checked against the iss field of the token.

Default is None(do not check iss on JWT).

【这是一个字符串,将根据令牌的iss字段进行检查。

默认是None(不要在JWT上检查iss)。】

JWT_ALLOW_REFRESH【JWT允许刷新】

Enable token refresh functionality. Token issued from rest_framework_jwt.views.obtain_jwt_token will have an orig_iat field. Default is False

【启用令牌刷新功能。令牌由rest_framework_jwt.views发出。obtain_jwt_token将有一个orig_iat字段。默认的是假的】

JWT_REFRESH_EXPIRATION_DELTA【JWT刷新过期增量】

Limit on token refresh, is a datetime.timedelta instance. This is how much time after the original token that future tokens can be refreshed from.

Default is datetime.timedelta(days=7) (7 days).

【令牌刷新的限制是一个日期时间。timedelta实例。这是在原始令牌之后可以刷新未来令牌的时间。

默认值是datetime.timedelta(days=7)(7天)。】

JWT_PAYLOAD_HANDLER【JWT载荷处理程序】

Specify a custom function to generate the token payload

【指定一个自定义函数来生成令牌有效负载】

JWT_PAYLOAD_GET_USER_ID_HANDLER【JWT负载获取用户ID处理程序】

If you store user_id differently than the default payload handler does, implement this function to fetch user_id from the payload. Note: Will be deprecated in favor of JWT_PAYLOAD_GET_USERNAME_HANDLER.

【如果您存储user_id的方式与默认有效负载处理程序的方式不同,则实现此函数从有效负载获取user_id。注意:不赞成使用JWT_PAYLOAD_GET_USERNAME_HANDLER。】

JWT_PAYLOAD_GET_USERNAME_HANDLER【JWT负载获取用户名处理程序】

If you store username differently than the default payload handler does, implement this function to fetch username from the payload.

【如果您存储用户名的方式与默认有效负载处理程序的方式不同,则实现此函数从有效负载获取用户名。】

JWT_RESPONSE_PAYLOAD_HANDLER【JWT响应负载处理程序】

Responsible for controlling the response data returned after login or refresh. Override to return a custom response such as including the serialized representation of the User.

Defaults to return the JWT token.

Example:

【负责控制登录或刷新后返回的响应数据。覆盖以返回自定义响应,例如包含用户的序列化表示。

默认返回JWT令牌。

例子:】

def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': UserSerializer(user, context={'request': request}).data
    }

Default is {'token': token}

JWT_AUTH_HEADER_PREFIX【JWT验证头前缀】

You can modify the Authorization header value prefix that is required to be sent together with the token. The default value is JWT. This decision was introduced in PR #4 to allow using both this package and OAuth2 in DRF.

Another common value used for tokens and Authorization headers is Bearer.

Default is JWT.

【您可以修改与令牌一起发送的授权头值前缀。默认值是JWT。这个决定是在PR #4中引入的,它允许在DRF中同时使用这个包和OAuth2。

用于令牌和授权标头的另一个常见值是承载。

默认是JWT。】

JWT_AUTH_COOKIE【JWT AUTH饼干】

You can set this to a string if you want to use http cookies in addition to the Authorization header as a valid transport for the token. The string you set here will be used as the cookie name that will be set in the response headers when requesting a token. The token validation procedure will also look into this cookie, if set. The ‘Authorization’ header takes precedence if both the header and the cookie are present in the request.

Default is None and no cookie is set when creating tokens nor accepted when validating them.

【如果希望在授权头之外使用http cookie作为令牌的有效传输,可以将其设置为字符串。您在这里设置的字符串将用作请求令牌时在响应头中设置的cookie名称。如果设置了,令牌验证过程还将检查此cookie。如果请求中同时存在报头和cookie,则“授权”报头优先。

默认值是None,在创建令牌时没有设置cookie,在验证令牌时也没有设置cookie。】

Extending JSONWebTokenAuthentication【延长JSONWebTokenAuthentication】

Right now JSONWebTokenAuthentication assumes that the JWT will come in the header, or a cookie if configured (see JWT_AUTH_COOKIE). The JWT spec does not require this (see: Making a service Call). For example, the JWT may come in the querystring. The ability to send the JWT in the querystring is needed in cases where the user cannot set the header (for example the src element in HTML).

To achieve this functionality, the user might write a custom Authentication:

【现在,JSONWebTokenAuthentication假设JWT将出现在报头中,或者如果配置了cookie(请参见JWT_AUTH_COOKIE),那么将出现一个cookie。JWT规范不要求这样做(参见:进行服务调用)。例如,JWT可能在querystring中。在用户无法设置标题(例如HTML中的src元素)的情况下,需要在querystring中发送JWT的能力。

要实现此功能,用户可以编写自定义身份验证:】

class JSONWebTokenAuthenticationQS(BaseJSONWebTokenAuthentication):
    def get_jwt_value(self, request):
         return request.QUERY_PARAMS.get('jwt')

It is recommended to use BaseJSONWebTokenAuthentication, a new base class with no logic around parsing the HTTP headers.

【建议使用BaseJSONWebTokenAuthentication,这是一个新的基类,没有解析HTTP头的逻辑。】

Creating a new token manually【手动创建新令牌】

Sometimes you may want to manually generate a token, for example to return a token to the user immediately after account creation. You can do this as follows:

【有时您可能希望手动生成令牌,例如在帐户创建之后立即将令牌返回给用户。你可以这样做:】

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)

猜你喜欢

转载自blog.csdn.net/Python_anning/article/details/88243203
今日推荐