fenrir-soft/authentication 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

fenrir-soft/authentication

最新稳定版本:1.0.0

Composer 安装命令:

composer require fenrir-soft/authentication

包简介

README 文档

README

Requirements

  • php 8.2+

Installation

Run the command:

$ composer require fenrir-soft/authentication

Add the following to your .env file

JWT_SECRET=you-secret-phrase
JWT_ALG=HS256

Create a src/container-definitions.php file, if you have'nt yet, and add the following:

<?php

use Fenrir\Framework\MiddlewareCollection;
use Rocca\Cdn\Middlewares\AuthMiddleware;
use Rocca\Cdn\Services\JwtService;

return [
    ...
    JwtService::class => function () {
        return new JwtService(
            key: $_ENV['JWT_SECRET'],
            alg: $_ENV['JWT_ALG']
        );
    },
    MiddlewareCollection::class => function () {
        return new MiddlewareCollection(
            AuthMiddleware::class
        );
    },
    ...
]

On your controllers add the #Auth attribute

class MyController {

    #[Route(path: '/admin')]
    #[Auth(roles: ["admin"], permissions: ["admin:access"], redirect_url: "admin/login")]
    public function index() {}
}

To authenticate you'll need to set the Authorization header with a jwt token with the following claims

{
    "role": "admin",
    "acl": ["admin:access"]
}

To create a jwt token you can use the JwtService like this:

<?php

use Fenrir\Framework\Lib\Request;
use Fenrir\Framework\Lib\Response;
use Fenrir\Authentication\Services\JwtService;


class AuthController {
    public function __construct(
        private Request $request,
        private Response $response,
        private JwtService $jwt_service
    ) {}

    public function login() {
        $login = $this->request->get('login', '');
        $password = $this->request->get('password', '');

        if ($login === 'admin' && $password === '12345') {
            $jwt_token = $this->jwt_service->encode([
                'sub' => 'my-user-id',
                'iat' => time(),
                'exp' => time() + 3600, /// valid for one hour
                'role' => 'admin',
                'acl' => ['admin:access']
            ]);

            $this->response->json([
                'jwt' => $jwt_token,                
            ]);
            return;
        }

        $this->response->json([
            'error' => "Invalide username or password"
        ]);
    }
}

统计信息

  • 总下载量: 10
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-10-13