首页 > 解决方案 > 登录后向每个请求/链接添加令牌(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 链接?

标签: phpajaxlaravelhttpmiddleware

解决方案


你可能缺乏这里preventDefault()描述的。此外,如果您将此库用于 JWT,那么您可以将令牌包含在查询字符串中,例如http://api.mysite.com/me?token={yourtokenhere}


推荐阅读