php - 登录后向每个请求/链接添加令牌(laravel)
问题描述
这个问题可能会重复,但我可能需要一些指导。
场景:用户登录 web 后,laravel 中的登录控制器会将 JWT 令牌返回给客户端并保存在浏览器本地存储中。之后,发送到服务器的每个链接(href)或请求都需要带有令牌的授权标头(在中间件中进行验证)。
我有主页:
<a href="{{ route('devices') }}" id="mylink">Click me</a>
<button type="submit" id="submit-button">Submit</button>
和
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: { "xCustomHeader": "xmyValue" }
});
$("#mylink").click(function(e) {
var link = $(this).attr('href'); // get the anchor href link
//attach the token from local storage
$.ajaxSetup({
headers: { "Authorisation ": "xxxxxx" }
});
//get request to web php route for GET request
//mostly problem here??
$.ajax({
method: "get",
url: link
});
});
</script>
这是 web.php 路线:
Route::get('/devices', 'DevicesController@index')->name('devices');
这是 DevicesController 类:
public function __construct()
{
$this->middleware('token.verify'); //check whether the token is provided in Authorisation header
}
public function index(Request $request)
{
$location = $this->getUnitLatLng();
return View::make("devices")->with($location); //return view
}
这是 TokenVerify 中间件类:
public function handle($request, Closure $next, $guard = null)
{
try {
$token = $request->header('Authorisation');
if ($token) {
return $next($request);
}
} catch (Exception $ex) {
$response = array('success' => false, 'data' => null, 'detail' => array('message' => 'Messages::MSG_ERROR_500', 'error' => array($ex)));
return response()->json($response);
}
}
问题:登录主页后,点击“点击我”锚点后,中间件似乎没有获得授权标头令牌。Href 链接无法附加标头,因此我使用 ajax 并获取视图。
但中间件仍然没有得到标题。有什么想法和修改吗?如何将标头令牌附加到按钮/href 链接?
解决方案
推荐阅读
- javascript - 如何制作下拉类别列表?
- php - 如何将控制器中的 foreach 放入刀片 laravel 中的表视图中
- github - 使用 github 进行 Spring Cloud 配置
- java - 在 Java 中使用 .equals()、.isEmpty() 和 .length() 检查空字符串
- amazon-web-services - S3 | 对存储桶应用加密但排除其中的文件夹
- html - Content.jsp 显示在一个小的左上角区域,没有充满白色背景的页面。如何设置 CSS?
- angular - 为什么我得到标志“?” 在 URL 的开头并在导航绝对路径时重新启动应用程序?
- php - 在类别页面上显示数量 Magento 2
- tensorflow - RNN 使用均方误差不收敛
- laravel - Laravel 无法使用已软删除用户的 Token