hyperf框架中jwt权限认证

1.安装依赖

composer require firebase/php-jwt

2.配置jwt。 路径 config/autoload/jwt.php

<?php

declare(strict_types=1);

return [
    'key' => 'qewwqeqweqweqweqw',
    'issue' => 'qqqqq',
    'expire' => 7200
];

3.对jwt的封装

<?php
declare(strict_types=1);

namespace App\Service;

use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;

class JWTService
{

    public function encode($data)
    {
        $time = time();
        $key = config('jwt.key');
        $issue = config('jwt.issue');
        $expire = config('jwt.expire');
        $payload = array(
            'iss' => $issue,
            'iat' => $time,
            'nbf' => $time,
            'exp' => $time + $expire,
            'data' => $data
        );
        return JWT::encode($payload, $key);
    }

    public function decode($token)
    {
        $key = config('jwt.key');
        try {
            JWT::$leeway = 120;//当前时间减去60,把时间留点余地
            $decoded = JWT::decode($token, $key, ['']); //HS256是默认方式,`在这里插入代码片`这里要和签发的时候对应
            $arr = (array)$decoded;
            return (array)$arr['data'];
        } catch (SignatureInvalidException $e) {  //签名不正确
            return false;
        } catch (BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return false;
        } catch (ExpiredException $e) {  // token过期
            return false;
        }
    }
}

4.权限验证中间件

<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Service\JWTService;
use App\Service\UserService;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JwtMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var JWTService
     */
    protected $jwtService;

    /**
     * @var UserService
     */
    protected $userService;

    public function __construct(ContainerInterface $container,JWTService $jwtService,UserService $userService)
    {
        $this->container = $container;
        $this->jwtService = $jwtService;
        $this->userService = $userService;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = Context::get(ResponseInterface::class);
        $path = $request->getUri()->getPath();
        $arrPath = explode('/',$path);
        if(is_numeric(end($arrPath))){
            array_pop($arrPath);
            $path = implode('/',$arrPath);
        }
        $ignorePath = config('ignore_path');
        //验证token
        if(!in_array($path,$ignorePath )){
            $hasToken = $request->hasHeader('Authorization');
            $token = $request->getHeaderLine('Authorization');
            if(!$hasToken || empty($token)){
                $data = json_encode([
                    'code' => 402,
                    'message' => '请重新登录'
                ],JSON_UNESCAPED_UNICODE);
                return $response->withStatus(200)->withBody(new SwooleStream($data));
            }
            try{
                $arr = $this->jwtService->decode($token);
            }catch (\Exception $exception){
                $data = json_encode([
                    'code' => 402,
                    'message' => '登录凭证异常,请重新登录'
                ],JSON_UNESCAPED_UNICODE);
                return $response->withStatus(200)->withBody(new SwooleStream($data));
            }

            $userId = (int)$arr['userId'] ?? 0;
            $userInfo = $this->userService->getUserInfo($userId);
            if(empty($userInfo)){
                $data = json_encode([
                    'code' => 402,
                    'message' => '登录凭证异常,请重新登录',
                ],JSON_UNESCAPED_UNICODE);
                return $response->withStatus(200)->withBody(new SwooleStream($data));
            }
            $request = $request->withAttribute('userInfo',$userInfo);
            $request = Context::set(ServerRequestInterface::class,$request);
        }

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

5.在配置文章config/autoload/middlewares中添加权限中间件

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
return [
    'http' => [
        \App\Middleware\JwtMiddleware::class,
    ],
];
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 .NET JWT(JSON Web Token)是一种常见的认证方式。JWT 是一个开放标准,可以在网络上安全地传输信息,包括用户身份和权限。 下面是一个简单的示例,演示如何在 .NET 使用 JWT 进行权限认证: 1. 首先,你需要安装一个 JWT 库。例如,Microsoft 提供了一个名为 Microsoft.AspNetCore.Authentication.JwtBearer 的库,可以用于 ASP.NET Core 应用程序。 2. 在应用程序配置 JWT 认证服务。这通常涉及到指定 JWT 密钥,以及设置哪些控制器或方法需要进行身份验证和授权。 ```csharp services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "your_issuer", ValidAudience = "your_audience", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")) }; }); ``` 3. 在控制器或方法上使用 Authorize 属性标记,以确保只有经过身份验证和授权的用户才能访问它们。 ```csharp [Authorize] public class SecureController : ControllerBase { // ... } ``` 4. 当用户登录后,生成一个 JWT 并将其返回给客户端。客户端将在每个请求JWT 作为 Authorization 标头发送回服务器。 ```csharp var claims = new List<Claim> { new Claim(ClaimTypes.Name, "user_name"), new Claim(ClaimTypes.Role, "user_role") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "your_issuer", audience: "your_audience", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); ``` 以上是一个简单的 .NET JWT 权限认证的示例。当然,实际情况可能更加复杂,具体实现方式取决于你的应用程序需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值