Author: Little potato
Blog Park: www.cnblogs.com/HouJiao/
The Denver nuggets: juejin. Cn/user / 243617…
preface
Recently, I need to make a login authentication function, so I want to make a record of the whole process, so that I can check back in the future. Meanwhile, I hope to give some reference to students who have the same problem with me.
Since authentication is a back-end feature, my unprofessional front-end will not delve too deeply into implementing this feature. Therefore, there is no excessive principle in the recording process, focusing on recording the implementation process and the problems encountered in the process as well as solutions.
If you do not understand the principle of the front and back end process of login, you can do a little homework first, or directly look at my entire operation and results, after reading will start from the results and phenomena, in order to understand and learn the login authentication principle will be easier.
Initial environment introduction
The front frame
Framework: Vue HTTP library: AXIos
The back-end project
Backend framework: Python-based Django Framework WEB API: REST-Framework server: centos database: PostgreSQL Python version: 2.7.5 Django version: 1.10.1
A few notes on back-end databases
The database usesPostgreSQL
, and the database table has been synchronized, the command is:python manage.py migrate
.
Generated after the database is synchronized10
Related data sheets.
Of interest is the auth_user table, which is the user table generated by the Django framework and used later to store user information.
Let’s take a look at the table structure.
There is no data in the table.
Next we create a user for later login tests: Python manage.py createsuperuser
User created successfully, this time to query the data table, there is a user information.
The next step is the implementation of login authentication.
Back-end Django project configuration
Django login authentication configuration
First we need to configure the login authentication APP in the INSTALLED_APPS file of setting.py.
INSTALLED_APPS = [
...
'rest_framework.authtoken'
]
Copy the code
Set a global authentication scheme
The global authentication scheme is then configured in setting.py.
Set the global authentication scheme
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication'.# token authentication)}Copy the code
Database synchronization
Database synchronization is required when the above configuration is complete:python manage.py migrate
View the database here:
An additional data table named authToKEN_token is found, which is the data table related to user authentication.
A simple test
We have configured the global authentication mode, so it stands to reason that now anyone accesses one of the back endsAPI
It’s going to appear as thetaHTTP 401 is not authorized
That’s a mistake. Let’s try it.
It turned out that the request still worked. There is a problem with the global authentication scheme configuration of setting. The correct configuration is
REST_FRAMEWORK = {'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',),'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication', # token authentication)}Copy the code
DEFAULT_PERMISSION_CLASSES is a user permission configuration that allows unlimited access if not configured, regardless of whether our requests are authenticated or unauthenticated.
This can be seen in 👉 official documentation
What about adding this authentication, before going to the request API.
Finally, the server returns401
, the user authentication fails.
Take a second test after some thought
Then I remembered the new IsAuthenticated authorization configuration, so I modified the setting.
REST_FRAMEWORK = {'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), # 'DEFAULT_AUTHENTICATION_CLASSES': (# 'rest_framework. Authentication. TokenAuthentication', # # token authentication)}Copy the code
That is, global user authentication is annotated and permission authentication is preserved to test how this global authorization configuration affects the request.
We find that the API returns 403, which is a problem with access permissions.
In any case, TokenAuthentication alone does not work, and the official documentation makes it clear that if DEFAULT_PERMISSION_CLASSES is not configured, users will be allowed unlimited access regardless of whether our requests are authenticated or unauthenticated.
Therefore, if user authentication is required, it must also be matched with permission authentication, user authentication will take effect.
This is just an attempt on my part
The backend Django project implements the login API
Next, we implement the back-end login interface
Create a new app
django-admin startapp userAuth
Write login logic in views.py
# -*- coding: utf-8 -*-
# Create your views here.
from django.contrib import auth
from rest_framework.permissions import AllowAny
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes, permission_classes
@api_view(['POST'])
@permission_classes((AllowAny,))
@authentication_classes(())
def login(request) :
Login "" "" ""
result = True
errorInfo = u''
detail = {}
data = request.data
username = data.get('username')
password = data.get('password')
# Call Django for user authentication
# proves successful, the user returns < class 'django. Contrib. Auth. Models. User' >
User returns None
user = auth.authenticate(username=username, password=password)
print "user",user
if user == None:
result = False
errorInfo = U 'Wrong username or password'
return Response({"result": result, "detail": detail, "errorInfo": errorInfo})
The user name and password are successfully verified
If there is no token, the user will be created and the token will be returned when the user logs in for the first time
try:
tokenObj = Token.objects.get(user_id=user.id)
except Exception as e:
# Token does not exist indicates first login
tokenObj = Token.objects.create(user=user, token=token)
# Get token string
token = tokenObj.key
return Response({"result": result, "detail": {'token': token}, "errorInfo": errorInfo})
Copy the code
The simple code logic for logging in is written.
Before that, let’s take a look at the previously generated data table authToken_token for user authentication.
For the moment, there is no record, and then enter the user name and password on the login screen of the product.
The user name and password are the admin account created using the Python manage.py createsuperuser command
Since this is the first login, creating a token for the user, authToKEN_token, generates a record.
Here is a look at the authToken_token data table after I login successfully.
Front-end logon logic processing
Finally, regarding the logic of the front-end VUE, let’s first look at the methods logic of the login page.
login: function(){
axios.post(url, this.loginForm).then(response= >{
const {result, detail, errorInfo} = response.data;
if(result == true) {// Login succeeded
/ / set the token
localStorage.setItem('token', detail.token);
// Jump to the page
this.$router.push('/certMake');
}else{
this.$message({
showClose: true.message: errorInfo,
type: 'error'}); }}); }Copy the code
You can see that after successful login, I use localStorage to store the token locally.
We then need to set this token to the request header when accessing other apis.
But before we do that, let’s take a lookAPI
Does not addtoken
The result of.
The token information is then added to the request header.
// Other module requests
getCertList: function(){
const url = '/api/cert/certManage/certList';
// Obtain the token maintained during login from localStorage
const auth = 'Token ' + localStorage.getItem('token');
const header = {'Authorization':auth}
axios.get(url, {'headers': header}).then(response= >{
console.log(response.data);
const {result, detail, errorInfo} = response.data;
if(result == true) {this.certList = detail.certList;
}else{
this.$message({
showClose: true.message: errorInfo,
type: 'error'}); }}); }Copy the code
Then re-request the above API.
You can see that the token has been added to the request header and the status code of the response is 200.
That means our login page has been successful.
conclusion
This article isn’t really that simple (actually I didn’t know what to do when I tried 🔥), but there are some features that need to be improved.
The next article will sort out the following points:
Optimization of AXIOS: request encapsulation, encapsulation of authentication information Settings 2. Logout 3. Example Set the token expiration timeCopy the code
Refer to the article
👉 Django-REst-Framework official documentation # Permission document 👉 Django-REst-Framework official documentation # Authorization document
Write in the last
If this article helps you, ❤️ follow + like + favorites + comment + forward ❤️ to encourage the author
Article public number first, focus on unknown treasure program yuan for the first time to get the latest article
Ink ❤ ️ ~