Don Djoe
Don Djoe

Reputation: 705

Laravel Dingo JWT

I am currently coding an API in Laravel with Dingo and JWT as its authentication

It works fine, and I have set Dingo config to protected, so a valid JWT token will always need to be there, otherwise it will fail with 401 error. Again it works fine.

The question is .. how can I customise the error message? At the moment it shows like this

{
    message: "JWT has expired",
    status_code: 401,
    debug: { "..."
    }
}

At minimum I want to get "JWT has expired" changed to a custom text, either from JWT or Dingo but of course if it can be customised further, it would be great.

Any advice? Thanks

Upvotes: 0

Views: 1793

Answers (2)

yangwendaxia
yangwendaxia

Reputation: 179

My solution is to create an AuthController class as following code:

<?php

namespace App\Http\ApiControllers\V1;

use App\Http\Controllers\Controller;
use Dingo\Api\Routing\Helpers;

class BaseController extends Controller
{
    use Helpers;
}

AuthController

<?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());
    }


}

Then ,you can customise the error message as you like . For more info, you can refer to https://github.com/tymondesigns/jwt-auth/wiki/Authentication

Upvotes: 1

Don Djoe
Don Djoe

Reputation: 705

I found a solution

By creating my own provider (or rather extending the default FirebaseProvider) and set the config to use the custom provider

The default is

'provider' => 'Tymon\JWTAuth\Providers\FirebaseProvider'

changed to

'provider' => 'CustomPackages\Providers\MyFirebaseProvider'

I agree that this solution may not be the most elegant way. But it works and I am happy to hear about other solution

Upvotes: 1

Related Questions