2017-03-09 34 views
3

两天来我正在挖掘谷歌,但无法找到我的问题的起始线程,现在我没有选择。请帮助我一些方向/如何使用laravel 5.3护照从Android应用程序进行API登录

我有一个Web应用程序运行内置laravel 5.3,我已经安装护照描述here。如果我去/home其完美展现。

Home page

现在我必须做出一个Android应用程序从

  1. 一个已经存在的web应用程序的用户可以登录
  2. 获得该用户的所有任务列表TaskModel (ons_tasks(id, title, description))

只有相关路线

in web.php 
Auth::routes(); 

in api.php 

Route::get('/user', function (Request $request) { 
    return $request->user(); 
})->middleware('auth:api'); 


Route::group(['middleware' => ['auth:api']], function() { 

    Route::get('/test', function (Request $request) { 
     return response()->json(['name' => 'test']); 
    }); 

    Route::get('/task/list', function (Request $request) {   
     $list = \App\Model\TaskModel::all(); 
     return response()->json($list); 
    }); 

}); 

登陆:如果我发送POST请求/login与电子邮件&密码得到TokenMismatchException错误,但从哪里获得令牌 Android应用的移动?我还需要在api中使用Auth::routes()吗? 如果那么我还需要什么才能登录并获取令牌,以便以后我可以发送它来创建任务列表。

其次,

如果我去/api/test它重定向我/home页面,而不 showning任何错误!

在此先感谢。

+0

你是否解决了这个问题? – utdev

回答

1

当您启用Passport的API

你需要使用密码授予客户端在这种情况下,看到this section of Passport's documentation认证。

一旦你生成一个密码授予客户端,使用:

php artisan passport:client --password 

您将需要从应用程序中请求访问令牌,并与您的后续请求发送,以访问受保护的权威性:api中间件路线。

为了获得访问令牌,将请求发送到您的应用程序的/oauth/token路线(这是一个PHP实现明显,确保正确的格式如下请求在您的Java实现):

$http = new GuzzleHttp\Client; 

$response = $http->post('http://your-app.com/oauth/token', [ 
    'form_params' => [ 
     'grant_type' => 'password', 
     'client_id' => '<client id returned from the artisan command above>', 
    ' client_secret' => '<secret returned from artisan command above>', 
     'username' => '[email protected]', 
     'password' => 'my-password', 
     'scope' => '', 
    ], 
]); 

return json_decode((string) $response->getBody(), true); 

确保您添加client_secretclient_id,这是从上面的技术人员调用返回的,并确保usernamepassword引用数据库中的有效用户。

如果在这里一切都很好,您应该在回复中收到access_tokenrefresh_tokenaccess_token是您需要使用auth:api守卫进行身份验证的内容。要正确地传递这回你的API,你将需要与头Authorization: Bearer <your accessToken>Accept: application/json

例如发送您的后续请求,访问您的“测试”路线:

$response = $client->request('GET', '/api/test', [ 
    'headers' => [ 
     'Accept' => 'application/json', 
     'Authorization' => 'Bearer '. <accessToken from /oauth/token call>, 
    ], 
]); 

如果您已设置这些正确的,你应该看到你指定的数组的JSON响应。

为什么/ api/test重定向我没有错误?

您正在请求使用auth:api中间件的路由。这将重定向你,因为你没有如上所述指定正确的标题,这是预期的行为。

希望这会有所帮助。