In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "Python Web framework Django how to use jwt to obtain user information". In daily operation, I believe that many people have doubts about how Python Web framework Django uses jwt to obtain user information. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "Python Web framework Django how to use jwt to obtain user information". Next, please follow the editor to study!
Undefined
Jwt:json web token
After the user registers and logs in, the user login status is recorded. We can use cookie and session to maintain the state, cookie is stored on the client side, security is low, session is stored on the server side, and security is high, but in the distributed architecture, session can not be synchronized, so we use jwt to verify the interface security.
Composition: head load visa
The Jwt server does not need to store the token string, and the user requests with the hash-encrypted and base64-encoded string. The server judges the user information and expiration time by identifying the token value, so it is impossible to cancel the token or change the token permission during the use period.
Installation and configuration of jwt
# install pip install djangorestframework-jwtFrom rest_framework_jwt.authentication import JSONWebTokenAuthenticationSettings.pyINSTALLED_APPS = [''rest_framework.authtoken',''] # 2, configure jwt authentication # # REST_FRAMEWORK = {# authentication 'DEFAULT_AUTHENTICATION_CLASSES': (' rest_framework_jwt.authentication.JSONWebTokenAuthentication' 'rest_framework.authentication.SessionAuthentication',' rest_framework.authentication.BasicAuthentication',),} import datetime JWT_AUTH = {'JWT_AUTH_HEADER_PREFIX':' JWT', 'JWT_EXPIRATION_DELTA': datetime.timedelta (days=1),} AUTH_USER_MODEL='app.User' # specifies to use model User in APP for authentication
In django, we use the built-in User table as the login function
From rest_framework_jwt.views import obtain_jwt_token # returns tokenurlpatterns = [re_path (obtain_jwt_token,name='login') after verifying password, # user returns token after login]
The front end gets the token and setitem
Var token = 'JWT' + data.tokenlocalStorage.setItem ('token', token)
In our encapsulated interceptor, there are request interceptor and response interceptor, which need to get the token each time the request is initiated.
Import Axios from 'axios'import {Toast} from' vant';import URLS from'.. /.. / config/urls' / / 1, create a new axios instance with custom configuration const instance = Axios.create ({baseURL: URLS.API_URL, responseType: 'json',}) / / 2. Add a request interceptor: this interceptor is called every time a request is sent. Add authentication tokeninstance.interceptors.request.use (config = > {/ / add authentication token before sending the request, console.log (localStorage.getItem ('token')) config.headers.Authorization = localStorage.getItem (' token')) # get token / / config.headers.Authorization = sessionStorage.getItem ('token') return config}, err = > {return Promise.reject (err)}); / / 3. Response interceptor instance.interceptors.response.use (response = > {if (response.status = 200) {return Promise.resolve (response);} else {return Promise.reject (response)) }}, / / if the server status code is not 200, error = > {if (error.response.status) {switch (error.response.status) {/ / 401: if you are not logged in / / if you are not logged in, jump to the login page and return to the current page with the path of the current page / / after the login is successful. This step needs to be done on the login page. Case 401: router.replace ({path:'/ login', query: {redirect: router.currentRoute.fullPath}}); break / / token Expiration / / Log Expiration prompt the user / / clear the local token and clear the token object in the vuex / / Redirect login page case 403: Toast ({message: 'login expired, please log in again', duration: 1000, forbidClick: login}) / / clear token localStorage.removeItem ('token'); store.commit (' loginSuccess', null) / / Jump to the login page, and pass the page to be viewed by fullPath. After successful login, setTimeout () = > {router.replace ({path:'/ login', query: {redirect: router.currentRoute.fullPath}});}, 1000) Break; / / 404 request does not exist case: Toast ({message: 'network request does not exist', duration: 1500, forbidClick: true}); break / / other errors, directly throw the error prompt default: Toast ({message: error.response.data.message, duration: 1500, forbidClick: true});} return Promise.reject (error.response);}}); export default instance
In this way, the security authentication of jwt interface is completed.
So how do we get jwt and extract the information we need in the python backend?
From rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.views import exception_handlerfrom rest_framework_jwt.utils import jwt_decode_handler# acquires the logged-in user token = request.META.get ('HTTP_AUTHORIZATION') [4:] token_user = jwt_decode_handler (token) user_id = token_user [' user_id'] # this method does not need to encapsulate getitem token at the front end or before Send token to the end and get .vuevar formdata = {id: this.$route.params.id / / get / id / / this.$route.query.subid get? subid=id token: localStorage.getItem ('token') } postCreate (formdata) .then (resp= > {console.log (resp) alert (resp.mes)}) .catch (err= > {alert (err) console.log (err)})} python views.pydef post (self) Request): data = request.data # get the data of the post method # print (data) token = data.get ('token') [4:] toke_user = jwt_decode_handler (token) user_id = toke_user [' user_id'] def get (self,request): data = request.query_params # get the parameters of the get method so far The study on "how the Python Web framework Django uses jwt to get user information" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.