Laravel令牌签名无法验证 [英] Laravel Token Signature could not be verified

查看:1836
本文介绍了Laravel令牌签名无法验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel/Lumen作为Web应用程序后端的API,并且遇到了麻烦.

I'm using Laravel/Lumen as an API for the backend of a webapp and run into a hiccup.

在一个示例中,我有一条不需要对用户进行身份验证的路由.但是我确实想检查访问用户是否具有有效令牌的路径控制器 .

In an example I have a route that does not need the user to be authenticated. But I do want to check in the routes controller if the user visiting has a valid token.

所以我写了以下内容:

    if ($tokenFetch = JWTAuth::parseToken()->authenticate()) {
        $token = str_replace("Bearer ", "", $request->header('Authorization'));
    } else {
        $token = '';
    }

我相信以上内容将检查Bearer令牌是否有效,否则它将返回一个空白变量.

I believe the above will check the Bearer token is valid else it will return a blank variable.

以下是我的整个控制器.

public function show($url, Request $request)
    {

        if ($tokenFetch = JWTAuth::parseToken()->authenticate()) {
            $token = str_replace("Bearer ", "", $request->header('Authorization'));
        } else {
            $token = 'book';
        }
        return response()->json(['token' => $token]);
    }

问题

如果我通过了有效的令牌载体,它将返回令牌,但是如果我通过了无效的令牌,则会出现以下错误:

If I a pass in a valid Token Bearer, it returns the token but if I pass in an invalid one I get the following error:

NamshiAdapter.php第62行中的

TokenInvalidException:

TokenInvalidException in NamshiAdapter.php line 62:

令牌签名无法验证.

如果我根本不传递令牌:

If I don't pass a token at all:

JWTAuth.php第195行中的JWTException:

JWTException in JWTAuth.php line 195:

无法从请求中解析令牌

有没有一种方法可以检查令牌是否已传递,是否已经校验了令牌是否有效,还可以检查令牌是否已传递,然后返回空返回值?

Is there a way to check if a token is passed and if it has then check if its valid, but also if one has not been passed then return a blank return?

推荐答案

您可以将其包装在try/catch块中

You can wrap it inside try/catch block

public function show($url, Request $request)
{
    try {
        $tokenFetch = JWTAuth::parseToken()->authenticate()) 
        $token = str_replace("Bearer ", "", $request->header('Authorization'));
    }catch(\Tymon\JWTAuth\Exceptions\JWTException $e){//general JWT exception
        $token = 'book';
    }
    return response()->json(['token' => $token]);
}

您可能需要单独处理一些例外情况( jwt- auth/Exceptions )

此外,当您使用laravel 5时,可以全局处理JWT异常,在这种情况下不建议这样做,但您应该了解此选项并选择自己. app/Exceptions/Handler.phprender方法内部添加[顶部]

Also as you're using laravel 5 you can global handling for JWT exceptions ,not recommended in this case but you should know of this option and choose yourself. app/Exceptions/Handler.php and inside render method add [at the top]

if ($e instanceof \Tymon\JWTAuth\Exceptions\JWTException) {
    //what happen when JWT exception occurs
}

这篇关于Laravel令牌签名无法验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆