Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use axios+PHP to realize login authentication in JWT

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to use axios+PHP to achieve login authentication in JWT, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

HTML

Our HTML structure is like this: a login form for the user to enter a user name and password, as well as a submit button; one is the display of information after a successful login.

According to the process, 1. Submit the login form, send the user name and password to the PHP backend, 2. After the back-end verification is successful, a token will be sent to the front end, 3. The front end takes this token to request user access, 4. The backend verifies toen, authenticates, and returns the corresponding result. The following js code implements 1, 3, 2 steps.

Document.querySelector ('# sub-btn'). Onclick = function () {let username = document.querySelector ('# username'). Value; let password = document.querySelector ('# password'). Value; var params = new URLSearchParams (); params.append ('user', username); params.append (' pass', password) Axios.post ('user.php?action=login', params). Then (response) = > {if (response.data.result =' success') {/ / Local storage token localStorage.setItem ('jwt', response.data.jwt); / / add token to header axios.defaults.headers.common [' XMurtoken'] = response.data.jwt Axios.get ('user.php') .then (function (response) {if (response.data.result = =' success') {document.querySelector ('# showpage'). Style.display = 'none'; document.querySelector (' # user'). Style.display = 'block'; document.querySelector (' # uname') [xss_clean] = response.data.info.data.username;} else {});} else {console.log (response.data.msg) ) .catch (function (error) {console.log (error);});}

Obviously, when the login is successful, immediately use the local storage token, then put the token in the request header header, and once again request another user information interface at the back end, and display the user information if it is successful.

If we want to log out, we don't need to request the back-end interface again, just OK the local storage at the front end.

Document.querySelector ('# logout'). Onclick = function () {localStorage.removeItem ('jwt'); document.querySelector (' # showpage'). Style.display = 'block'; document.querySelector (' # user'). Style.display = 'none';}

After a successful login, when we refresh the page (again request the page that can be accessed after login), we need to determine whether there is a token in the local storage. If there is a token, we can use it to verify whether the token is legal for the backend interface. If there is no problem, the relevant information of the user will be displayed. If the verification fails, it may be due to the past or fake token of the token.

Let jwt = localStorage.getItem ('jwt'); if (jwt) {axios.defaults.headers.common [' Xmurtoken'] = jwt; axios.get ('user.php'). Then (function (response) {if (response.data.result =' success') {document.querySelector ('# showpage'). Style.display = 'none'; document.querySelector (' # user'). Style.display = 'block'; document.querySelector (' # uname') [xss_clean] = response.data.info.data.username } else {document.querySelector ('# showpage'). Style.display = 'block'; console.log (response.data.msg);}) .catch (function (error) {console.log (error);});} else {document.querySelector (' # showpage'). Style.display = 'block';}

PHP

At the back end, we use a special JWT library: php-jwt

Install php-jwt using composer, and after receiving the login user name and password, PHP verifies whether the user name and password are correct (in actual development, the user name and password should be compared from the database. In this example, only simple verification is done for demonstration). If the user name and password are correct, then sign token. In token, we can define the issuer and expiration time of token, and return them to the front end. Note that when signing token, we need to define a key, which is a private key and cannot be told in practice.

Require 'vendor/autoload.php';use FirebaseJWTJWT;define (' KEY', '1gHuiop975cdashyex9Ud23ldsvm2Xq'); / / key $res [' result'] = 'failed';$action = isset ($_ GET [' action'])? $_ GET ['action']:''; if ($action = = 'login') {if ($_ SERVER [' REQUEST_METHOD'] = = 'POST') {$username = htmlentities ($_ POST [' user']); $password = htmlentities ($_ POST ['pass']) If ($username = = 'demo' & & $password = =' demo') {/ / user name and password are correct, then issue tokon $nowtime = time () $token = ['iss' = >' http://www.xuebuyuan.com', / / issuer 'aud' = >' http://www.xuebuyuan.com', / / jwt for users' iat' = > $nowtime, / / issue time 'nbf' = > $nowtime + 10, / / after what time the jwt is available' exp' = > $nowtime + 600, / / Expiration time-10min 'data' = > [' userid' = > 1, 'username' = > $username]] $jwt = JWT::encode ($token, KEY); $res ['result'] =' success'; $res ['jwt'] = $jwt;} else {$res [' msg'] = 'incorrect username or password!';}} echo json_encode ($res);} else {$jwt = isset ($_ SERVER ['HTTP_X_TOKEN'])? $_ SERVER [' HTTP_X_TOKEN']:'' If (empty ($jwt)) {$res ['msg'] =' You do not have permission to access.'; echo json_encode ($res); exit;} try {JWT::$leeway = 60; $decoded = JWT::decode ($jwt, KEY, ['HS256']); $arr = (array) $decoded; if ($arr [' exp'])

Users need to bring the token signed by the backend with each request, and the token,PHP in the backend acquisition request can obtain the token value by using $_ SERVER ['HTTP_X_TOKEN']. This X_TOKEN is in the header message of the request header at our front end.

Then PHP gets the token, decrypts and analyzes the token value, and returns it to the front end.

The above is all the contents of the article "how to use axios+PHP to achieve login authentication in JWT". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report