跳转到主要内容
Hello

主导航

  • 首页
用户帐户菜单
  • 登录

面包屑

  1. 首页

Drupal在用户rest修改资料后防止access_token失效

由 Administrator, 9 九月, 2025

任何已经安装的模块(推荐自定义模块中)

本方法不推荐使用,只适合不想使用refresh_token的情况,为了安全,还是推荐使用refresh_token。

路径:[模块名].module

新增代码:

<?php

use Drupal\Core\Entity\EntityInterface;
use Drupal\user\UserInterface;

/**
 * Implements hook_entity_update().
 */
function [模块名]_entity_update(EntityInterface $entity) {
  // ... (这里是带有判断逻辑的代码) ...
  if ($entity instanceof UserInterface) {
    if (!isset($entity->original)) {
      return;
    }
    $original = $entity->original;

    // $password_changed = $entity->getPassword() !== $original->getPassword();
    $status_changed = $entity->isBlocked() !== $original->isBlocked();
    // $roles_changed = array_diff($entity->getRoles(), $original->getRoles()) || array_diff($original->getRoles(), $entity->getRoles());
    // if ($password_changed || $status_changed || $roles_changed) {
    if ($status_changed) {
      /** @var \Drupal\simple_oauth\ExpiredCollector $collector */
      $collector = \Drupal::service('simple_oauth.expired_collector');

      $tokens_to_delete = $collector->collectForAccount($entity);
      if (!empty($tokens_to_delete)) {
        $collector->deleteMultipleTokens($tokens_to_delete);
      }
    }
  }
}

/**
 * Implements hook_module_implements_alter().
 */
function [模块名]_module_implements_alter(&$implementations, $hook) {
  if ($hook === 'entity_update') {
    // 确保我们的钩子在 simple_oauth 之后执行,或者直接禁用它
    // unset 是更保险的做法
    unset($implementations['simple_oauth']);
  }
}

注意:本代码启用后用户的access_token失效时间以simple_oauth设置为准。

标签

  • drupal
  • 登录或注册以发表评论

评论

RSS源
Powered by Drupal