首页 文章

JWT Auth配置Dingo Api Laravel 5.1 . *

提问于
浏览
0

我正在使用带有Dingo Api和JWT Auth的Laravel 5.1.33,安装了所有这些但是现在我很困惑,如果我需要做更多,如果我例如想要验证用户,那么用户无法访问某些路由而没有首先登录 .

我在api.php上修改了这段代码:

'auth' => [
    'jwt' => 'Dingo\Api\Auth\Provider\JWT',
],

当它到来时,我很困惑,在哪里添加这个代码,它真正做了什么?

app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
   return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

我已经读过dingo / api内置了对tymondesigns / jwt-auth的支持,这是否意味着我不需要编写任何身份验证代码,或者这意味着什么?

任何人都可以告诉我,如果我必须修改当前的AuthController,此时如下所示:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

如果是这样,需要添加哪些方法?它说Dingo支持内置的jwt auth,因此我决定使用这个软件包,不仅仅是这个原因以及其他一些原因,比如变形金刚,速率限制等......但我仍然感到困惑,我是否需要编写额外的代码对于已在构建中支持的身份验证用户...如果没有,我该如何登录?我没有声明用于身份验证的路由,也没有注册用户,我应该以某种方式将这些路由指向某些控制器,任何人都可以帮忙解决这个问题?

2 回答

  • 0

    以下是步骤:

    Step 1:

    打开App \ Providers \ AuthServiceProvider . 将以下代码粘贴到 boot 方法中

    app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
    
        return new \Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);        
    });
    

    Step 2

    创建一个身份验证控制器,生成身份验证令牌并将其返回

    namespace App\Http\Controllers\Api;
    
    use Illuminate\Http\Request;
    use JWTAuth;
    use Tymon\JWTAuth\Exceptions\JWTException;
    
    class AuthenticateController extends ApiController
    {
    
    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);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return $this->response->errorInternal('Could not create token');
        }
    
        return $this->response->array([
            'token' => $token,
            'expire_in' => \Carbon\Carbon::now()->addMinutes(config('jwt.ttl'))->format('Y-m-d H:i:s')
        ]);
    
    }
    

    }

    Step 3:

    创建一个如下所示的根Api控制器 .

    namespace App\Http\Controllers\Api;
    
    use App\Http\Controllers\Controller;
    use Dingo\Api\Routing\Helpers;
    
    
    class ApiController extends Controller
    {
        use Helpers;
    }
    

    Step 4

    现在您已准备好使用Dingo JWT auth . 只需从ApiController类扩展您的控制器类 . 那必须是所有Api控制器的父母 .

    namespace App\Http\Controllers\Api;
    
    
    use App\Http\Requests\Request;
    
    class TestController extends ApiController
    {
        public function index(Request $request)
        {
            $this->auth; # Here Auth is the logged in user object
            # to return pagination
            return $this->response->paginator(User::paginate(10), new 
              UserTransformer());
            # to return a single Model instance
            return $this->response->item($user, new UserTransformer());
            # to return error. Others error methods as well
            return $this->response->errorInternal('Error Message');
            # to return a custom array
            return $this->response->array([
                'status' => 200,
                'message' => 'Msg'
            ]);
    }
    

    }

  • -1

    look at this github project,你可以参考它的路线和控制器 .

    例如,需要添加一些方法

    • login:用户登录获取令牌 .

    • 刷新令牌:令牌无效时 .

相关问题