2015-10-06 103 views
3

所以我想创建一个基本的JWT令牌认证。JWT授权laravel/angularjs问题

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

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

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

我登录后,令牌存储在本地存储中。然后,我试着打电话给authenticntate的索引来“获取所有用户”,并且授权标题与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')); 
    } 
} 
+0

我是从这个问题的痛苦。你找到解决方案吗? –

+0

我已经研究了几个星期,仍然没有解决方案。 48个观点并没有解决方案。 hrmmmm –

+0

我找到了一个解决方案,我只是不记得它是什么。让我考虑一下。你使用Apache吗? –

回答

1

当使用Apache,你需要设置的.htaccess不裁剪出来的Authorization头。

打开的.htaccess在path/to/your/project/public/.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]  

+0

这对我工作!谢谢! –