laravel dingo/api添加jwt-auth認證

來源:互聯網
上載者:User
這篇文章主要介紹了關於laravel dingo/api添加jwt-auth認證,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

前面我們學了laravel dingo/api建立簡單的api,這樣api是開放給所有人的,如何查看和限制api的調用呢?可以用jwt-auth來驗證,JSON Web Token Authentication

  1,首先安裝jwt-auth外掛程式,在命令列中用composer安裝

composer require tymon/jwt-auth '0.5.*'

  2,然後發布

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

  在/config/產生了一個jwt.php檔案

  3,產生key

php artisan jwt:generate

  如果命令無法運行,可以在/config/jwt.php檔案中修改changeme為自己設定的密匙

'secret' => env('JWT_SECRET', 'changeme'),

  4,修改/app/Api/Controllers/HelloController.php為

<?phpnamespace App\Api\Controllers;use Illuminate\Http\Request;use App\Http\Controllers\Controller;//添加jwt-auth認證use JWTAuth;use Tymon\JWTAuth\Exceptions\JWTException;class HelloController extends Controller{    public function index()    {        return '{content:Helloworld!}';    }//添加jwt-auth認證  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 response()->json(['error' => 'could_not_create_token'], 500);        }        // all good so return the token        return response()->json(compact('token'));    }}

  5,添加路由(/routes/web.php)

$api->post('auth', 'App\Api\Controllers\HelloController@authenticate');

  6,測試路由:php artisan api:routes,如果出現如下提示表示正確

  訪問url:***.com/api/auth顯示錯誤,因為沒加token

重新修改hellocontrol和loutes

<?phpnamespace App\Api\Controllers;use Illuminate\Http\Request;use App\Http\Controllers\Controller;use JWTAuth;use Tymon\JWTAuth\Exceptions\JWTException;class HelloController extends Controller{    /**     * Create a new controller instance.     *     * @return void     */    /**     * Show the application dashboard.     *     * @return \Illuminate\Http\Response     */    public function index()    {        return '{content:Helloworld!}';    }  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 response()->json(['error' => 'could_not_create_token'], 500);        }        // all good so return the token        return response()->json(compact('token'));    }  //添加user  public function user()    {      JWTAuth::parseToken();      $user = JWTAuth::parseToken()->authenticate();      return $user;    }}

<?phpRoute::get('/', function () {    return view('welcome');});Auth::routes();Route::get('/home', 'HomeController@index')->name('home');$api = app('Dingo\Api\Routing\Router');$api->version('v1', function ($api) {    $api->get('helloworld', 'App\Api\Controllers\HelloController@index');  $api->post('auth', 'App\Api\Controllers\HelloController@authenticate');  $api->get('auth', 'App\Api\Controllers\HelloController@user');});

  用Google瀏覽器postman外掛程式擷取token,注意是post方法,步驟如所示

  將擷取的token複製,黏貼到第二步的使用者驗證token中,5中就是我們剛剛註冊的使用者

以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.