我的解决方案是创建一个 AuthController 类,如下代码:
<?php
namespace App\Http\ApiControllers\V1;
use App\Http\Controllers\Controller;
use Dingo\Api\Routing\Helpers;
class BaseController extends Controller
{
use Helpers;
}
授权控制器
<?php
/**
* Created by PhpStorm.
* User: ***
* Date: 26/10/2016
* Time: 14:07
*/
namespace App\Http\ApiControllers\V1;
use App\Http\Requests\AddUserRequest;
use App\Http\Transformer\UserTransformer;
use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class AuthController extends BaseController
{
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (!$token = JWTAuth::attempt($credentials)) {
// return response()->json(['error' => 'invalid_credentials'], 401);
//return response()->json(['error' => '用户名或密码错误'], 401);
return $this->response->error('用户名或密码错误', 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
// return response()->json(['error' => 'could_not_create_token'], 500);
// return response()->json(['error' => '创建 token 失败'], 500);
return $this->response->error('创建 token 失败', 500);
}
// all good so return the token
return response()->json(compact('token'));
// return $this->response->item($token);
}
public function getAuthenticatedUser()
{
try {
if (!$user = JWTAuth::parseToken()->authenticate()) {
return $this->response->errorNotFound('没有此用户');
}
} catch (TokenExpiredException $e) {
return $this->response->errorUnauthorized('token_expired');
} catch (TokenInvalidException $e) {
return $this->response->errorBadRequest('token_invalid');
} catch (JWTException $e) {
return $this->response->errorInternal('token_absent');
}
return $this->response->item($user,new UserTransformer());
}
}
然后,您可以根据需要自定义错误消息。有关更多信息,您可以参考https://github.com/tymondesigns/jwt-auth/wiki/Authentication