【五一创作】Hyperf3.0创建中间件并使用JWT鉴权

很多小伙伴在使用API与后端通讯是都在想如何更安全高效的鉴权

那么可以在hyperf的自定义中间件中加入jwt完成接口的鉴权

文章开始

JWT 鉴权的重要性主要体现在以下几个方面:

  1. 安全性:JWT 使用数字签名或加密机制来保证传输过程中的安全性,确保传输的信息不会被篡改或伪造。

  2. 可扩展性:JWT 可以轻松地与其他身份验证和授权机制集成,例如 OAuth、OpenID 等。

  3. 无状态性:JWT 本身不需要存储在服务器端,因此可以轻松地扩展应用程序,而无需担心服务器端的负载问题。

  4. 可定制性:JWT 可以携带各种自定义声明,例如用户 ID、角色、权限等,使得开发者能够根据具体的业务需求进行定制。

1.创建中间件

<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Exception\UnauthorizedException;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

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

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var ResponseInterface
     */
    protected $response;

    public function __construct(ContainerInterface $container, RequestInterface $request, ResponseInterface $response)
    {
        $this->container = $container;
        $this->request = $request;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): PsrResponseInterface
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            throw new UnauthorizedException('Token not found');
        }

        $jwt = $this->container->get(\HyperfExt\Jwt\Jwt::class);
        $payload = $jwt->getParser()->parse((string) $token);

        if (!$jwt->verify($payload)) {
            throw new UnauthorizedException('Unauthorized');
        }

        $user = $jwt->getUser($payload['sub']);

        if (!$user) {
            throw new UnauthorizedException('User not found');
        }

        Context::set('user', $user);

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

上述代码,需要在App目录或对应的应用内创建Middleware文件夹,新建JwtAuthMiddleware.php文件并粘贴此代码,其中需要关注的是 process 方法,这里是通过request中的header('Authorization')字段拿到通讯token,并通过jwt的内建方法快速提取用户ID等信息及过期时间,并通过Content协程上下文进行传递

2.在 config/autoload/middlewares.php 中注册中间件

<?php

declare(strict_types=1);

return [
    'http' => [
        ······其他中间件
        \App\Middleware\JwtAuthMiddleware::class,
    ],
];

 这里是注册中间件,加入hyperf的运行流程,方便后续的引用

3.引用中间件去识别用户

这里要注意官方提供了多种方法引用中间件,本篇文章仅简单介绍常用的两种

  1.注解引用

  通过在控制器声明处注解,如下代码

<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\Controller;
use App\Middleware\JwtAuthMiddleware;
use Hyperf\Utils\Context;

/**
 * @Controller()
 * @Middleware(JwtAuthMiddleware::class)
 */
class UserController
{
    /**
     * @PostMapping(path="/user/info")
     */
    public function info()
    {
        $user = Context::get('user');
        return [
            'code' => 0,
            'data' => $user,
        ];
    }
}

  2.绑定路由注解

 在config/routes.php中对指定路由的方法进行鉴权

  如下方代码,将路由/member/user/info 的访问用户加入Jwt自建中间件进行鉴权

use App\Middleware\JwtAuthMiddleware;

Router::addGroup(
    '/member', function () {
        Router::post('/user/info', [\App\Controller\UserController::class, 'info']);
    },
    ['middleware' => [JwtAuthMiddleware::class]]
);

总结

Hyperf 3.0 是一个高性能的 PHP 框架,支持创建中间件并使用 JWT 鉴权去识别用户。

JWT(JSON Web Token)是一种基于 JSON 的开放标准(RFC 7519),用于在网络应用之间传递声明,以便进行身份验证和授权。JWT 由三部分组成:头部、载荷和签名。在 JWT 的载荷中,可以存储一些与用户相关的信息,例如用户的 ID、用户名等。

将两者相结合,可以打造出性能与安全共存的完美的接口安全方案

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了实现SpringBoot+Vue前后端分离的登录界面使用JWT鉴权,需要进行以下步骤: 1.在SpringBoot中配置SpringSecurity,包括用户认证和授权,可以参考引用中的实现方式。 2.在SpringBoot中配置JWT,包括生成Token和解析Token,可以使用jjwt库实现,可以参考引用中的maven依赖配置。 3.在Vue中实现登录界面,包括输入用户名和密码,发送POST请求到后端验证用户信息,并获取Token。 4.在Vue中使用获取到的Token进行后续请求的鉴权,可以在请求头中添加Authorization字段,值为Bearer加上Token。 下面是一个简单的示例代码,仅供参考: 1. SpringBoot中的配置 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } @Bean(BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .and() .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/auth/**") .permitAll() .anyRequest() .authenticated(); // Add our custom JWT security filter http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } } ``` 2. Vue中的登录界面 ```html <template> <div> <h2>Login</h2> <form @submit.prevent="login"> <div> <label>Username:</label> <input type="text" v-model="username" required> </div> <div> <label>Password:</label> <input type="password" v-model="password" required> </div> <button type="submit">Login</button> </form> </div> </template> <script> import axios from 'axios'; export default { data() { return { username: '', password: '' }; }, methods: { async login() { try { const response = await axios.post('/api/auth/login', { username: this.username, password: this.password }); const token = response.data.token; localStorage.setItem('token', token); axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; this.$router.push('/'); } catch (error) { console.error(error); } } } }; </script> ``` 3. Vue中的请求鉴权 ```javascript import axios from 'axios'; const token = localStorage.getItem('token'); if (token) { axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; } axios.get('/api/protected/resource') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值