2016-12-02 5 views
3

私はガードを使用してコードと認証されたユーザを作成しましたが、それはapi_tokenapi_tokenの生成方法は?

/** 
* This'll provide login authentication to the user 
* @param Request $request 
* @return json 
*/ 
public function authenticate(Request $request) 
{ 
    //getting and setting locale for the request 
    $locale = ($request->header('lang-code') == 'KO') ? "ko" : "en"; 
    app()->setLocale($locale); 

    $credentials = $request->only('email','password'); 

    try { 
     // verify the credentials and create a token for the user 
     if (!$token = auth()->attempt($credentials)) { 
      return response()->json(['success' => parent::FAILURE, 'message' => trans('messages.api.login.failure')],401); 
     } 

    } catch (GeneralException $e) { 
     // something went wrong 
     return response()->json(['success' => parent::FAILURE, 'message' => trans('messages.api.login.tokenNC')],500); 
    } 

    return response()->json(['success' => parent::SUCCESS, 'message' => trans('messages.api.login.success'), 'data' => auth()->user()],200); 
} 

機能の上に私を提供していませんが正常に動作しているが、私はauth()->guard('api')->user()->api_tokenを使用するとき、私はトークン届きません。 api_tokenを生成することができないのに、この列は既に私のDB内にあります。

EDITED

ルート/ api.php:

Route::group(['namespace' => "Api\\v1", 'as' => 'api.v1.', 'prefix' => 'v1'], function() { 
    Route::any('/login', '[email protected]'); 
}); 

のconfig/auth.php:

'defaults' => [ 
     'guard' => 'web', 
     'passwords' => 'users', 
    ], 

    'guards' => [ 
     'web' => [ 
      'driver' => 'session', 
      'provider' => 'users', 
     ], 

     'api' => [ 
      'driver' => 'token', 
      'provider' => 'users', 
     ], 
    ], 
+0

それでも採石場を持っている場合は、私に尋ねるか、アップ票と私の答えを受け入れます! – msonowal

+0

あなたの** config/auth.php **はどのようなものですか? –

+0

あなたのルートファイルも –

答えて

0

あなたは自動的にそれを行うためにモデルのミューテーターを使用することができますモデルクラスのブートメソッドをオーバーライドします。あなたはトークン認証を使用するすべてのルートがauth:apiミドルウェアにより保護されていることを確認する必要があるかもしれないあなたの場合には、ユーザーモデル

protected static function boot() 
{ 
    parent::boot(); 
    static::creating(function($model) 
    { 
     $model->api_token = $model->generateCode(); 
    }); 
} 

protected function generateCode() 
{ 
    return bin2hex(openssl_random_pseudo_bytes(16)); 
    //you can use your own random fucntion here or you can use inbuilt Crypt funciton 
} 
+0

私は試してみましょう。だから、我々は成功した認証 – devmyb

+0

いいえ、私が答えたことは、使用のためのAPIトークンを生成するためのものであり、後に 'api_token'を作成する必要があることを意味していますが、あなたのauthenticateメソッドを上書きする必要があり、使用払い:APIガードのために内蔵された認証用のAPIのミドルウェアapi'私は届かない:それは私がそのようにしようとしたが、認証 '使用している間 – msonowal

+0

データ – devmyb

1

です。この例のように

:それはあなたを助けている場合

Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function() { 
    Route::post('/authentificate', '[email protected]'); 
}); 
+0

を期待どおりに動作しないアプリ – devmyb

+0

あなたは '' $ credentials'''を意味していますか? –

+0

実際に私は 'auth:api'という名前の新しいミドルウェアを作成しました。 – devmyb

関連する問題