laravel 使用laravel 5.3通行证从Android应用程序登录API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42693913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:31:18  来源:igfitidea点击:

API login from android app using laravel 5.3 passport

laravellaravel-5.3laravel-passport

提问by Atiqur

For two days I am digging google but could not find the starting thread for my problem, now I am out of option. Please help me with some direction/howTo

两天来,我一直在搜索谷歌,但找不到解决我的问题的起始线程,现在我别无选择。请帮助我一些方向/方法

I have a web application running built with laravel 5.3, I have installed passport as described here. if I go /homeits showing perfectly.

我有一个使用 laravel 5.3 构建的 Web 应用程序,我已按照此处所述安装了 Passport 。如果我去/home完美显示。

Home page

主页

Now I have to make an android app from which

现在我必须制作一个 android 应用程序,从中

  1. An already existing user of web app can login
  2. get all the task list of that user TaskModel (ons_tasks(id, title, description))
  1. 网络应用程序的现有用户可以登录
  2. 获取该用户的所有任务列表 TaskModel (ons_tasks(id, title, description))

routes related only

仅与路线相关

in web.php

在 web.php 中

Auth::routes();

in api.php

在 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);
    });

});

To login :if I send post request /loginwith email & password get the TokenMismatchExceptionerror but Where do I obtain a token for android app in mobile?Do I need the Auth::routes()in the api too? if then what else Do I need to just login and get a token so later I can send it for getting the task lists.

登录:如果我发送/login带有电子邮件和密码的帖子请求,则会收到TokenMismatchException错误,但我从哪里获得移动设备中 android 应用程序的令牌?我也需要Auth::routes()api 吗?如果然后还有什么我需要登录并获取令牌,以便稍后我可以发送它以获取任务列表。

Secondly,

其次,

If I go to /api/testit redirects me to /homepage without showing any error !!!

如果我去 /api/test它会将我重定向到/home页面而不会显示任何错误!!!

Thanks in advance.

提前致谢。

回答by Aaron Fahey

To authenticate with your Passport-enabled API

使用启用 Passport 的 API 进行身份验证

You'll need to use the Password Grant Client in this situation, see this section of Passport's documentation.

在这种情况下,您需要使用 Password Grant Client,请参阅Passport 文档的这一部分

Once you've generated a Password Grant Client, using:

生成密码授予客户端后,使用:

 php artisan passport:client --password

You will need to request an access token from your application, and send it with your subsequent requests, in order to access the protected auth:api middleware routes.

您需要从应用程序请求访问令牌,并将其与后续请求一起发送,以便访问受保护的 auth:api 中间件路由。

To get an access token, send a request to your app's /oauth/tokenroute (this is a PHP implementation obviously, ensure you are correctly formatting below request in your Java implementation):

要获取访问令牌,请向您的应用程序的/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);

Ensure you add the client_secretand client_idthat was returned from the artisan call above, and ensure usernameand passwordreferences a valid user in your database.

确保添加了从上面的 artisan 调用返回的client_secretclient_id,并确保usernamepassword引用了数据库中的有效用户。

If everything is fine here, you should receive an access_tokenand refresh_tokenin the response. The access_tokenis what you need to authenticate using the auth:apiguard. To correctly pass this back to your api, you will need to send your subsequent requests with the headers Authorization: Bearer <your accessToken>and Accept: application/json

如果这里一切正常,您应该在响应中收到一个access_tokenrefresh_token。这access_token就是您需要使用auth:api警卫进行身份验证的内容。要将其正确传递回您的 api,您需要将后续请求与标头Authorization: Bearer <your accessToken>Accept: application/json

For example, to access your "test" route:

例如,要访问您的“测试”路线:

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

If you've set these correctly, you should see a JSON response with the array you have specified.

如果您正确设置了这些,您应该会看到一个带有您指定数组的 JSON 响应。

Why is /api/test redirecting me with no error?

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

You are requesting a route with the auth:apimiddleware. This will redirect you as you have not specified the correct headers as described above, this is expected behavior.

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

Hope this helps.

希望这可以帮助。