我正在尝试使用Laravel 5.3和Angular 2与JWT实现身份验证。
Auth部分正在工作,我可以获得令牌,但我正试图唠叨任何获取路线,我收到错误
代码
我添加了提供程序和别名,以及公开vendor文件夹并生成了jwt的密钥
在我的内核中我添加了这个:
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \TymonJWTAuth\Middleware\RefreshToken::class,
已禁用csrfToken。
这些是我的路线
Route::resource('authenticate', 'AuthController', ['only' => ['index']]);
Route::post('authenticate', 'AuthController@authenticate');
Route::post('logout', 'AuthController@logout');
我的AuthController
class AuthController 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']]);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// Get all roles
$users = User::with('role', 'branch')->get();
// Send the response
return response()->json([
'users' => $users
], 200);
}
// Authentification
public function authenticate(Request $request)
{
// Retrieve email
$email = $request->input('email');
$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);
}
// Retrieve user
$user = User::where('email', '=', $email)->first();
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
// return response()->json([
// 'user' => $user,
// 'token' => compact('token')
// ], 200);
}
// Logout
public function logout(Request $request)
{
$this->validate($request, [
'token' => 'required'
]);
JWTAuth::invalidate($request->input('token'));
}
}
正如我所说,我可以在验证后获得令牌,但是当我使用此令牌导航到某个路径时,就像这个:
Route::resource('authenticate', 'AuthController', ['only' => ['index']]);
我得到了这个结果:
{
"error": "token_not_provided"
}
答案 0 :(得分:0)
如果您的网络服务器是apache。你需要添加这个
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
到/path/to/project/public/.htaccess
中的htaccess文件。
这通常是导致此错误的原因。请查看此链接以获取更多信息。 https://github.com/tymondesigns/jwt-auth/wiki/Authentication