What is Token
Token literally means a token, the function is similar to Session, it is also used to verify the user information, Token is a string generated by the server, when the client sends a login request, the server will generate a Token and return this Token to the client, as the client to request an identification of the client in the future, the client only need to bring the Token to the requesting data, without having to bring the username and password again. The difference with session is that session is the user information stored in the server to maintain the user's request status, while the Token in the server does not need to store the user's login record, each time the client sends a request to the server will bring the server to send the Token, the server receives the request to verify that the client's request with a Token, if the validation is successful, the request will be returned to the client. The server receives the request and verifies that the client's request contains the Token, and if the verification is successful, it returns the requested data to the client.
Why Token
No need to store to reduce server costs, session is the user information stored in the server, when the number of users increases the pressure on the server will also increase.
2. Defense against CSRF cross-site forgery request attacks, session is based on the cookie for user identification, cookie if intercepted, the user information is easy to leak.
3. Strong scalability, session needs to be stored can not be shared, when building more than one server, other servers can not get to the session in the verification data users can not verify the success. Token can be shared between servers so that no matter where you can access it.
It can reduce the pressure on the server and reduce frequent queries to the database.
5. Support cross-domain access
6. For mobile platform applications
Token-based authentication process
- Client requests login with username and password
- The server receives the request and starts verifying the username and password.
- After successful authentication, the server generates a Token and sends it to the client.
- Once the client receives the Token, it can be stored, either in a cookie or in Local Storage.
- When the client requests the server for the source of the credentials again, it carries the Token generated by the server and sends it to the server.
- The server receives the request and then verifies the Token carried inside the client's request, if the verification is successful, it returns the requested data to the client, otherwise the request is rejected.
Forms of Token Composition
The JWT standard Token has three parts:
header
Each token has a header, which is the header data that contains the algorithm used to tell us whether the token is encrypted or not. If the token is unencrypted, this attribute can be set to none.
payload (data)
Inside the Payload is some data to be included in the Token, the content can be defined by yourself, or you can refer to the standard fields (abbreviation: full name) iss: Issuer, sub: Subject, exp: Expiration time, iat: Issued at.
signature
Generate the Header and Playload using Base64 encoding and then add the signature characters and encrypt them with a cryptographic algorithm to get a unique signature, which can be used to prevent other people from tampering with the information in the Token.
How Django uses Token
That is, we know the composition of the Token, then we will create the next Token, the first definition of Header and Payload, header in the definition of the type of token and encryption, Payload definition of the specific content, how to username, issue time, expiration time and so on.
headers={'type':'JWT','alg':'HS256'} payloads={'iss':user,'iat':()}
respectively, encrypt headers and payloads, Django has a built-in module, you can use it to encrypt and decrypt any data, directly call dumps and load function to achieve can be headers and payloads encrypted and then encrypted and then signing.b64_encode encoding to get a string, and then use the MD5 encryption headers and payloads to generate a unique signature, and finally headers, payloads, signature combination into a Token, the following is the test code:
Next to bring the Token to the project to use the next, in order to facilitate the encryption we encapsulate into a method called directly, here I wrote Encrypt, Decrypt, Token method to encrypt and decrypt and encapsulate the Token, and finally bring the token to the data returned to the front-end, here I use JsonResponse to return to the data, inside the data I use JsonResponse to return the data, data to store the user request data, code to return the status of the request, token to store our token token.
HEADER={ 'type':'JWT', 'alg':'HS256' } def Encrypt(value): data=(value) data=signing.b64_encode(()).decode() return data def Decrypt(value): data=signing.b64_decode(()).decode() data=(data) return data def Token(headers,payloads): header=Encrypt(headers) payload=Encrypt(payloads) md5=hashlib.md5() (("%s.%s"%(header,payload)).encode()) signature=() token="%s.%s.%s"%(header,payload,signature) return token def login(request): user = ('username').strip() pwd = ('password').strip() print() # print(user,pwd) obj=(name=user) if obj: print('456789') passwd=(name=user).values('password')[0]['password'] ret=check_password(pwd,passwd) userobj=(name=user) print('ret=',ret) if ret: headers=HEADER data={'phone': , 'mail': } payloads={'iss': , 'iat':()} token=Token(headers,payloads) print(token) info={'token':token} info['code']=200 info['data']=data print(info) return JsonResponse(info) else: return HttpResponse('400') else: return HttpResponse('400')
At this point, the front-end request to log in can receive the background return info data, which contains data, token and caode, then we can get the token stored, generally stored in the client's localstorage or sessionStorage, the next time the request again the token sent to the server, the server will return the required data after successful validation. The server will return the required data after successful verification.
to this article on the use of Django Token-based authentication implementation of the article is introduced to this , more related Django Token authentication content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future !