簡體   English   中英

(API) Laravel 7 上不允許使用 tymon/jwt-auth 的 405 方法

[英](API) 405 Method Not Allowed on Laravel 7 with tymon/jwt-auth

所以我要從這個問題開始。

我有與承載令牌身份驗證一起使用的前端應用程序,該應用程序發送到我的后端。

在我想從我的路線中獲取我的用戶數據之前,一切都可以進行身份驗證

Route::get('api/auth/me','Backend\AuthController@me');

我收到錯誤 405 Method GET not allowed

完整錯誤消息: Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The GET method is not supported for this route. Supported methods: POST. in file C:\Programming\LSUniverseCMS\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php on line 117 Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The GET method is not supported for this route. Supported methods: POST. in file C:\Programming\LSUniverseCMS\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php on line 117

我已經設置了使用GET響應的路線

這是我的api.php文件:

     <?php

    use Illuminate\Support\Facades\Route;


     Route::group(['prefix' => 'auth', 'middleware' => 'api'], function ($router) {

        Route::post('login', 'Backend\AuthController@login')->name('login');
        Route::post('register', 'Backend\AuthController@register')->name('register');
        Route::post('refresh', 'Backend\AuthController@refresh')->name('refresh');
        Route::post('logout', 'Backend\AuthController@logout')->name('logout');
        Route::get('verify/{token}', 'Backend\VerificationController@verify')->name('verify');
        Route::get('me', 'Backend\AuthController@me')->name('me');

    });

    Route::group(['middleware' => 'api', 'prefix' => 'user'], function ($router) {
    });

我的AuthController.php文件:

<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\User;
use App\UserVerification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    /**
     * Create instance of AuthController
     * Make middleware ignore login and register routes
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' =>['login','register']]);
    }

    /**
     * Register the user with requested credentials
     *
     * @param  mixed $request
     * @return void
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'min:4'],
            'email' => ['email', 'required', 'unique:users'],
            'password' => ['required', 'regex:/^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/'],
            're_password' => ['required', 'same:password'],
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()->first()], 400);
        }

        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => Hash::make($request->input('password')),
            'isAdmin' => 0,
            'balance' => 0.00,
            'verified' => 0,
        ]);

        if ($user) {
            UserVerification::create([
                'user_id' => $user->id,
                'token' => md5("$user->id $user->email" . sha1(time())),
            ]);

            return response()->json(['message' => 'Created'], 201);
        }

        return response()->json(['error' => 'Failed'], 400);

    }

    /**
     * Get JWT token via given credentials
     *
     * @return mixed
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $credentials = request(['email', 'password']);
        $verified = User::where('email', $credentials['email'])->first()->verified;
        if ($verified == 1) {
            if (!$token = auth('api')->attempt($credentials)) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
        } else {
            return response()->json(['error'=>'Not verified'], 401);
        }

        return $this->respondWithToken($token);
    }

    /**
     * Return user information from database
     *
     * @return void
     */
    public function me()
    {
        return response()->json(auth('api')->user());
    }

    /**
     * Log the user out (Invalidate the token)
     *
     * @return \Illuminate\Http\Response;
     */
    public function logout()
    {
        auth()->logout();
        return response()->json(['message' => 'Successfuly']);
    }

    /**
     * Refresh user token
     *
     * @return void
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * respondWithToken
     *
     * @param  mixed $token
     * @return void
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60,
        ]);
    }

}

我的路線:列表:

+--------+----------+-------------------------+----------+------------------------------------------------------------+------------+
| Domain | Method   | URI                     | Name     | Action                                                     | Middleware |
+--------+----------+-------------------------+----------+------------------------------------------------------------+------------+
|        | POST     | api/auth/login          | login    | App\Http\Controllers\Backend\AuthController@login          | api        |
|        | POST     | api/auth/logout         | logout   | App\Http\Controllers\Backend\AuthController@logout         | api        |
|        |          |                         |          |                                                            | auth:api   |
|        | GET|HEAD | api/auth/me             | me       | App\Http\Controllers\Backend\AuthController@me             | api        |
|        |          |                         |          |                                                            | auth:api   |
|        | POST     | api/auth/refresh        | refresh  | App\Http\Controllers\Backend\AuthController@refresh        | api        |
|        |          |                         |          |                                                            | auth:api   |
|        | POST     | api/auth/register       | register | App\Http\Controllers\Backend\AuthController@register       | api        |
|        | GET|HEAD | api/auth/verify/{token} | verify   | App\Http\Controllers\Backend\VerificationController@verify | api        |
|        | GET|HEAD | {path?}                 |          | Illuminate\Routing\ViewController                          | web        |
+--------+----------+-------------------------+----------+------------------------------------------------------------+------------+

我的 URI 標簽: https://i.imgur.com/cT1MMS7.png

那么我的錯誤在哪里? 請幫助我,我可能堅持了 3 個多小時,我遵循 tymondesign/jwt-auth 文檔中的每一步,但根本不起作用。

我找到了問題的解決方案。 這是我的錯誤,因為我的User.php model 中有錯字

Model 更改前:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
        'verified', 'balance', 'isAdmin',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'verified',
    ];

    /**
     * getJWTCustomClaims
     *
     * @return mixed
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * getJWTIdentifier
     *
     * @return array
     */
    public function getJWTIdentifier()
    {
        return $this->key;
    }
    
    /**
     * RelationShip between user, and user activation token
     *
     * @return void
     */
    public function verifyToken()
    {
        return $this->hasOne(UserVerification::class);
    }
}

Model 更改后:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
        'verified', 'balance', 'isAdmin',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'verified',
    ];

    /**
     * getJWTCustomClaims
     *
     * @return mixed
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * getJWTIdentifier
     *
     * @return array
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    
    /**
     * RelationShip between user, and user activation token
     *
     * @return void
     */
    public function verifyToken()
    {
        return $this->hasOne(UserVerification::class);
    }
}

所以我將getJWTIdentifier() return 從$this->key更改為$this->getKey()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM