我们打开项目,点击会员后可以看到我们的地址栏后边有token的这个参数
这个是因为我们在账号密码登录或者微信授权登录时将参数暂时放置到了地址栏后边
我们可以打开JWT的文档:https://learnku.com/articles/17883#de9435
这里有的问题所以在第七节中处理了这个问题
<?php namespace App\Auth; use Tymon\JWTAuth\JWT; use Tymon\JWTAuth\JWTGuard; use Illuminate\Http\Request; use Illuminate\Contracts\Session\Session; use Illuminate\Contracts\Auth\UserProvider; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Support\Facades\Redis; class JWTSessionGuard extends JWTGuard { protected $session; protected $id; public function __construct(JWT $jwt, UserProvider $provider, Request $request , Session $session){ $this->session = $session ; parent::__construct($jwt, $provider, $request); } public function login(JWTSubject $user) { $token = $this->jwt->fromUser($user); $this->setToken($token)->setUser($user); $this->updateSession($user->id); return $token; } protected function updateSession($id) { // $this->session->put($this->getName(), $id); // dump(session()->all()); // dump($this->getName()); // $this->session->migrate(true); Redis::set($this->getName(), $id); // $this->id = $id; } public function getName() { return 'login_jwt_'.sha1(static::class); } // 检验是否登录 public function webCheck() { // Redis::del($this->getName()); // dump(session()->all()); // dump($this->getName()); $id = Redis::get($this->getName()); dump($id); // $id = $this->session->get($this->getName()); return !is_null($this->provider->retrieveById($id)); } }
然后添加一个验证登录的一个中间件
修改路由
然后进行测试
点击会员,用户未登录会跳转到登录页面
控制器代码
<?php namespace App\Http\Controllers\Api\V1; use http\Cookie; use JWTAuth; use App\User; use App\Http\Controllers\Api\Traits\TransFormer; use Dingo\Api\Routing\Helpers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class AuthorizationsController extends Controller { use Helpers,TransFormer; /** * 账号登录 */ public function store(Request $request) { $param = $request->only(['email','password']); if(!($token = auth('api')->attempt($param))){ return $this->response->array($this->transFormer(4000,'用户账号密码错误')); } // dump($token);die; // return [ // 'error' => 0, // 'message' => '登录成功', // 'redirect' => route('web.member.index',['token'=>$token]) // ]; return $this->response->array($this->transFormer(0,'用户登录成功',route('web.member.index')))->withCookie(cookie()->forever('token', $token)); } /** * 微信网页登录 * 这里引用了easyWechat */ public function socialStore(Request $request) { $wechatUser = session('wechat.oauth_user.default'); $user = User::where('weixin_openid',$wechatUser->id)->first(); if(!$user){ $user = User::create([ 'name' => $wechatUser->name, 'weixin_openid' => $wechatUser->id ]); } return redirect(route('web.member.index'))->withCookie(cookie()->forever('token', auth('api')->login($user))); // return redirect()->route('web.member.index'); // return redirect(route('web.member.index'))->withCookie(cookie()->forever('token',auth('api')->login($user))); } }