Laravel 5.3 Passport 自定义补助金?

2023-12-30

我知道我不是唯一一个走到这一步的人。有谁知道如何properly在 Laravel(5.3) Passport 中实现自定义授权?

Or

有一个很好的链接/教程来参考如何正确执行此操作吗?

我知道有这个包:

https://github.com/mikemclin/passport-custom-request-grant https://github.com/mikemclin/passport-custom-request-grant

但我要求更多的是“自己动手”的方法。

先感谢您。


namespace App\Providers;

use App\Auth\Grants\FacebookGrant;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Bridge\RefreshTokenRepository;
use Laravel\Passport\Passport;
use League\OAuth2\Server\AuthorizationServer;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        app(AuthorizationServer::class)->enableGrantType(
            $this->makeFacebookGrant(), Passport::tokensExpireIn()
        );

        Passport::routes();

        //
    }

    /**
     * Create and configure a Facebook grant instance.
     *
     * @return FacebookGrant
     */
    protected function makeFacebookGrant()
    {
        $grant = new FacebookGrant(
            $this->app->make(RefreshTokenRepository::class)
        );

        $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());

        return $grant;
    }
}

编辑: 抱歉,仅发布此代码,我不知道此代码对您有多大用处。

好吧,我将在这里留下我的 FacebookGrant 实现,希望这对某人有所帮助。

<?php

namespace App\Auth\Grants;

use Illuminate\Http\Request;
use Laravel\Passport\Bridge\User;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\UserEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\AbstractGrant;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use League\OAuth2\Server\RequestEvent;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;

class FacebookGrant extends AbstractGrant
{
    /**
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
     */
    public function __construct(
        RefreshTokenRepositoryInterface $refreshTokenRepository
    ) {
        $this->setRefreshTokenRepository($refreshTokenRepository);

        $this->refreshTokenTTL = new \DateInterval('P1M');
    }

    /**
     * {@inheritdoc}
     */
    public function respondToAccessTokenRequest(
        ServerRequestInterface $request,
        ResponseTypeInterface $responseType,
        \DateInterval $accessTokenTTL
    ) {
        // Validate request
        $client = $this->validateClient($request);
        $scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
        $user = $this->validateUser($request, $client);

        // Finalize the requested scopes
        $scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client, $user->getIdentifier());

        // Issue and persist new tokens
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $scopes);
        $refreshToken = $this->issueRefreshToken($accessToken);

        // Inject tokens into response
        $responseType->setAccessToken($accessToken);
        $responseType->setRefreshToken($refreshToken);

        return $responseType;
    }

    /**
     * @param ServerRequestInterface $request
     *
     * @return UserEntityInterface
     * @throws OAuthServerException
     */
    protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
    {
        $facebookId = $this->getRequestParameter('facebook_id', $request);
        if (is_null($facebookId)) {
            throw OAuthServerException::invalidRequest('facebook_id');
        }

        $email = $this->getRequestParameter('email', $request);
        if (is_null($email)) {
            throw OAuthServerException::invalidRequest('email');
        }

        $user = $this->getUserEntityByUserFacebookId(
            $facebookId,
            $email,
            $this->getIdentifier(),
            $client
        );

        if ($user instanceof UserEntityInterface === false) {
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));

            throw OAuthServerException::invalidCredentials();
        }

        return $user;
    }

    /**
     *  Retrieve a user by the given Facebook Id.
     *
     * @param string  $facebookId
     * @param string  $email
     * @param string  $grantType
     * @param \League\OAuth2\Server\Entities\ClientEntityInterface  $clientEntity
     *
     * @return \Laravel\Passport\Bridge\User|null
     * @throws \League\OAuth2\Server\Exception\OAuthServerException
     */
    private function getUserEntityByUserFacebookId($facebookId, $email, $grantType, ClientEntityInterface $clientEntity)
    {
        $provider = config('auth.guards.api.provider');

        if (is_null($model = config('auth.providers.'.$provider.'.model'))) {
            throw new RuntimeException('Unable to determine authentication model from configuration.');
        }

        $user = (new $model)->where('facebook_id', $facebookId)->first();

        if (is_null($user)) {
            $user = (new $model)->where('email', $email)->first();

            if (is_null($user)) {
                return;
            }

            // Now that we retrieved the user with the email, we need to update it with
            // the given facebook id. So the user account will be linked correctly.
            $user->facebook_id = $facebookId;
            $user->save();
        }

        return new User($user->getAuthIdentifier());
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentifier()
    {
        return 'facebook';
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 5.3 Passport 自定义补助金? 的相关文章

  • 作曲家 | laravel 5 - 更新依赖项但框架本身

    我正在为我的项目使用 Laravel 5 的预测试版 我发现 Laravel 5 的应用程序框架在 github 存储库中发生了更改 并且由于它是开发版本 因此预计会经常更改 我的问题是 我可以使用 Composer 只更新特定的依赖项而不
  • 重置密码 电子邮件

    我是 Laravel 开发新手 目前正在从事小型项目 我想自定义重置密码的电子邮件模板 甚至将其链接到完全不同的模板 对于身份验证脚手架 我使用了php artisan make auth命令 但是 默认重置密码功能使用默认的 Larave
  • 如何在 Laravel 查询中使用多个 OR,AND 条件

    我需要 Laravel 查询帮助 我的自定义查询 返回正确结果 Select FROM events WHERE status 0 AND type public or type private 如何写这个查询Laravel Event w
  • 在 Eloquent 中定义自定义属性

    我的数据库中有 3 个不同的字段 city state country 如何在 Eloquent 中定义另一个属性以从这 3 个字段返回一个字符串 第一种方法 但不起作用 protected address public function
  • AWS-PHP-SDK / SNS 直接寻址返回错误

    您好 我正在使用 Laravel 4 设置来利用 AWS SNS 向我的 iOS 设备发送推送消息 从 AWS 控制台向我的设备发布命令效果很好 然后我尝试从 PHP sns AWS get sns sns gt publish array
  • Laravel Vue 组件只能传递数字?

    在我的 UserMenu vue 中我写道 export default props nameVal data return 并在blade php中
  • 如何使用更新资源控制器 laravel 4?

    我有带有索引 编辑 更新方法的客户控制器 Route resource customer CustomerController 控制器方法更新 public function update id echo id 我的 HTML 表单
  • Laravel 警告:未知:无法打开流:第 0 行的“未知”中没有此类文件或目录

    使用以下命令创建新的 Laravel 项目后 laravel 新 项目名称 一开始它运行了 但第二次运行后我收到错误消息 警告 未知 无法打开流 第 0 行的 未知 中没有此类文件或目录 致命错误 未知 无法打开第 0 行未知中所需的 D
  • Laravel 4 使用资源控制器轻松删除记录

    我是 Laravel 框架的新手 但我真的很喜欢它 我最大的问题是我一直在寻找如何使用资源控制器删除单个记录 控制器方法 public function destroy id department Department find id de
  • 分页在服务器端好还是前端好? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我正在构建 Laravel Vue 应用程序 我想知道在后端使用分页还是在前端使用分页更好 我认为最好在每页发送尽可能少的数据的请求 但我想听听
  • Laravel 5 使用语句[重复]

    这个问题在这里已经有答案了 第一次使用 Laravel 5 我了解命名空间的使用以及为什么需要使用它们 我不明白的是为什么我需要添加如下所示的 use 语句 在控制器的顶部 use Session use Input use Respons
  • Laravel - 记录“找不到路线”

    当找不到路线时 我没有看到任何日志输出 我在开发模式下运行 laravel 当遇到不存在的路线时 我会看到此错误 message exception Symfony Component HttpKernel Exception NotFou
  • 如何使用 Laravel IoC 将数据库注入构造函数

    我想使用 DB 类与 IoC 容器进行事务处理 use Illuminate Database Connection as DB public function construct DB db this gt db db 但是当使用 db
  • Laravel - 保存在存储文件夹中的图像不向用户显示

    我有这段代码可以将图像保存在 storage app uploads 文件夹中 image main Image where property id id gt get file request gt file file destinati
  • Laravel http 请求:无法运行多个请求

    我在 Laravel http 请求方面遇到了严重的问题 请帮我解决这个问题 我假设我有 2 个请求路由到相同的控制器 Req 1 http localhost 8000 manualScheduler runScript task nam
  • Laravel 验证规则仅针对字母

    我正在尝试添加验证规则以仅接受信件 我正在使用regex规则 但它仍然不起作用 下面是我的代码 Validate request input this gt validate request name gt required regex p
  • 使用 Laravel 4 验证多个文件上传

    如何在 Laravel 4 中验证上传文件的数组 我已将其设置为允许多个文件 并且已测试这些文件是否存在于 Input file files 数组中 但如何验证每个文件呢 这是我尝试过的 notesData array date gt In
  • Laravel 从 5.6 升级到 Laravel 6

    我有一个项目https github com javedbaloch4 Laravel Booking https github com javedbaloch4 Laravel Booking发展于Laravel 5 6现在我想将其升级到
  • 在 apache docker 容器中运行虚拟主机

    我在同一个 apache 容器中有两个 php 应用程序 我试图在端口上运行其中一个应用程序 因为它需要通过根域而不是子文件夹进行访问 我想在端口 8060 上运行应用程序 我尝试使用 apache 虚拟主机执行此操作 但它不会加载页面 h
  • 无法显示 Laravel 欢迎页面

    我的服务器位于 DigitalOcean 云上 我正在使用 Ubuntu 和 Apache Web 服务器 我的家用计算机运行的是 Windows 7 我使用 putty 作为终端 遵循所有指示https laracasts com ser

随机推荐

  • UWP 检查当前页面的名称或实例

    在我的 UWP 应用程序中 我从协议或 toast 启动 在 onactivated 方法中 我想检查应用程序的主视图是否打开或正在显示哪个页面 全部来自 App xaml cs 我想做这样的事情 If Mainpage is not sh
  • JFreeChart:鼠标单击获取数据源值

    我有一个显示进程内存状态的 JFreeChart 实例 初始化如下 m data new TimeSeriesCollection TimeSeries vmsize new TimeSeries VMSize TimeSeries res
  • java.security.InvalidKeyException:密钥长度不是 128/192/256 位

    我是 Java 新手 尝试使用混合加密 使用 AES 128 对称加密 然后对生成的对称密钥使用 RSA 1024 非对称加密 有人可以帮助我为什么会收到此异常吗 我已经关注了其他帖子 并在相应的文件夹中下载了 Java 加密扩展 JCE
  • R图上的纸张边框

    不确定 R 的plot ly 函数是否具有此功能 我还没有找到它 但我想我会问 Plot ly 确实有一个 paper bgcolor 参数 可以更改绘图所在纸张的颜色 如下所示 mydf data frame x 1 5 y 1 5 pl
  • 没有意图过滤器的 Android BroadcastReceiver

    我在一些 Android 广告网络 sdks 中看到他们声明BroadcastReceiver没有意图过滤器 像这样的事情
  • 从容器连接到主机服务的示例

    我是 Docker 和无人机编程的新手 我能够将 python 脚本 包含 Dronekit 代码 部署到 Windows 10 上的 docker 容器 要运行该脚本 我需要连接到主机上的服务 我在下面提供了一个片段 Windows 有一
  • android:无法制作多线芯片组

    我在相对布局中有一个芯片组以及一个文本视图 其代码如下所示
  • 使用 C++ 静态控制背景颜色

    我正在使用 Windows API 创建一个基本的 GUI 但遇到了一个问题 它从一个主窗口开始 该窗口以我设置的自定义背景颜色打开 RGB 230 230 230 然后 它使用静态控件在左上角显示文本 settingstext Creat
  • 如何在 Windows 上挂载 docker 套接字?

    我正在尝试使一个仅在 Unices 上开发的应用程序在 Windows 上运行 它全部是 dockerized 的 并且使用 traefik 负载均衡器 用于运行 traefik 的 docker 的卷如下所示 volumes var ru
  • Photoshop 沿 y 轴移动图层

    我正在编写一个脚本 该脚本将向右 向左 向上或向下移动图层 这取决于图层的哪个边缘位于画布内 我已经设法使用bounds 0 和bounds 2 使图层左右移动 x轴 但是当我尝试让它向上或向下移动时 它仍然向左 向右移动 难道是我的边界数
  • PHP Zend Route Config.ini - 类似模式

    我正在使用配置文件在我的应用程序中路由我的请求 我有以下条目 路线 deal route deal id 路线 deal defaults controller 交易 路线 deal defaults action 索引 路线 deal r
  • Azure - 在 Powershell 中断开 VNet 集成

    通过 Azure 门户 我可以断开 VNet 集成 如下所示 我需要使用 Az 模块在 Powershell 脚本中执行此操作 这可能吗 只需使用下面的命令 它在我这边工作得很好 Remove AzResource ResourceGrou
  • axios 不发送参数的 POST 请求

    我正在尝试使用以下代码将一些数据从 Vue js 发布到基于 Symfony 的后端 updateQuestion function axios post staff question api this id id test name sr
  • IOError:[Errno 2]没有这样的文件或目录[重复]

    这个问题在这里已经有答案了 我在尝试对文件夹中的许多文件运行迭代时遇到问题 这些文件存在 如果我从文件打印文件 我可以看到它们的名称 我对编程很陌生 你能帮我一下吗 亲切的问候 import os for path dirs files i
  • 如何设置 javapns(iOS 推送通知)?

    我查看了 javapns 的文档 wiki http code google com p javapns http code google com p javapns 不幸的是 本应显而易见的事情对我来说却并非如此 如何设置有效的推送通知服
  • ‘(’ 标记之前预期的构造函数、析构函数或类型转换

    编译polygone h and polygone cc给出错误 polygone cc 5 19 error expected constructor destructor or type conversion before token
  • 从存储过程获取输出参数而不调用execute()

    我想通过实体管理器从 Java 程序中调用 PL SQL 存储过程 StoredProcedureQuery storedProcedureQuery entityManager createStoredProcedureQuery som
  • 自执行函数语法和回调语法解释

    也许是一个有点愚蠢的问题 但我想了解为什么自执行函数及其回调的语法与所有其他 JS 语法如此不同 function 我只需要理解为什么用它来封装它是有效的 我没想到这是有效的 然后额外的 之后的回调 它就直接位于它之后 我也不期望它是有效的
  • 使用嵌入的 dll 作为资源启动程序时出现问题

    我已经搞定了About com 在 Delphi EXE 中嵌入 dll 的指南 http delphi about com od windowsshellapi l aa012103c htm只要我实际上不使用 DLL 作为外部函数 这似
  • Laravel 5.3 Passport 自定义补助金?

    我知道我不是唯一一个走到这一步的人 有谁知道如何properly在 Laravel 5 3 Passport 中实现自定义授权 Or 有一个很好的链接 教程来参考如何正确执行此操作吗 我知道有这个包 https github com mik