2017-05-10 125 views
2

我已閱讀下面的文章,它是真棒。那篇文章中的一切都很清楚,但我有一個重大疑問。OAuth2密碼授權混淆

https://stormpath.com/blog/the-ultimate-guide-to-mobile-api-security

文章作者說,在「OAuth2用戶密碼補助」,而登錄到移動應用程序,只需要以獲得從API服務器的訪問令牌發送電子郵件和密碼,但我已閱讀在許多地方,您還需要在該請求中發送client_id和client_secret。我打算使用Laravel建立我的API:

https://laravel.com/docs/master/passport#password-grant-tokens

在這裏你可以看到它迫使我送的client_id和client_secret在該請求。

我對此非常困惑。如果我必須在該請求中發送client_id和client_secret,首先我需要通過在授權服務器上創建客戶端來獲取它。那麼在哪個活動中,我應該創建該客戶端?當用戶嘗試從移動應用程序登錄時?我只需要知道確切的流程。

任何幫助,將不勝感激。

感謝

回答

1

客戶端獲取誰需要與服務器的OAuth2集成開發人員創建。它與特定用戶的登錄流無關。

ex。我想與Facebook登錄集成;我在Facebook上創建了一個客戶端,並將其納入我的服務,它的Facebook的方式知道我的服務是誰。

因此,用戶通過您的應用程序登錄;然後您的應用程序將該用戶名和密碼發送到後端服務器。後端服務器然後添加client_id和祕密,以便OAuth服務器可以驗證請求的真實性。

因此,對於您的情況,用戶登錄到您的移動應用程序,您發送該登錄請求(用戶名和密碼,SSL)到您的後端服務器。您的後端服務器然後將該請求轉發到OAuth2服務,如下面的請求。

'form_params' => [ 
    'grant_type' => 'password', 
    'client_id' => 'client-id', 
    'client_secret' => 'client-secret', 
    'username' => '[email protected]', 
    'password' => 'user-password', 
    'scope' => '', 
], 

這會直接返回一個access_token和一個可以安全地存儲在移動應用程序中的刷新令牌。

+0

謝謝。只是爲了讓您知道我要構建應用和API,因此圖片中沒有第三方網站,如臉譜網。因此,您知道爲了獲得訪問令牌,客戶端ID和客戶端密鑰是必需的,那麼我應該創建它們並將它們放在移動應用程序代碼中並將它們發送到API請求中?在那種情況下,無論設備和用戶如何,這些憑證都是相同的。 –

+0

您不能將它們放在移動應用程序上,移動應用程序上的任何代碼都可以被攔截並且可以直接讀取。任何人都可以反編譯你的應用程序,並閱讀你的client_id和祕密。 檢查,出https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript它通過您的一些需求。 –

0

我在名爲ConfigurePassport的遷移中創建授權客戶端,並設置我希望應用程序使用的密鑰。您不需要每個用戶的客戶端。

public function up() 
{ 
    /* 
    * This command will create the encryption keys needed to generate secure access tokens. 
    * In addition, the command will create "personal access" and "password grant" 
    * clients which will be used to generate access tokens 
    */ 
    Artisan::call('passport:install', array('-n' => true)); 

    // Set Password Grant Client secret to known key 
    DB::table('oauth_clients')->where('password_client', 1)->update(
     ['secret' => env('GRANT_CLIENT_SECRET', 'dfhsdfhbtg545fdf45yedh5f5blahblah')] 
    ); 
} 

上述遷移運行人員命令passport:install按照安裝客戶端的文檔。 https://laravel.com/docs/master/passport#password-grant-tokens

現在,您的移動應用可以請求這樣的令牌:唯一的每用戶參數是用戶名和密碼。

您可以在password_client爲true的oauth_clients表中找到客戶端ID。它可能會是2.

$http->post('http://your-app.com/oauth/token', [ 
    'form_params' => [ 
     'grant_type' => 'password', 
     'client_id' => 2, 
     'client_secret' => 'dfhsdfhbtg545fdf45yedh5f5blahblah', 
     'username' => '[email protected]', 
     'password' => 'my-password', 
     'scope' => '', 
    ], 
]); 
+0

謝謝,如果你可以更詳細地解釋一下,會很好。 –

+0

@ParthVora增加了一點,特別是你錯過了什麼? –

+0

所以在應用程序中,我必須硬編碼client_id和client_secret? –