我想在我的Laravel中追加Authorization: Bearer {yourtokenhere}
。如果在邮递员中我将授权放在标题选项卡上并通过编写Bearer {token}
手动给出标记值,这样我可以保护特定的路由,但是如何在Laravel源代码中执行此操作?我应该在我的控制器中做什么,或者我应该在Middleware或Kernel或其他地方添加另一种方法?这是因为我得到{"error":"token_not_provided"}
每一个访问受jwt.auth middleware
保护的路线。
这是我受保护的路线,给我{"error":"token_not_provided"}
:
Route::group(['middleware' => ['jwt.auth']], function(){
Route::get('/dashboard', 'AppController@dashboard');
});
这是我在AuthController中的signin方法:
public function signin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
// grab credentials from the request
$credentials = $request->only('username', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json([
'error' => 'Invalid Credentials, username and password dismatches. Or username may not registered.',
'status' => '401'
], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json([
'user_id' => $request->user()->id,
'token' => $token
]);
}
你可以这样设置
$request = Request::create(route('abc', 'GET');
$request->headers->set('X-Authorization', 'xxxxx');
有关更多信息,您可以按照此stackoverflow回答How to set headers for forwarded request
如果您使用jwt,您甚至可以将您的令牌传递给网址,就像www.example.com/post?token=kjdhfkjsffghrueih
一样
就像你说的那样,你需要在AuthAcontroller
这个,然后你必须在客户端设置它。首先将该令牌存储在localstorage中,并将该令牌设置为来自localstorage的http调用(通过ajax或axios我猜),然后将请求发送到laravel。
要在ajax调用中访问,您可以使用下面的代码
headerParams = {'Authorization':'bearer t-7614f875-8423-4f20-a674-d7cf3096290e'}; //token form localstorage
然后在ajax中使用它
type: 'get',
url: 'https://api.sandbox.slcedu.org/api/rest/v1/students/test1',
headers: headerParams,
或者如果你使用axios,你可以设置它
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('SecurityKey');