【翻译】REST framework JWT Auth(django rest framework-jwt)

JWT certified REST framework

Description link

Outline

This package provides Django REST framework of JSON Web Token authentication support.

We need to meet the conditions

  • 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)

Safety

And some of the more typical usage JWT different, this module only generates the authentication token, the user authentication token verification request DRF one API resource protection. The actual request parameters JWT itself is not included in the statement, which means they are not signed and could be tampered with. You should only through SSL / TLS public API endpoints to prevent certain types of content tampering and replay attacks.

installation

Use pipinstalled

$ pip install djangorestframework-jwt

usage

In settings.pyadded JSONWebTokenAuthenticationto Django rest framework of DEFAULT_AUTHENTICATION_CLASSESthe.

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 urls.py, add the following URL routing to allow a username and password POSTto get a token.

from rest_framework_jwt.views import obtain_jwt_token
#...

urlpatterns = [
    '',
    # ...

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

If you have a user name and password for the admin user password123, you can by doing the following in a terminal to a simple test endpoint is operating properly.

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

Alternatively, you can use Django REST framework supports all content types to get the auth token. E.g:

$ 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.

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

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

Refresh token

If JWT_ALLOW_REFRESHTrue, you can "refresh" unexpired token to get a new token has an expiration time of the update. Add the following URL format:

from rest_framework_jwt.views import refresh_jwt_token
#  ...

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

As shown below to refresh an existing token passing endpoints: {“ token”:EXISTING_TOKEN}. Please note that only the unexpired token is valid. JSON response looks normal token endpoint obtaining {“ token”:NEW_TOKEN}the same.

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

Refresh reusable token (Token 1-> 2- token> token 3), but this token chain original token (using the username / password credentials acquired) is stored as a time orig_iat. You can only be a token to refresh JWT_REFRESH_EXPIRATION_DELTA.

A typical use case is a Web application that you want the user to "log on" to the site without having to re-enter the password, or were intimidated before the token expires. Imagine, they have a one hour token, they are still just at the last minute to do something. Using a mobile device, you may be able to store username / password to get a new token, but this is not a good idea in your browser. Each time the user loads the page, you can check whether there is an existing unexpired token, if the token is about to expire, please refresh the token to extend the session. In other words, if the user is actively using your site, then they can maintain their "session (session)" effective.

Authentication token

In some micro-services architecture, authentication is handled by a single service. Other services commissioned to confirm the user has logged on to this responsibility to verify the identity of the service. JWT This usually means that the service will be received from the user is passed to the authentication service, and will be subject to wait before JWT effective protection of resources returned to the user for confirmation.

This package uses to verify endpoint supports this setting. Add the following URL format:

from rest_framework_jwt.views import verify_jwt_token

#...

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

The authentication token is transmitted to the terminal 200 returns a response, if the token is valid, the token is returned. Otherwise, it returns a 400 Bad Request (Request error) and a point out errors invalid token reason.

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

Other configurations

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,

}

The package uses JSON Web Token Python implementation PyJWT, and allows them to modify some of the options available.

JWT_SECRET_KEY

This is the key used to sign the JWT. Make sure this is safe and will not be shared or public.
The default value of the project settings.SECRET_KEY.

JWT_GET_USER_SECRET_KEY

This is a more powerful version of JWT_SECRET_KEY. It is user-defined, therefore, if the token is stolen, the owner can easily change it. Changing this value will give all the tokens given user is unavailable. Value should be a function, the user merely accepts as a parameter and returns its key.
The default is None.

JWT_PUBLIC_KEY

This is cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKeythe type of object. It passed JWT for signature verification. After setting overrides JWT_SECRET_KEY. Read the documentation for more details. Note that you must be JWT_ALGORITHMset RS256, RS384or RS512one.
The default is None.

JWT_PRIVATE_KEY

This is cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeythe type of object. It will be used to JWT's signature component is signed. After setting overrides JWT_SECRET_KEY. Read the documentation for more details. Note that you must be JWT_ALGORITHMset RS256, RS384or RS512one.
The default is None.

JWT_ALGORITHM

Possible values are any password PyJWT supported signature algorithm .
The default value “ HS256”.

JWT_VERIFY

If the password is wrong, it throws a jwt.DecodeErrortelling you. You can still be JWT_VERIFYset Falseto get the payload.
The default value True.

JWT_VERIFY_EXPIRATION

You can be JWT_VERIFY_EXPIRATIONset Falseto shut down due time to verify. If there is no expiration verification, JWT will always be there, which means that an attacker can use indefinitely leaked tokens.
The default value True.

JWT_LEEWAY

This allows you to verify the expiration time in the past but not very far. For example, if you have a payload JWT, the effective time is set to 30 seconds after creation, but you know sometimes you will be processed in 30 seconds, you can swing the time to 10 seconds, so there is a certain margin.
The default is 0seconds.

JWT_EXPIRATION_DELTA

This is an example of datetime.timedelta of Python. It will be added to datetime.utcnow () to set the expiration time.
The default value datetime.timedelta(seconds = 300)(5分钟).

JWT_AUDIENCE

This is a string, in accordance with the token aud(if present) check field.
The default value None(if present on the JWT aud, the failure).

JWT_ISSUER

This is a string token according isscheck field.
The default value is None(not checked on the JWT iss).

JWT_ALLOW_REFRESH

Enable token refresh function. From rest_framework_jwt.views.obtain_jwt_tokenthe token issuance will have orig_iata field. The default is False.

JWT_REFRESH_EXPIRATION_DELTA

Refresh is a token limiting datetime.timedeltaexample. This is the original token after token can refresh time in the future.
The default value datetime.timedelta(days = 7)(7天).

JWT_PAYLOAD_HANDLER

Specify a custom function to generate the token payload.

JWT_PAYLOAD_GET_USER_ID_HANDLER

If you store user_idthe default handler for different payload, please implement this feature in order to obtain from the payload user_id. Note: not recommended JWT_PAYLOAD_GET_USERNAME_HANDLER.

JWT_PAYLOAD_GET_USERNAME_HANDLER

If you store usernamethe default handler for different payload, please implement this function to obtain a user name from the payload.

JWT_RESPONSE_PAYLOAD_HANDLER

Responsible for controlling the response data returned after login or refreshed. Overridden to return a custom response, including, for example, a sequence of user representation. The default return JWTtoken.

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

The default is {'token': token}

JWT_AUTH_HEADER_PREFIX

You can modify the Authorization header to be sent with the token value prefix. The default value JWT. PR #. 4 introduced decision to allow the use of this package and at the same time OAuth2 the DRF.

Another common value for the token and the authorization header is Bearer.

The default value JWT.

If in addition to outside but also use the authorization header http cookieefficient transmission as token, it can be set to the string. String you set here will be used as the name of the cookie set in the response headers in the request token. Token validation process will also investigate the cookie (if set). If the request contains a header and a cookie, the "Authorization" header has priority.

The default is “None”not to set a cookie when you create a token, or do not accept at the time of authentication token.

Extended JSONWebTokenAuthentication

Now, JSONWebTokenAuthentication assume JWT will appear in the header or cookie (if configured) (see JWT_AUTH_COOKIE ). JWT specification need not do so (see: service call ). For example, JWT can appear in the query string. If the user can not set headers (e.g. src element in HTML), you need to have a function of transmitting the JWT in the query string.

In order to achieve this function, the user can write custom 身份验证:

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

Recommended BaseJSONWebTokenAuthentication, which is a new base class, no HTTP header parsing logic.

Create a new token manual

Sometimes you may need to manually generate a token, such as the token immediately returned to the user after creating an account. You can follow these steps:

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)

Guess you like

Origin www.cnblogs.com/cpl9412290130/p/11957829.html