2015-10-06 107 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

這對我工作!謝謝! –