passport
-
按照文档搭建环境
-
生成token 返回给前台
$user = User::create($input); $success['token'] = $user->createToken('MyToken')->accessToken; return response()->json(['success'=>$success], $this->successStatus);
3 . 在需要防护的api外加上中间件
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'Api\UserController@details');
});
4 . 前台请求接口的时候, 设置请求头,并且将token加到请求头中
var $accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImYxZDdjYzY3ZWRhYzM1MGM3YjY0OGRjN2U0NjM3Y2Q5MWI1YjYxZDc0ZmI2MDJmNTJmZDE2NTU5YzUxYWUwMjk0OWIzNDQ5MzcyNjJhZTgxIn0.eyJhdWQiOiIxIiwianRpIjoiZjFkN2NjNjdlZGFjMzUwYzdiNjQ4ZGM3ZTQ2MzdjZDkxYjViNjFkNzRmYjYwMmY1MmZkMTY1NTljNTFhZTAyOTQ5YjM0NDkzNzI2MmFlODEiLCJpYXQiOjE0OTczMTk0MzIsIm5iZiI6MTQ5NzMxOTQzMiwiZXhwIjoxNTI4ODU1NDMyLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.U1ElWxuQTteai1o94YCax_zmfBSr9M0y5TSfJT-0EYAWxqf6r5ljOIFXWCgLLxhGNJxzeUD0HxUAm6wjhv6mB0_V073NSXa4IBwsISoEUMjzFBkNZ3OMft4Q9MX1bwTqNP30RPXGlREhLtCMW8dmFkLW2lRXj56SJS-zeG3EIKq6b7nw8-Lla5eFoBNb2oksDDbAA7SXBLBQD0vw3MdKsUYPs2asLYDaNv7n4GA5X2U1dRnnmAGIUpoqOJJdK9tvGRKSb4yaUhHy_NOAOhzEsDG2U_tKYRrH2IL5E-MWxFb-qZNVMctLspn3FF0ATeNgQPSoQFOZoZawrt7iI60bFEvmHl4Hl6k-fUZzIaCpkD_Bl_K0Jmx_8UQE-eJXsmKH-RAhhY2eGOesHeQlK6KR6SAOa5gPB57RMLNmeumSugNpxNFwKGBOBy2gAWjeDQvqIPwtvr_g52P0kOpxJROV0cQQk1xrXFB4kK7J7Zb_0MTcknNBCONm-t3enGd22846CbQf_0bnN7jTNnFI4ahH2T8xRVgqh7b2wdHudIYgAmDEvKn9f7bU1JsdLZlwePJfZBmI4G27KVq_BGKOyI39yi_xdvaLnXfCFqbjoUVCEp56iWTDiy2pZ3JBe9rxKtIV-6fqx-SlEzHqmriGCPIoAXiWFY60pH1g8D5icweADm0';
$.ajax({
type:'post',
data:'',
url:'/api/details',
headers:{
'Accept' : 'application/json',
'Authorization' : 'Bearer ' + $accessToken
},
success:function(data){
alert('success');
console.log(data);
}
});
})
})
如果302重定向,说明请求头没有设置好,如果报500说明token错误
总结
- 服务端生成token
- native拿到token之后存到本地
- 请求时通过请求头携带token,请求已经加了中间件验证的接口
- 服务端并没有保存token,而是通过一系列的算法,判断计算出的值与你傳来的token是否一直
- 这个token只有时效性,多次生成token之后,前面的token依然有效,目前掌握的知识暂时无法实现单点登录,下一步开始研究reac native本地存储和接口访问,最后研究单点登录
网友评论