Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

$this->auth->guard('api')->checkOrFail();不起作用 #10

Closed
taobali32 opened this issue Mar 15, 2021 · 1 comment
Closed

$this->auth->guard('api')->checkOrFail();不起作用 #10

taobali32 opened this issue Mar 15, 2021 · 1 comment

Comments

@taobali32
Copy link

taobali32 commented Mar 15, 2021

问题:

$this->auth->guard('api')->checkOrFail(); 不能拦截,并且后续打印当前用户为空

流程:

中间件代码

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            $this->auth->guard('api')->checkOrFail();

        }catch (TokenExpiredException $e){

            var_dump(2231);
            if ($e->getMessage() == 'Token has expired') {

                return $this->response->json(
                    [
                        'code' => 401,
                        'data' => [],
                        'msg'  => '登陆失效'
                    ]
                );
//                throw new \Exception($e->getMessage());
            }

        }catch (TokenInvalidException $exception){

            return $this->response->json(
                [
                    'code' => 401,
                    'data' => [],
                    'msg'  => 'token错误'
                ]
            );
//            throw new \Exception($exception->getMessage());

        }catch (\Throwable $throwable){

            $msg = $throwable->getMessage() == 'A token is required' ? '没有TOKEN' : '请登录';
            return $this->response->json(
                [
                    'code' => 401,
                    'data' => [],
                    'msg'  => $msg
                ]
            );

        }

        return $handler->handle($request);
    }

控制器

    public function ti(TiRequest $request): array
    {
        $post = $request->validated();

        $user = $this->auth->guard('api')->user();

        var_dump($user ); 
    }

版本

"hyperf-ext/auth": "^2.1",
"hyperf-ext/jwt": "^2.1",

jwt.php配置

<?php

declare(strict_types=1);
/**
 * This file is part of hyperf-ext/jwt
 *
 * @link     https://github.com/hyperf-ext/jwt
 * @contact  [email protected]
 * @license  https://github.com/hyperf-ext/jwt/blob/master/LICENSE
 */
return [
    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Secret
    |--------------------------------------------------------------------------
    |
    | Don't forget to set this in your .env file, as it will be used to sign
    | your tokens. A helper command is provided for this:
    | `php bin/hyperf.php gen:jwt-secret`
    |
    | Note: This will be used for Symmetric algorithms only (HMAC),
    | since RSA and ECDSA use a private/public key pair (See below).
    |
    | Note: This value must be encoded by base64.
    |
    */

    'secret' => env('JWT_SECRET'),

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Keys
    |--------------------------------------------------------------------------
    |
    | The algorithm you are using, will determine whether your tokens are
    | signed with a random string (defined in `JWT_SECRET`) or using the
    | following public and private keys. A helper command is provided for this:
    | `php bin/hyperf.php gen:jwt-keypair`
    |
    | Symmetric Algorithms:
    | HS256, HS384 & HS512 will use `JWT_SECRET`.
    |
    | Asymmetric Algorithms:
    | RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
    |
    */

    'keys' => [
        /*
        |--------------------------------------------------------------------------
        | Public Key
        |--------------------------------------------------------------------------
        |
        | Your public key content.
        |
        */

        'public' => env('JWT_PUBLIC_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Private Key
        |--------------------------------------------------------------------------
        |
        | Your private key content.
        |
        */

        'private' => env('JWT_PRIVATE_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Passphrase
        |--------------------------------------------------------------------------
        |
        | The passphrase for your private key. Can be null if none set.
        |
        | Note: This value must be encoded by base64.
        |
        */

        'passphrase' => env('JWT_PASSPHRASE'),
    ],

    /*
    |--------------------------------------------------------------------------
    | JWT time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in seconds) that the token will be valid for.
    | Defaults to 1 hour.
    |
    | You can also set this to null, to yield a never expiring token.
    | Some people may want this behaviour for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    | Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
    |
    */

    'ttl' => env('JWT_TTL', 1000000),

    /*
    |--------------------------------------------------------------------------
    | Refresh time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in seconds) that the token can be refreshed
    | within. I.E. The user can refresh their token within a 2 week window of
    | the original token being created until they must re-authenticate.
    | Defaults to 2 weeks.
    |
    | You can also set this to null, to yield an infinite refresh time.
    | Some may want this instead of never expiring tokens for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    |
    */

    'refresh_ttl' => env('JWT_REFRESH_TTL', 3600 * 24 * 14),

    /*
    |--------------------------------------------------------------------------
    | JWT hashing algorithm
    |--------------------------------------------------------------------------
    |
    | Specify the hashing algorithm that will be used to sign the token.
    |
    | possible values: HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512
    |
    */

    'algo' => env('JWT_ALGO', 'HS512'),

    /*
    |--------------------------------------------------------------------------
    | Required Claims
    |--------------------------------------------------------------------------
    |
    | Specify the required claims that must exist in any token.
    | A TokenInvalidException will be thrown if any of these claims are not
    | present in the payload.
    |
    */

    'required_claims' => [
        'iss',
        'iat',
//        'exp',
        'nbf',
        'sub',
        'jti',
    ],

    /*
    |--------------------------------------------------------------------------
    | Persistent Claims
    |--------------------------------------------------------------------------
    |
    | Specify the claim keys to be persisted when refreshing a token.
    | `sub` and `iat` will automatically be persisted, in
    | addition to the these claims.
    |
    | Note: If a claim does not exist then it will be ignored.
    |
    */

    'persistent_claims' => [
        // 'foo',
        // 'bar',
    ],

    /*
    |--------------------------------------------------------------------------
    | Lock Subject
    |--------------------------------------------------------------------------
    |
    | This will determine whether a `prv` claim is automatically added to
    | the token. The purpose of this is to ensure that if you have multiple
    | authentication models e.g. `App\User` & `App\OtherPerson`, then we
    | should prevent one authentication request from impersonating another,
    | if 2 tokens happen to have the same id across the 2 different models.
    |
    | Under specific circumstances, you may want to disable this behaviour
    | e.g. if you only have one authentication model, then you would save
    | a little on token size.
    |
    */

    'lock_subject' => true,

    /*
    |--------------------------------------------------------------------------
    | Leeway
    |--------------------------------------------------------------------------
    |
    | This property gives the jwt timestamp claims some "leeway".
    | Meaning that if you have any unavoidable slight clock skew on
    | any of your servers then this will afford you some level of cushioning.
    |
    | This applies to the claims `iat`, `nbf` and `exp`.
    |
    | Specify in seconds - only if you know you need it.
    |
    */

    'leeway' => env('JWT_LEEWAY', 0),

    /*
    |--------------------------------------------------------------------------
    | Blacklist Enabled
    |--------------------------------------------------------------------------
    |
    | In order to invalidate tokens, you must have the blacklist enabled.
    | If you do not want or need this functionality, then set this to false.
    |
    */

    'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),

    /*
    | -------------------------------------------------------------------------
    | Blacklist Grace Period
    | -------------------------------------------------------------------------
    |
    | When multiple concurrent requests are made with the same JWT,
    | it is possible that some of them fail, due to token regeneration
    | on every request.
    |
    | Set grace period in seconds to prevent parallel request failure.
    |
    */

    'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),

    /*
    |--------------------------------------------------------------------------
    | Blacklist Storage
    |--------------------------------------------------------------------------
    |
    | Specify the handler that is used to store tokens in the blacklist.
    |
    */

    'blacklist_storage' => HyperfExt\Jwt\Storage\HyperfCache::class,
];

代码中间件

image

出错token

bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJodHRwOlwvXC9hcGkucm9hLmppYWJhb2xlc2hvcC5jb21cL2FwaVwvYXV0aFwvbG9naW4iLCJpYXQiOjE2MTU1MzcyMzgsImV4cCI6MTYxNjUzNzIzOCwibmJmIjoxNjE1NTM3MjM4LCJqdGkiOiJuSWR2UWNmMEhweUxxWmp5Iiwic3ViIjoxMDAwNTU1LCJwcnYiOiJmNmI3MTU0OWRiOGMyYzQyYjc1ODI3YWE0NGYwMmI3ZWU1MjlkMjRkIn0.GFCOnwmiq-YzD2F8877yr0IIyzyY_OIXIAQELRG6Ceu_FYPNd2PfdCWqm7Zw-oWGkFCNOPB2g43_XYh_uFfEug

运行结果

image

结果非常致命, 现在我的临时解决

   $user = $this->auth->guard('api')->user();
            
            if (empty($user)){
                //  more...
            }

问题发现

这个token应该是前n天生成的,今天偶然测试,发现checkOrFail不能拦截了

其他

我在 链接 中补充了常用使用方式,然后 $this->auth->guard('api')->checkOrFail(); 是大佬帮我补充的

我的.env

JWT_SECRET=MBe71G4hdUdUxROnamk4dFYkVRVY5c2BekIdvDt2ZqJuXORaQLliE8SnIPPPdRwwDLlCLTnfb4k2FdIwru/ELg==
JWT_PRIVATE_KEY="-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIJnDBOBgkqhkiG9w0BBQ0wQTApBgkqhkiG9w0BBQwwHAQILsX69csRlUMCAggA\nMAwGCCqGSIb3DQIJBQAwFAYIKoZIhvcNAwcECLUjDd9rb6OtBIIJSBXf6Daui41H\nxMUQ8+9T3eRBE0M1QWEUeKzEau5tBJ/oErSKaqO89RUMwFj9cOjN3TDwdLadUC25\nDEIGlY9JKxVKQ38Vzd+jLcZq6Q7HfFYLbLy+WXHLRk32pVgnLXsCSn8bS4s7ZFKE\nOpR2UCOW/WxIiUoLaD7IT3Mfre4sJDcnR9EcFvb8X3/X1Tjran2eGGv8qM5DOKD9\n2FWqrCoJne47Y2ZS54bFebFZSGelN7vsQ88+6e9K3st6VkPjrXpjKAMyEB1JxJpL\n+UeJEHoRGjpkuPxfoTYw8+Aoi52E+BFZnUoqshSDbwlHCWlmMLecPSDR7DCUoSyb\nd51VYS66prdFXnaRcoMRzZK/GnoS3ctudVZbjjRuBNGqg27O0mBDU5bU3N5nicSn\n5p7v7PQUbhx39XE1tJEDWdbxl9BAgBUVMmlihielgZCW+AHsCfD1tFX3/QgOzGdP\nl2jg9lGDT5OxVZgIwFkk7A59FWhQiDya7I2DtlVPYauXFl4cDsSMpCvdlz4NUDWF\n8I+4OFDASAFpqVrJeyDT2dISAEdKu89gbqJj5pEEKtPng3P4zivQzBIF96YcCPVP\nsF78rk3nse/L0D//GqVl5Ye8n8iH8c9cKPJbvKUAhYXDCRzoUKrPIHD00Utsl/6O\nkpcRmNLV1xoNZYBBua4hmPn1Q64XMZktCZiH+ggVBndy6ggzyqcQyGTQKQGh+iJP\nMnX7CxFag4vXIM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a3y7akPcl81DtfYlG6UdbLHVrmQnKiVS\ndgWYMrGzgssIMIsw8Mn+dVzpvsypDkCK9YBzFtTal7E+ly38deBFCdR29JcCYsHb\ntZ7pWxFF5BTL1H9lwztd/6kCAwEAAQ==\n-----END PUBLIC KEY-----\n"
JWT_PASSPHRASE="i29jy/McO4/RulZTm5U0WQ=="
@taobali32
Copy link
Author

问题已解决, 因为现在测试期间大量生成测试数据,然后登陆,注册操作等, 该token出现在 账号删除了 这个token还能验证成功,进入控制器。。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant