猿问

“message”: “方法 Illuminate\\Auth\\SessionGuard:

我正在尝试将 JWT 添加到 .按照文档设置所有内容。https://jwt-auth.readthedocs.io/en/develop/quick-start/"tymon/jwt-auth": "^1.0"Laravel Framework 7.26.1

这是我的AuthController.php

<?php 


namespace App\Http\Controllers;

    

    use Illuminate\Support\Facades\Auth;

    use App\Http\Controllers\Controller;

    

    class AuthController extends Controller

    {

        /**

         * Create a new AuthController instance.

         *

         * @return void

         */

        public function __construct()

        {

            $this->middleware('auth:api', ['except' => ['login']]);

        }

    

        /**

         * Get a JWT via given credentials.

         *

         * @return \Illuminate\Http\JsonResponse

         */

        public function login()

        {

    

            $credentials = request(['email', 'password']);

    

            if (! $token = Auth::attempt($credentials)) {

                return response()->json(['error' => 'Unauthorized'], 401);

            }

    

            return $this->respondWithToken($token);

        }

...

这是 API.php


Route::post('login', 'AuthController@login')->middleware('api');


Route::post('logout', 'AuthController@logout');

Route::post('refresh', 'AuthController@refresh');

Route::post('me', 'AuthController@me');

当试图从邮递员那里击中时,这就是我得到的http://127.0.0.1:8000/api/login/


函数式编程
浏览 166回答 3
3回答

海绵宝宝撒

好。所以显然你必须在expires_in中指定守卫'expires_in' => auth('api')->factory()->getTTL() * 60我将函数更新为respondWithTokenAuthController.phpreturn response()->json([&nbsp; &nbsp; &nbsp; &nbsp; 'access_token' => $token,&nbsp; &nbsp; &nbsp; &nbsp; 'token_type' => 'bearer',&nbsp; &nbsp; &nbsp; &nbsp; //'expires_in' => auth()->factory()->getTTL() * 60&nbsp; &nbsp; &nbsp; &nbsp; 'expires_in' => auth('api')->factory()->getTTL() * 60&nbsp; &nbsp; ]);它修复了它。

心有法竹

正确,但由于您正在处理 API,因此您可以按照以下方式将默认保护从 更改为 in:webapiconfig/auth.php'defaults' => [&nbsp; &nbsp; &nbsp; &nbsp; 'guard' => 'api',&nbsp; &nbsp; &nbsp; &nbsp; 'passwords' => 'users',],然后,您可以在不指定守卫的情况下使用 auth:'expires_in' => auth()->factory()->getTTL() * 60您可能还需要运行以清除缓存,并且一切都应该很好。php artisan optimize

梵蒂冈之花

如果您要为 graphql 应用程序实现此功能,请确保将其包含在config/auth.php'defaults' => [&nbsp; &nbsp; 'guard' => 'api',&nbsp; &nbsp; 'passwords' => 'users',],'guards' => [&nbsp; &nbsp; 'api' => [&nbsp; &nbsp; &nbsp; &nbsp; 'driver' => 'jwt',&nbsp; &nbsp; &nbsp; &nbsp; 'provider' => 'users',&nbsp; &nbsp; ],],也不要忘记在用户.php模型中实现implements JWTSubjectclass User extends Authenticatable implements JWTSubject{ use HasApiTokens, HasFactory, Notifiable;&nbsp;public function getJWTIdentifier () {&nbsp; &nbsp; return $this->getKey();&nbsp;}&nbsp;public function getJWTCustomClaims () {&nbsp; &nbsp; return [];&nbsp;}}
随时随地看视频慕课网APP
我要回答