简体   繁体   中英

JWT Auth config on Dingo Api Laravel 5.1.*

I am using Laravel 5.1.33 with Dingo Api and JWT Auth, have installed all of these but now I am confused if I need to do more if I for example want to authenticate a user so the user is not able to access certain routes without being logged in first.

I havethis code modified on api.php:

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

I am confused when it comes here, where to add this code and what does it really do?

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

I have read dingo/api has in-built support for tymondesigns/jwt-auth, does this mean I dont need to write any authentication code, or what does this mean?

Could anyone tell me if I have to modify the current AuthController which at this moment looks as below:

<?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']),
        ]);
    }
}

If so, what methods needs to be added? It says that Dingo supports in built jwt auth, therefor i decided to use this packages, not only this reasons as well as few other reasons, like transformers,rate limit etc... but I am still confused whether I need to write extra code for Authentication users as it already supports in build... If not, how do I login? I have no routes declared for authentications,nor register users, I should somehow point those routes to some controllers, anyone could help with this?

Here is the steps:

Step 1:

Open App\\Providers\\AuthServiceProvider . Paste the following code into boot method

app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {

    return new \Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);        
});

Step 2

Create a authenticate controller that generate a auth token and return it

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:

Create a root Api Controller that will looks like following.

namespace App\Http\Controllers\Api;

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


class ApiController extends Controller
{
    use Helpers;
}

Step 4

Now you are ready to use Dingo JWT auth. Just extend your controller class from ApiController class. That must be the parent of all Api Controller.

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'
        ]);
}

}

look at this github project , you can refer to it's route and controller.

Some methods needs to be added, for example ,

  1. login:user login to get token.
  2. refresh token: when token is invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM