如何在Drupal 9网站启动时实现未登录用户重定向至Keycloak登录页
实现未登录用户自动重定向到Keycloak登录页的方法
方法1:使用Redirect模块结合权限控制
- 安装并启用Redirect模块(Drupal官方模块)
- 创建一条重定向规则:
- 源路径:
<front>(代表网站首页) - 目标路径:
http://localhost:8080 - 勾选“仅限匿名用户”选项
- 重定向类型选择“302 Found”(临时重定向,已登录用户可正常访问首页)
- 源路径:
- 保存规则后,未登录用户访问首页时会自动跳转至Keycloak登录页,已登录用户不受影响
方法2:自定义代码实现(适合开发者)
如果不想依赖额外模块,可通过自定义模块实现:
针对Drupal 9/10(使用事件订阅器)
- 创建自定义模块(示例模块名:
custom_keycloak_redirect) - 在模块的
src/EventSubscriber目录下创建RedirectSubscriber.php文件,代码如下:
<?php namespace Drupal\custom_keycloak_redirect\EventSubscriber; use Drupal\Core\Session\AccountInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; class RedirectSubscriber implements EventSubscriberInterface { protected $currentUser; public function __construct(AccountInterface $current_user) { $this->currentUser = $current_user; } public function checkRedirect(RequestEvent $event) { // 仅处理主请求且用户未登录的情况 if (!$event->isMainRequest() || !$this->currentUser->isAnonymous()) { return; } $request = $event->getRequest(); // 排除Keycloak回调路径,替换为你实际配置的回调路径 if ($request->getPathInfo() !== '/user/keycloak/callback') { $response = new RedirectResponse('http://localhost:8080'); $event->setResponse($response); } } public static function getSubscribedEvents() { $events[KernelEvents::REQUEST][] = ['checkRedirect', 30]; return $events; } }
- 在模块根目录的
custom_keycloak_redirect.services.yml中注册服务:
services: custom_keycloak_redirect.redirect_subscriber: class: Drupal\custom_keycloak_redirect\EventSubscriber\RedirectSubscriber arguments: ['@current_user'] tags: - { name: event_subscriber }
- 启用自定义模块后,未登录用户访问任何页面(除回调路径外)都会自动跳转到Keycloak登录页
针对Drupal 7
通过hook_init()实现:
function custom_keycloak_redirect_init() { global $user; if ($user->uid == 0) { // 排除Keycloak回调路径 if (current_path() != 'user/keycloak/callback') { drupal_goto('http://localhost:8080'); } } }
方法3:使用Rules模块(适用于Drupal 7/8)
- 安装并启用Rules模块
- 创建新规则:
- 事件选择“用户访问页面”
- 添加条件“用户角色比较”,选择“匿名用户”
- 添加动作“页面重定向”,目标URL设为
http://localhost:8080 - 可选:添加条件“页面路径比较”,排除Keycloak回调路径,避免循环跳转
注意事项
- 务必确保Keycloak的回调路径配置正确,并在重定向规则/代码中排除该路径,防止出现循环跳转问题
- 如果仅需要限制首页跳转,可在规则或代码中添加路径判断,仅当访问首页时触发重定向
内容的提问来源于stack exchange,提问作者Syed Abdul Hannan
相关产品推荐
相关产品推荐

