1.使用header
客户端
index.html
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<style>
.oc{
width: 200px;
height: 100px;
position: center;
background: aqua;
border :1px solid black;
}
</style>
</head>
<body>
<div class="oc"></div>
<script>
$(".oc").click(function () {
$.ajax({
url: './index.php',
data: {'name':'user'},
beforeSend: function (request) {
request.setRequestHeader("token","111111");
},
method:'POST',
success:function (data,status,request) {
alert(data);
var re=request.getResponseHeader("Authorization"); //返回返回的 header 对应的字段
console.log("auth:",re)
}
});
});
</script>
</body>
</html>
服务器端
index.php
<?php
//生成token
function generateToken(){
// 32个字符组成一组随机字符串
$randChars = rand(1,10);//getRandChars(32);
//用三组字符串,进行md5加密
$timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
$salt = 'salt';//config('secure.token_salt');
return md5($randChars.$timestamp.$salt);
}
$token = $_SERVER['HTTP_TOKEN']; //获取header里面token的信息
$service_token = generateToken(); //可以存到redis中,设置过期时间
if ($token == $service_token)
{
$data = [
'code'=>1,
'message'=>'success',
'data'=>'index',
];
}else{
header("Content-Type: text/html;charset=utf-8");
header("Authorization: ".$service_token);//把token放在设置 header里面的Authorization发送费客户端
$data = [
'code'=>1,
'message'=>'fail',
'data'=>[],
];
}
exit(json_encode($data));
效果如下所示:
2.服务器使用echo返回客户端,客户端post方式发送token到服务器端也行
class Token
{
public function getToken($code = '')
{
//return 'success';
(new TokenGet())->goCheck();
$ut = new UserToken($code);
$token = $ut->get();
return [
'token'=>$token
];
}
/*
* 第三方应用获取令牌
*/
public function getAppToken($ac='',$se='')
{
(new AppTokenGet())->goCheck();
$app = new AppToken();
$token = $app->get($ac,$se);
return [
'token'=>$token
];
}
public function verifyToken($token='')
{
if(!$token){
throw new ParameterException(['token不允许为空']);
}
$valid = TokenService::verifyToken($token);
return[
'isValid'=>$valid
];
}
}
tokenservice
class Token
{
public static function generateToken(){
// 32个字符组成一组随机字符串
$randChars = getRandChars(32);
//用三组字符串,进行md5加密
$timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
$salt = config('secure.token_salt');
return md5($randChars.$timestamp.$salt);
}
public static function getCurrentTokenVar($key)
{
$token = Request::instance()->header('token');
$vars = Cache::get($token);
if(!$vars)
{
throw new TokenException();
}else{
if(!is_array($vars))
{
$vars = json_decode($vars,true);
}
if(array_key_exists($key,$vars))
{
return $vars[$key];
}else{
throw new Exception('尝试获取的Token变量不存在');
}
}
}
public static function verifyToken($token)
{
$exits = Cache::get('token');
if($exits){
return true;
}else{
return false;
}
}
}