<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                ## 一,安裝firebase/php-jwt擴展: 1,命令: ~~~ liuhongdi@lhdpc:/data/php/admapi$ composer require firebase/php-jwt ~~~ 2,安裝成功后的位置: ![](https://img.kancloud.cn/7b/b5/7bb5b79cec30773a8ddf6b66291ac003_352x390.png) 3,查看firebase/php-jwt的版本: ~~~ liuhongdi@lhdpc:/data/php/admapi$ composer show firebase/php-jwt ~~~ ![](https://img.kancloud.cn/d4/e0/d4e01e6a9217c6bf404c22b1f7ae28a6_1225x494.png) ## 二,前端vue代碼: Login.vue ~~~ <template> <div style="padding:20px;display: flex;align-items:center;justify-content: center;"> <form :model="account" style="margin-top:50px;width:400px;"> <input v-model="account.username" placeholder="請輸入用戶名" style="width:392px;font-size:16px;" /><br/> <input v-model="account.password" type="password" placeholder="請輸入密碼" style="width:392px;margin-top:10px;font-size:16px;" /><br/> <!--v-loading.fullscreen.lock="isLoading"--> <div @click="login" style="margin-top:10px;width: 100%;height:40px;line-height:40px;background: #ff0000;border-radius: 10px;"> 登錄 </div> <div @click="info" style="margin-top:10px;width: 100%;height:40px;line-height:40px;background: #ff0000;border-radius: 10px;"> info </div> <div class="text-align-right"> </div> </form> </div> </template> <script> import { ref, reactive } from "vue"; import { ElMessage } from "element-plus"; import { apiLogin,apiInfo,apiToken} from '@/api/api'; export default { name: "Login", setup() { const accountRef = ref(null); //表單字段 const account = reactive({ username: "", password: "", }); //登錄 const login = async () => { console.log('begin login'); var data = new FormData(); data.append("username",account.username); data.append("password",account.password); apiLogin(data).then(res => { //成功 if (res.code == 0) { //保存jwt token到本地 localStorage.setItem('token', res.data.token); //提示 ElMessage.success("登錄成功!"); } else { ElMessage.error("登錄失敗:"+res.msg); } }).catch((error) => { console.log(error) }) }; const login2 = () => { console.log('begin login2'); } const info = () => { apiInfo().then(res => { //成功 if (res.code == 0) { //保存jwt token到本地 //localStorage.setItem('token', res.data.token); //提示 //ElMessage.success("登錄成功!"); console.log(res.data); } else { ElMessage.error("用戶信息獲取失敗:"+res.msg); } }).catch((error) => { console.log(error) }) } return { account, //loginRules, accountRef, login, login2, info, //isLoading, }; }, } </script> <style scoped> </style> ~~~ api/axios.js ``` ... //post export function postForm (url, params) { return new Promise((resolve, reject) => { let headers = { 'Content-Type': 'application/x-www-form-urlencoded', } //判斷params中是否包含X-CSRF-TOKEN var token = ""; if (params.has("X-CSRF-TOKEN")) { token = params.get("X-CSRF-TOKEN"); params.delete("X-CSRF-TOKEN"); headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': token, } } _axios.post(url, params,{headers}) .then(res => { resolve(res.data) }) .catch(err => { console.log("api error:"); console.log(err); //alert(err); reject(err.data) }) }) } ... ``` api/api.js ``` //get, import { get, postForm} from './axios' //user export const apiLogin = pLogin => postForm('/api/auth/login', pLogin) ... ``` ## 三,后端php代碼: 1,創建middleware ~~~ liuhongdi@lhdpc:/data/php/admapi$ php think make:middleware CheckJwt Middleware:app\middleware\CheckJwt created successfully.? ~~~ 2,CheckJwt的代碼:? ~~~ <?php declare (strict_types = 1); namespace app\middleware; use app\lib\util\JwtUtil; class CheckJwt { /** * 處理請求,得到用戶信息 * * @param \think\Request $request * @param \Closure $next * @return Response */ public function handle($request, \Closure $next) { $auth = $request->header('authorization'); if ($auth == null) { return $next($request); } $token = str_replace("Bearer ","",$auth); $jUtil = new JwtUtil(); $res = $jUtil->verifyjwt($token); if (isset($res['code']) && isset($res['userId']) && $res['code'] == 0 && is_int($res['userId'])) { $userId = $res['userId']; $request->auth = $userId; } else { $request->auth = 0; } return $next($request); } } ~~~ 3,app/middleware.php 使從jwt得到用戶信息的middleware生效: ~~~ <?php // 全局中間件定義文件 return [ app\middleware\CheckJwt::class, ]; ~~~ 4,controller/Auth.php ~~~ <?php declare (strict_types = 1); namespace app\controller; use app\BaseController; use think\facade\Cache; use think\Request; use app\result\Result; use think\response\Json; use app\validate\Login as LoginValidate; use app\validate\GoodsList as GoodsListValidate; use think\exception\ValidateException; use app\lib\util\JwtUtil; class Auth extends BaseController { /* *得到form token * *@return \think\Response * */ public function token():Json { $type="sha1"; $type = is_callable($type) ? $type : 'md5'; $token = call_user_func($type, $this->request->server('REQUEST_TIME_FLOAT')); $key = uniqid(); Cache::set($key,$token,300); $res = [ "token"=>$key.$token, ]; return Result::Success($res); } /** * 登錄 * * @return \think\Response */ public function login():Json { // Header驗證 if ($this->request->header('X-CSRF-TOKEN')){ $reqToken = $this->request->header('X-CSRF-TOKEN'); $key = substr($reqToken,0,13); $value = Cache::get($key); $origToken = $key.$value; if ($origToken === $reqToken) { //驗證通過 } else { //驗證不通過 return Result::Error(422,'表單token錯誤'); } } else { return Result::Error(423,'找不到表單token'); } try { validate(LoginValidate::class) ->check($_POST); } catch (ValidateException $e) { // 驗證失敗 輸出錯誤信息 return Result::Error(422,$e->getError()); } if ($_POST["username"] == "dddddd" && $_POST["password"] == "111111"){ //驗證成功,生成jwt返回 $userId = 123; $jUtil = new JwtUtil(); $token = $jUtil->createJwt($userId); $res = ["token"=>$token]; // 防止重復提交 Cache::delete($key); return Result::Success($res); } else { return Result::Error(422,"用戶名密碼錯誤"); } } } ~~~ Result.php ``` <?php namespace app\result; use think\response\Json; class Result { //success static public function Success($data):Json { $rs = [ 'code'=>0, 'msg'=>"success", 'data'=>$data, ]; return json($rs); } //error static public function Error($code,$msg):Json { $rs = [ 'code'=>$code, 'msg'=>$msg, 'data'=>"", ]; return json($rs); } } ``` 5,lib/util/JwtUtil.php ~~~ <?php namespace app\lib\util; use Firebase\JWT\ExpiredException; use Firebase\JWT\JWT; class JwtUtil { private $signKey = "lhd@2001:liuhongdi"; private $timeMinutes = 5; /** * 根據json web token設置的規則生成token * @return \think\response\Json */ public function createJwt($userId):string { $key = md5($this->signKey); //jwt的簽發**,驗證token的時候需要用到 $time = time(); //簽發時間 $expire = $time + $this->timeMinutes*60; //過期時間 $token = array( "userId" => $userId, "iss" => "http://www.liuhongdi.com/",//簽發組織 "aud" => "lhd", //簽發作者 "iat" => $time, //簽發時間 "nbf" => $time, //生效時間 "exp" => $expire //過期時間 ); $jwt = JWT::encode($token,$key); return $jwt; } /** * 驗證token * @return \think\response\Json */ public function verifyjwt($token) { $key = md5($this->signKey); //jwt的簽發**,驗證token的時候需要用到 try{ $jwtAuth = json_encode(JWT::decode($token,$key,array("HS256"))); $authInfo = json_decode($jwtAuth,true); if (!$authInfo['userId']){ return ['code'=>0,'msg'=>"用戶不存在"]; } return ['code'=>0,'userId'=>$authInfo['userId'],'msg'=>"ok"]; }catch (ExpiredException $e){ return ['code'=>0,'msg'=>"token過期"]; }catch (\Exception $e){ return ['code'=>0,'msg'=>$e->getMessage()]; } } } ~~~ ## 四,效果測試 1,界面:用戶名 dddddd,密碼;111111,可見php的代碼: ![](https://img.kancloud.cn/a5/5c/a55cd0926c973d019e143bd091b2c7ee_1364x694.png) 2,未登錄時點info ![](https://img.kancloud.cn/6d/11/6d1114cbca7f177aefdc1b31bc669ebd_1284x588.png) 3,登錄后的返回: ![](https://img.kancloud.cn/49/29/49291e5417d8d37744f1fdc512349b6f_1262x554.png) 4,登錄后查看info的返回: ![](https://img.kancloud.cn/3d/28/3d28221bb29da63439be2cb264340883_1274x524.png)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看