auth0/symfony

Symfony SDK 用于 Auth0 身份验证和管理 API。

安装次数: 332,824

依赖项: 0

建议者: 0

安全: 0

星星: 124

关注者: 53

分支: 74

公开问题: 0

类型:symfony-bundle

5.3.0 2024-06-24 20:08 UTC

README

auth0/symfony

Symfony SDK 用于 Auth0 身份验证和管理 API。

📚 文档 - 🚀 入门 - 💬 反馈

文档

  • 文档站点 — 探索我们的文档站点并了解更多关于 Auth0 的信息。

入门

要求

  • PHP 8.1+
  • Symfony 6.4 LTS 或 7
    • Symfony 7 支持是社区贡献的,目前处于实验性状态。

请查看我们的 支持策略 了解何时将终止对语言和框架版本的维护。

安装

使用 Composer 将依赖项添加到您的应用程序中

composer require auth0/symfony

配置 Auth0

Auth0 仪表板 中创建一个 常规 Web 应用程序。确认“令牌端点身份验证方法”设置为 POST

接下来,在“设置”页面“应用程序 URI”部分下配置您的应用程序的回调和注销 URL

  • 允许的回调 URL:Auth0 在身份验证期间将重定向到的您的应用程序的 URL,例如,http://localhost:8000/callback
  • 允许的注销 URL:Auth0 注销后将重定向到的您的应用程序的 URL,例如,http://localhost:8000/login

注意 域名客户端 ID客户端密钥。这些值将稍后使用。

配置 SDK

安装后,您应该在您的应用程序中找到一个新文件,config/packages/auth0.yaml。如果此文件不存在,请手动创建它。

以下是一个示例配置,它将使用环境变量分配值。您应避免直接在此文件中存储敏感凭证,因为它通常会被提交到版本控制。

auth0:
  sdk:
    domain: "%env(trim:string:AUTH0_DOMAIN)%"
    client_id: "%env(trim:string:AUTH0_CLIENT_ID)%"
    client_secret: "%env(trim:string:AUTH0_CLIENT_SECRET)%"
    cookie_secret: "%kernel.secret%"

    # custom_domain: "%env(trim:string:AUTH0_CUSTOM_DOMAIN)%"

    # audiences:
    #  - "%env(trim:string:AUTH0_API_AUDIENCE)%"

    # token_cache: cache.auth0_token_cache
    # management_token_cache: cache.auth0_management_token_cache

    scopes:
      - openid
      - profile
      - email
      - offline_access

  authenticator:
    routes:
      callback: "%env(string:AUTH0_ROUTE_CALLBACK)%"
      success: "%env(string:AUTH0_ROUTE_SUCCESS)%"
      failure: "%env(string:AUTH0_ROUTE_FAILURE)%"
      login: "%env(string:AUTH0_ROUTE_LOGIN)%"
      logout: "%env(string:AUTH0_ROUTE_LOGOUT)%"

配置您的 .env 文件

在您的应用程序目录中创建或打开一个 .env.local 文件,并添加以下行

#
# ↓ Refer to your Auth0 application details (https://manage.auth0.com/#/applications) for these values.
#

# Your Auth0 application domain
AUTH0_DOMAIN=...

# Your Auth0 application client ID
AUTH0_CLIENT_ID=...

# Your Auth0 application client secret
AUTH0_CLIENT_SECRET=...

# Optional. Your Auth0 custom domain, if you have one. (https://manage.auth0.com/#/custom_domains)
AUTH0_CUSTOM_DOMAIN=...

# Optional. Your Auth0 API identifier/audience, if used. (https://manage.auth0.com/#/apis)
AUTH0_API_AUDIENCE=...

#
# ↓ These routes will be used by the SDK to direct traffic during authentication.
#

# The route that SDK will redirect to after authentication:
AUTH0_ROUTE_CALLBACK=callback

# The route that will trigger the authentication process:
AUTH0_ROUTE_LOGIN=login

# The route that the SDK will redirect to after a successful authentication:
AUTH0_ROUTE_SUCCESS=private

# The route that the SDK will redirect to after a failed authentication:
AUTH0_ROUTE_FAILURE=public

# The route that the SDK will redirect to after a successful logout:
AUTH0_ROUTE_LOGOUT=public

请确保此 .env.local 文件包含在您的 .gitignore 中。它永远不会被提交到版本控制。

配置您的 security.yaml 文件

打开您的应用程序的 config/packages/security.yaml 文件,并根据以下示例进行更新

security:
  providers:
    auth0_provider:
      id: Auth0\Symfony\Security\UserProvider

  firewalls:
    auth0:
      pattern: ^/private$ # A pattern example for stateful (session-based authentication) route requests
      provider: auth0_provider
      custom_authenticators:
        - auth0.authenticator
    api:
      pattern: ^/api # A pattern example for stateless (token-based authorization) route requests
      stateless: true
      provider: auth0_provider
      custom_authenticators:
        - auth0.authorizer
    dev:
      pattern: ^/(_(profiler|wdt)|css|images|js)/
      security: false
    main:
      lazy: true

  access_control:
    - { path: ^/api$, roles: PUBLIC_ACCESS } # PUBLIC_ACCESS is a special role that allows everyone to access the path.
    - { path: ^/api/scoped$, roles: ROLE_USING_TOKEN } # The ROLE_USING_TOKEN role is added by the Auth0 SDK to any request that includes a valid access token.
    - { path: ^/api/scoped$, roles: ROLE_READ_MESSAGES } # This route will expect the given access token to have the `read:messages` scope in order to access it.

更新您的 config/bundle.php

SDK 包应该由 Symfony Flex 项目自动检测和注册,但您可能需要将 Auth0Bundle 添加到您的应用程序包注册表中。无论哪种方式,注册包都是一个好主意,以确保安全。

<?php

return [
    /*
     * Leave any existing entries in this array as they are.
     * You should just append this line to the end:
     */

    Auth0\Symfony\Auth0Bundle::class => ['all' => true],
];

可选:添加身份验证辅助路由

SDK 包含了一些预构建的 HTTP 控制器,可用于处理身份验证。这些控制器不是必需的,但在入门时可能很有帮助。在许多情况下,这些控制器可能提供您集成 Auth0 到应用程序所需的所有功能,提供即插即用的解决方案。

要使用这些控制器,请打开您的应用程序的 config/routes.yaml 文件,并添加以下行:

login: # Send the user to Auth0 for authentication.
  path: /login
  controller: Auth0\Symfony\Controllers\AuthenticationController::login

callback: # This user will be returned here from Auth0 after authentication; this is a special route that completes the authentication process. After this, the user will be redirected to the route configured as `AUTH0_ROUTE_SUCCESS` in your .env file.
  path: /callback
  controller: Auth0\Symfony\Controllers\AuthenticationController::callback

logout: # This route will clear the user's session and return them to the route configured as `AUTH0_ROUTE_LOGOUT` in your .env file.
  path: /logout
  controller: Auth0\Symfony\Controllers\AuthenticationController::logout

推荐:配置缓存

SDK 在其配置中提供了两个缓存属性:token_cachemanagement_token_cache。它们与任何 PSR-6 缓存实现兼容,其中 Symfony 默认提供了几种。

这些用于存储 JSON Web Key Sets (JWKS) 结果,分别用于验证访问令牌签名和生成的管理 API 令牌。我们建议配置此功能,通过减少 SDK 需要发出的网络请求次数来提高您应用程序的性能。如果您频繁进行管理 API 请求,这还将极大地帮助避免触发速率限制条件。

以下是一个示例 config/packages/cache.yaml 文件,用于配置 SDK 使用 Redis 作为缓存后端:

framework:
  cache:
    prefix_seed: auth0_symfony_sample

    app: cache.adapter.redis
    default_redis_provider: redis://localhost

    pools:
      auth0_token_cache: { adapter: cache.adapter.redis }
      auth0_management_token_cache: { adapter: cache.adapter.redis }

请参阅 Symfony 缓存文档 以获取适配器特定配置选项。请注意,SDK 目前不支持 Symfony 的“Cache Contract”适配器类型。

示例:获取用户信息

以下示例展示了如何在控制器中检索已认证用户。为此示例,我们将创建一个名为 ExampleController 的模拟类,它可通过 /private 路由访问。

将路由添加到您的应用程序的 config/routes.yaml 文件中:

private:
  path: /private
  controller: App\Controller\ExampleController::private

现在更新或创建一个 src/Controller/ExampleController.php 类,包含以下代码:

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class ExampleController extends AbstractController
{
    public function private(): Response
    {
        return new Response(
            '<html><body><pre>' . print_r($this->getUser(), true) . '</pre> <a href="/logout">Logout</a></body></html>'
        );
    }
}

如果您访问浏览器中的 /private 路由,您应该看到已认证用户的信息。如果您尚未认证,您将被重定向到 /login 路由进行登录,然后返回 /private

支持策略

我们的支持窗口由 Symfony 发布支持PHP 发布支持 安排决定,支持将在 Symfony 框架或以下 PHP 运行时停止接收安全修复时结束,哪个先到算哪个。

已过时的语言或框架版本的弃用不被视为破坏性更改,因为 Composer 可以优雅地处理这些场景。遗留应用程序将停止接收我们的更新,但将继续在那些不受支持的 SDK 版本上运行。

注意: 我们目前不支持 Symfony LTS 版本,但预计在 Symfony 6.x 分支进入 LTS 窗口时将添加对此类版本的支持。

注意: Symfony 7 支持是由社区贡献的,目前被视为实验性。

反馈

贡献

我们感谢您对此次仓库的反馈和贡献!在您开始之前,请参阅以下内容:

提出问题

要提供反馈或报告错误,请 在我们的问题跟踪器上提出问题

漏洞报告

请不要在公共 GitHub 问题跟踪器上报告安全漏洞。有关披露安全问题的程序,请参阅 负责任的披露计划

Auth0 是一个易于实现、可定制的身份验证和授权平台。
要了解更多信息,请查看 为什么选择 Auth0?

本项目采用MIT许可协议。有关更多信息,请参阅许可协议文件