JWT授权 Laravel / AngularJS问题

3

我正在尝试创建基本的JWT令牌身份验证。

我使用Laravel作为我的后端API,使用tymon/jwt-auth创建令牌/刷新令牌并提供中间件来检查令牌。

我使用AngularJS与Satellizer将返回的令牌存储在本地存储中,并将该令牌发送给所有未来请求。

我使用Laravel 5.1 / Jwt-auth 0.5.* / AngularJs 1.4.7 / Satellizer(最新版本)。

我登录后,令牌被存储在我的本地存储中。然后,我尝试调用authenticate的索引来“获取所有用户”,授权标头带有Bearer <token stored in local storage>,但我得到了“token_not_provided”的响应,就好像中间件没有在授权标头中查找令牌一样。这里是我的一些代码。我遵循https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps

AuthenticateController.php:

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\User;

class AuthenticateController extends Controller
{

    public function __construct()
    {
        // Apply the jwt.auth middleware to all methods in this controller
        // except for the authenticate method. We don't want to prevent
        // the user from retrieving their token if they don't already have it
        $this->middleware('jwt.auth', ['except' => ['authenticate']]);
    }

    public function index()
    {
        // Retrieve all the users in the database and return them
        $users = User::all();
        return $users;
    }

    public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            // verify the credentials and create a token for the user
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        // if no errors are encountered we can return a JWT
        return response()->json(compact('token'));
    }
}

我遇到了这个问题。你找到解决方案了吗? - Marco Aurélio Deleu
我已经研究了几周,但仍然没有解决方案。48次浏览,但也没有解决方案。嗯... - Bill Garrison
我找到了一个解决方案,只是不记得是什么了。让我想一想。你使用Apache吗? - Marco Aurélio Deleu
是的先生....LAMP环境 - Bill Garrison
1个回答

1
当使用Apache时,您需要设置.htaccess以不剪切Authorization头。在path/to/your/project/public/.htaccess中打开.htaccess并添加以下内容。
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

我的翻译如下:

我的就像这个:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On        

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]    


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接