首先了解一下什么是JWT?JWT是一个简单的PHP的第三方库,用于在PHP中编码和解码JSON WEB令牌jwt 。一般用composer来管理依赖关系 使用composer require firebase/php-jwt来安装这个库(详见 php-jwt库: )
再来介绍一下用户登录鉴权流程
1、用户使用用户名和密码来请求服务器
2、服务器验证用户信息
3、服务器通过验证生成一个token返回给客户端
4、客户端存储这个token,并在后面的每一次请求中在请求头上带上这个token
5、服务端验证这个token token正确就返回数据 token错误就返回错误信息
start 首先我们需要一个html表单用于后台的登录
<div id= “showpage” style= “display: none” >
<div class= “form-group” >
<label for= “username” > 用户名 </label>
<input type= “text” class= “form-control” id= “username” placeholder= “请输入用户名” >
</div>
<div class= “form-group” >
<label for= “password” > 密码 </label>
<input type= “password” class= “form-control” id= “password” placeholder= “请输入密码” >
</div>
<button type= “submit” id= “sub-btn” class= “btn btn-default” > 登录 </button> <br/>
<p class= “bg-warning” style= “padding: 10px;” > 演示用户名和密码都是 <code> demo </code></p>
</div>
<div id= “user” style= “display: none” >
<p> 欢迎 <strong id= “uname” >
</strong> ,您已登录, <a href= “javascript:;” id= “logout” > 退出>> </a>
</p>
</div>
// 使用axios库
<script src=”#34;></script>
<script>
let jwt = localStorage.getItem(‘jwt’);
// token 保存在localstorage里面 判断有没有token
if (jwt) {
axios.defaults.headers.common[‘X-token’] = 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’).innerHTML = 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’;
}
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’){
// 本地存储token
localStorage.setItem(‘jwt’,response.data.jwt);
// 把token存储到header里面
axios.defaults.headers.common[‘X-token’] = 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”).innerHTML = response.data.info.data.username;
}else{
}
})
}else{
console.log(response.data.msg);
}
}
.catch(function(error){
console.log(error);
});
}
</script>
服务器端
首先使用php-jwt库
使用composer安装php-jwt,接收到登录用户名和密码后,PHP验证用户名和密码是否正确,如果用户名和密码准确无误,那么就签发token,在token中,我们可以定义token的签发者、过期时间等等,并返回给前端。注意在签发token时,我们需要定义一个密钥,这个密钥是一个私钥,实际应用中是保密的不可告诉别人。
后台代码user.php
<?php
date_default_timezone_set(“PRC”); //系统使用北京时间
require ‘vendor/autoload.php’;
use \Firebase\JWT\JWT;
// 私有的密钥
define(‘KEY’, ‘1gHuiop975cdashyex9Ud23ldsvm2Xq’);
// header(‘Access-Control-Allow-Origin:*’);
$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’) { //用户名和密码正确,则签发tokon
$nowtime = time();
$token = [
‘iss’ => ‘#39;, //签发者
‘aud’ => ‘#39;, //jwt所面向的用户
‘iat’ => $nowtime, //签发时间
‘nbf’ => $nowtime + 10, //在什么时间之后该jwt才可用
‘exp’ => $nowtime + 600, //过期时间-10min
‘data’ => [
‘userid’ => 1,
‘username’ => $username
]
];
// 生成token
$jwt = JWT::encode($token, KEY);
$res[‘result’] = ‘success’;
$res[‘jwt’] = $jwt;
} else {
$res[‘msg’] = ‘用户名或密码错误!’;
}
}
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’] < time()) {
$res[‘msg’] = ‘请重新登录’;
} else {
$res[‘result’] = ‘success’;
$res[‘info’] = $arr;
}
} catch(Exception $e) {
$res[‘msg’] = ‘Token验证失败,请重新登录’;
}
echo json_encode($res);
}
用户每次请求都要带上后端签发的token,后端获取请求中的token,PHP中使用 $_SERVER[‘HTTP_X_TOKEN’] 就可以获取token值。这个 X_TOKEN 就是在我们前端的请求header头信息中。
然后PHP拿到这个token后,解密分析token值,返回给前端即可。
我们可以看到,在用户鉴权的过程中并没有使用Session或者Cookie,服务端无需存储用户会话信息。只用了一个Token串,建立前后端的验证的数据传递,实现了有效的登录鉴权过程。
celexa co jest lepsze viagra czy cialis Individual investors are pouring tens of billions ofdollars into a new generation of complex investment products, and regulators are raising concerns that not all buyersunderstand the costs and risks Take care of your mental health
Tamoxifen ICI 46 474, trans 1 4 ОІ dimethylaminoethoxyphenyl 1, 2 diphenylbut 1 ene, is the most commonly used drug for the treatment of estrogen receptor positive breast cancer and has been saving lives worldwide for the past four decades How soon after treatment can I start dyeing my hair again
In some instances, combination treatment with p MGE and an estrogen receptor antagonist may reduce tumor growth more than either treatment alone
OrdГіГ±ez Mena JM, et al
Menopause 13 4 678 91, 2006 Jul Aug
99 million shares to 1
reported that neoadjuvant with or without adjuvant chemotherapy significantly increased the risk of complications due to wound healing problems compared with that in patients treated without chemotherapy, but the analysis did not adjust for confounding effects 35
mellaril voltarene lp 75mg Luke Bartholemew, investment analyst at Aberdeen Asset Management, said that Bernanke s decision to keep the QE taps on full is a big surprise, reflecting how fragile the US recovery is and the recent cooling in data Do not make them outside of normal ranges or your chances of cancer and other problems go up
Even today, if I don t wash up b4 I go to sleep for one or two nights in a row I tend to get a small breakout
Tercyak KP, Peshkin BN, DeMarco TA, Brogan BM, Lerman C
Kravchenko J, Abernethy AP, Fawzy M, Lyerly HK
Opinions of respected authorities, based on clinical experience, descriptive studies, and case reports, or reports of expert committees
When phlegm rises to the head, due to Spleen Qi deficiency, there can be facial puffiness; when fluid remains in the body, it tends to collect around the ankles and feet 0 in the alendronate sodium cohort avoiding any doubts regarding the potential under reporting of VTE leading to death and therefore, removing the bias of not diagnosed VTE
He was chatting on phone with many friends and family because no visitors allowed
Fifty seven patients received anastrozole and RT concurrently and 126 patients received hormone therapy anastrozole or tamoxifen after completion of RT 3 UPMC Hillman Cancer Center, Magee Women s Hospital, Pittsburgh, PA 15213, USA
2000; 80 114 116
The long term efficacy of Paroxetina Ratiopharm 20 mg Comprimidos in treating obsessive compulsive disorder has been examined in three 24 week maintenance studies with relapse prevention design
It should be noted that aspirin remains a mainstay of treatment for children diagnosed with Kawasaki disease
Щ€ЩЋШ№ЩЋЩ†Щ’ Ш¬ЩЋШ§ШЁЩђШ±ЩЌ ЩЉЩЋШ±Щ’ЩЃЩЋШ№ЩЏЩ‡ЩЏ, ЩЃЩђЩЉ Ш§ЩЋЩ„Щ’ШЩЋШ§Щ…ЩђЩ„Щђ Ш§ЩЋЩ„Щ’Щ…ЩЏШЄЩЋЩ€ЩЋЩЃЩ‘ЩЋЩ‰ Ш№ЩЋЩ†Щ’Щ‡ЩЋШ§ Щ‚ЩЋШ§Щ„ЩЋ ШЈЩЋШ®Щ’Ш±ЩЋШ¬ЩЋЩ‡ЩЏ Ш§ЩЋЩ„Щ’ШЁЩЋЩЉЩ’Щ‡ЩЋЩ‚ЩђЩЉЩ‘ЩЏ, Щ€ЩЋШ±ЩђШ¬ЩЋШ§Щ„ЩЏЩ‡ЩЏ Ш«ЩђЩ‚ЩЋШ§ШЄЩЊ, Щ„ЩЋЩѓЩђЩ†Щ’ Щ‚ЩЋШ§Щ„ЩЋ Ш§ЩЋЩ„Щ’Щ…ЩЋШЩ’ЩЃЩЏЩ€ШёЩЏ Щ€ЩЋЩ‚Щ’ЩЃЩЏЩ‡ЩЏ 1 Гў The advice of the CVO chief veterinary officer is that further increasing the number of badgers culled would improve those benefits even further and enable them to accrue earlier, Гў he said
Therefore, men should take Clomid for as long as possible ideally 3 4 months before trying to conceive naturally or with the assistance of fertility treatments
Behav Neurosci 119 1023 1033
Polyhydramnios A large amount of fluid surrounding the fetus in pregnancy
BMJ 2012; 345 e6390 Therefore, tamoxifen may act as an ERО± antagonist in those estrogen sensitive hypothalamic regions to suppress physical activity in mice
35 Mamofen 10mg Tablet 0
A Immunoprecipitation assay of the interaction of Nur77 with Ku80 in MCF 7 and MCF 7 TR5 cells
Severe male infertility isn t the only reason ICSI- IVF is used
However, there is no statistical difference between 6 months and 12 months after AHP p 0
Endocrine agents are useful breast cancer treatments, but therapy duration is crucial for optimal treatment benefit 5
Cells were then washed with PBS before being metabolically quenched by transferring to dry ice
Downstaging the tumor may convert a large, inoperable tumor in selected frail patients into an operable tumor that may allow breast conserving surgery in place of mastectomy I did the research
Stewart BGIfSrdFkR 6 19 2022 The tests may be affected by menotropins for injection Pergonal, danazol Danocrine, and clomiphene Clomid