laravel 项目中JWT的实际应用(二)

马克飞 1月前 82

接上一篇写,如果没看过上一篇,请出门左转

应用实例

  • 新建一个UserRepository.php代码如下:
<?php

namespace App\Repositories;

use App\Models\User;

class UserRepository
{
    private $user;

    /**
     * UserRepository constructor.
     * @param $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * add user
     *
     * @param array $validated
     * @return void
     */
    public function store($validated)
    {
        $this->user->fill($validated);
        $this->user->setPassword($validated->password);
        return $this->user->save();
    }
}
  • 再新建一个AuthService.php用来实现一些方法,代码如下:
<?php

namespace App\Services;

use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Facades\JWTFactory;
use App\Exceptions\RestfulException;

class AuthService
{
    /**
     * 生成token
     *
     * @param array $credentials
     * @return void
     */
    public function generateToken($credentials)
    {
        if (!$token = JWTAuth::attempt($credentials)) {
            throw new RestfulException('认证token生成失败,请重新登录', 401);
        }
        return $this->respondWithToken($token);
    }

    /**
     * 根据token返回用户信息
     *
     * @return void
     */
    public function me()
    {
        return JWTAuth::parseToken()->toUser();
    }

    /**
     * 刷新token
     *
     * @return void
     */
    public function refreshToken()
    {
        return $this->respondWithToken(JWTAuth::parseToken()->refresh());
    }

    /**
     * token失效
     *
     * @return void
     */
    public function invalidate()
    {
        return JWTAuth::parseToken()->invalidate();
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     * 该方法按照指定的格式返回输出信息
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return [
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => JWTFactory::getTTL()
        ];
    }
}
  • 最后我们新建一个UserController.php来实现一个login方法,代码如下:
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests\User\Store;
use App\Repositories\UserRepository;
use App\Http\Requests\Auth\Login;
use App\Services\AuthService;

class UserController extends Controller
{
    protected $userRepository;
    protected $authService;

    /**
     * UserController constructor.
     * @param $userRepository
     */
    public function __construct(UserRepository $userRepository, AuthService $authService)
    {
        $this->middleware('jwt.auth', ['except' => ['login', 'refresh', 'register']]);
        $this->userRepository = $userRepository;
        $this->authService = $authService;
    }

    /**
     * Display a listing of the resource.
     * 用户列表
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return $this->authService->me();
    }

    /**
     * Store a newly created resource in storage.
     * 添加用户
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Store $request)
    {
        $validated = $request->validated();
        return $this->userRepository->store($validated);
    }

    /**
     * Display the specified resource.
     * 用户详情
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     * 用户更新
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     * 删除用户(软删除)
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        //
    }

    public function login(Login $request)
    {
        $validated = $request->validated();
        return $this->authService->generateToken($validated);
    }
}
  • 当然别忘了加route,如下:
// user
Route::post('v1/user/login', 'UserController@login');
Route::apiResource('v1/user', 'UserController');
  • 请求login接口,返回结果如下:
{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9idWlsZC53ZWxpbmtzb3VsLmNvbToyMDgwXC9hcGlcL3YxXC91c2VyXC9sb2dpbiIsImlhdCI6MTU4NjYxNjkwOCwiZXhwIjoxNTg2NjIwNTA4LCJuYmYiOjE1ODY2MTY5MDgsImp0aSI6InVvUlE2eVV2SWloTEJvVm8iLCJzdWIiOjEsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.ZRQeY8wNiU01KzGcN3rQEIwhGLLfxQdda0EYxhDRq8Q",
    "token_type": "Bearer",
    "expires_in": 60
}
最新回复 (0)
    • 都市菜鸟网
      2
        立即登录 立即注册 
返回