[英](API) 405 Method Not Allowed on Laravel 7 with tymon/jwt-auth
So i'm going to begin with the problem.所以我要从这个问题开始。
I have frontend application that work with Bearer Token Authentication, which is send to my backend.我有与承载令牌身份验证一起使用的前端应用程序,该应用程序发送到我的后端。
Everything with authentication is fine until i want to get my user data from my route在我想从我的路线中获取我的用户数据之前,一切都可以进行身份验证
Route::get('api/auth/me','Backend\AuthController@me');
I get error 405 Method GET
not allowed我收到错误 405 Method GET
not allowed
Full Error Message: 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
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
I've already set my route to respond with GET
我已经设置了使用GET
响应的路线
Here is my api.php
file:这是我的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) {
});
My AuthController.php
file:我的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,
]);
}
}
My route:list:我的路线:列表:
+--------+----------+-------------------------+----------+------------------------------------------------------------+------------+
| 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 |
+--------+----------+-------------------------+----------+------------------------------------------------------------+------------+
My URI Tab: https://i.imgur.com/cT1MMS7.png我的 URI 标签: https://i.imgur.com/cT1MMS7.png
So where's my mistake?那么我的错误在哪里? Please help me i'm stuck with this maybe for more than 3 hours I followed every step in tymondesign/jwt-auth documentation but don't work at all.请帮助我,我可能坚持了 3 个多小时,我遵循 tymondesign/jwt-auth 文档中的每一步,但根本不起作用。
I found the solution of the problem.我找到了问题的解决方案。 It's my mistake because i have typo in my User.php
model这是我的错误,因为我的User.php
model 中有错字
Model before change: 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 after change: 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);
}
}
So i change getJWTIdentifier()
return from $this->key
to $this->getKey()
所以我将getJWTIdentifier()
return 从$this->key
更改为$this->getKey()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.