如何在 Laravel 网页中使用令牌认证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45386587/
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 16:24:07  来源:igfitidea点击:

How to use token authentication in laravel web page

phplaravelauthenticationjwt

提问by Niklesh Raut

I am trying to use JWT for laravel web page instead of session. so I made some changes.

我正在尝试将 JWT 用于 Laravel 网页而不是会话。所以我做了一些改变。

  1. Installed jwt-authand configure

  2. Then changed default guard as apiin config/auth.php

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
    
    'guards' => [
        ...
    
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],
    
  1. 安装jwt-auth配置

  2. 然后api在 config/auth.php 中更改默认保护

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
    
    'guards' => [
        ...
    
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],
    

Now I am getting error

现在我收到错误

(1/1) FatalErrorException Call to undefined method Illuminate\Auth\TokenGuard::attempt() in AuthenticatesUsers.php (line 75)

(1/1) FatalErrorException 调用 AuthenticatesUsers.php 中未定义的方法 Illuminate\Auth\TokenGuard::attempt()(第 75 行)

How to fix this and start token authentication for laravel web page(blades not API).

如何解决此问题并为 Laravel 网页(刀片不是 API)启动令牌身份验证。

采纳答案by Niklesh Raut

I found the solutionhere : https://github.com/tymondesigns/jwt-auth/issues/860

我在这里找到了解决方案https: //github.com/tymondesigns/jwt-auth/issues/860

In /routes/api.php - added a few basic authentication routes

在/routes/api.php - 添加了一些基本的身份验证路由

Route::post('login', 'Auth\LoginController@login');

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

In /app/http/Controller/auth/LoginController.php

在/app/http/Controller/auth/LoginController.php

and then override methods in login contoller

然后覆盖登录控制器中的方法

public function login(Request $request)
{
    $credentials = $request->only(["email","password"]);
    if ($token = $this->guard()->attempt($credentials)) {
        return $this->sendLoginResponse($request, $token);
    }

    $this->incrementLoginAttempts($request);
    return $this->sendFailedLoginResponse($request);
}

protected function sendLoginResponse(Request $request, $token)
{
    $this->clearLoginAttempts($request);

    return $this->authenticated($request, $this->guard()->user(), $token);
}

protected function authenticated(Request $request, $user, $token)
{
    setcookie("jwt_token", $token);
    return redirect('/');
    return response()->json([
        'token' => $token,
    ]);
}

protected function sendFailedLoginResponse(Request $request)
{
    return response()->json([
        'message' => "not found",
    ], 401);
}

Adding middleware AddToken

添加中间件 AddToken

public function handle($request, Closure $next)
{
    $token = isset($_COOKIE["jwt_token"])?$_COOKIE["jwt_token"]:"";
    //$request['token'] = $token;//this is working
    $request->headers->set("Authorization", "Bearer $token");//this is working
    $response = $next($request);
    //$response->header('header name', 'header value');
    return $response;
}

Register middleware in Kernel.php

在 Kernel.php 中注册中间件

 protected $middleware = [
    ....
    \App\Http\Middleware\AddToken::class,
];

回答by yixiang

I'm also using jwt protecting our api. You should change your config like below:

我也在使用 jwt 保护我们的 api。您应该像下面这样更改配置:

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

'guards' => [
    ...

    'api' => [
        'driver' => 'jwt', // KEY POINT!!!
        'provider' => 'users',
    ],
],

Make sure the jwt library installed correctly:

确保正确安装了 jwt 库:

  1. Tymon\JWTAuth\Providers\LaravelServiceProvider::class is added in your config/app.php.

  2. Your user model implements JWTSubject interface if you use eloquent model in your provider.

  1. Tymon\JWTAuth\Providers\LaravelServiceProvider::class 被添加到你的 config/app.php 中。

  2. 如果您在提供程序中使用 eloquent 模型,您的用户模型将实现 JWTSubject 接口。

回答by AddWeb Solution Pvt Ltd

I think you can try this :

我想你可以试试这个:

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

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

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

EDIT

编辑

You can find some help from the step by step example. In this example you need to focus on how to configure and use that token base authentication.

您可以从分步示例中找到一些帮助。在此示例中,您需要关注如何配置和使用该令牌基础身份验证。

Hope this help you well.

希望这对你有帮助。

回答by Kevin Patel

Please refer this link. If you are using api as default then laravel authentication will throw an error.

请参考此链接。如果您使用 api 作为默认值,那么 Laravel 身份验证将引发错误。

回答by Oluwatobi Samuel Omisakin

Laravel uses default Session based authentication out of the box with the default scaffolding users-view-controller that you already have. You have additional means of adding your own custom guard in the doc, so you can make use of the guard as needed.

Laravel 使用开箱即用的默认基于会话的身份验证,以及您已经拥有的默认脚手架 users-view-controller。您可以通过其他方式在 doc中添加您自己的自定义保护,因此您可以根据需要使用保护。

Therefore as @KevinPatel suggested, revert back to the default configuration, then in your route: group the route you want to be under JWT authentication, add the JWTMiddleware, in this case you have to update the controller responsible for your authentication to use the JWTAuth instead of the default auth.

因此,正如@KevinPatel 建议的那样,恢复到默认配置,然后在您的路由中:将您想要在 JWT 身份验证下的路由分组,添加 JWTMiddleware,在这种情况下,您必须更新负责身份验证的控制器以使用 JWTAuth而不是默认的身份验证。

You should check this answer if you need to understand it better check this answer on Laracasts

如果你需要更好地理解它,你应该检查这个答案在 Laracasts 上检查这个答案

One recommended way to incorporate the JWTAuthis to go for Dingo API(of course you are not building api, but) because Dingo already added some flesh to the authentication and other routes management - so things are pretty easy to use and configure

合并 JWTAuth 的一种推荐方法是使用Dingo API(当然您不是在构建 api,但是)因为 Dingo 已经为身份验证和其他路由管理添加了一些内容 - 所以事情很容易使用和配置