如果已经在其他应用程序中登录主域,如何使用 symfony 安全登录到子域?

Posted

技术标签:

【中文标题】如果已经在其他应用程序中登录主域,如何使用 symfony 安全登录到子域?【英文标题】:how to login to subdomain using symfony security if already loggedin on main domain in other app? 【发布时间】:2017-01-28 07:14:38 【问题描述】:

我已经登录到主域。说 example.com(在旧版 kohana 中开发的应用程序)。我正在尝试登录 subdmain,比如说 foo.bar.example.com

foo.example.com 是 symfony 应用程序。下面是我的配置。开发工具栏显示“匿名”用户。它不会从 cookie 中的会话 ID 登录用户。

security.yml

# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:

    # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory:
            memory: ~

    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            anonymous: ~
            # activate different ways to authenticate

            # http_basic: ~
            # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: ~
            # http://symfony.com/doc/current/cookbook/security/form_login_setup.html

Config.yml

framework:
    #esi:             ~
    #translator:       fallbacks: ["%locale%"] 
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:       enable_annotations: true 
    #serializer:       enable_annotations: true 
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies:  %trusted_proxies%
    session:
        # handler_id set to null will use default session handler from php.ini
        handler_id:  'snc_redis.session.handler'
        name: 'MY_COOKIE_NAME'
        cookie_domain: '.example.com'
    fragments:       ~
    http_method_override: true
    request:
        formats:
            pdf: 'application/pdf'
            epub: 'application/epub+zip'


snc_redis:
    session:
        client: session
        prefix: ''
    clients:
        default:
            type: predis
            alias: default
            dsn: %redis_dsn%
            logging: false
            options:
#                profile: 2.6
                profile: 2.2
                connection_persistent: false
        slave:
            type: predis
            alias: slave
            logging: false
            dsn: %redis_dsn_slave%

        session:
            type: predis
            alias: session
            dsn: %redis_dsn%

我是否需要配置至少一个身份验证提供程序?要么 我需要编写自定义身份验证提供程序,就像记住我一样工作?

Symfony\Component\Security\Http\Firewall\AbstractAuthenticationListener->句柄

  if ($this->options['require_previous_session'] && !$request->hasPreviousSession()) 
                throw new SessionUnavailableException('Your session has timed out, or you have disabled cookies.');
            

请求有

public function hasPreviousSession()

    // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
    return $this->hasSession() && $this->cookies->has($this->session->getName());

【问题讨论】:

默认情况下,会话 cookie 配置在子域上,为了使相同的 cookie 可访问,请确保检查 SESSIONID cookie 是否具有正确的 TLD 域。所以,“example.com”而不是“sub.example.com”。 我已正确设置域。但仍然没有运气 Symfony 不会自动使用SESSIONID,您应该创建自己的Provider,以便将该会话与(共享)数据库中的会话相匹配。之后您可以手动设置UsernamePasswordToken 必须有默认实现,将 cookie 中的 sessionId 与存储在文件系统中的 session 相匹配。我已经配置了 redis 会话处理程序,并将其映射到 session.handler_id。抱歉无法理解为什么我们需要编写自定义提供程序。 【参考方案1】:

在主域和登录后,您可以将令牌保存到数据库和 cookie 中,在第二个应用程序中,您应该创建一个自定义身份验证器,该身份验证器可以从导航器中恢复令牌并提取到数据库中。如果找到匹配项,它将对用户进行身份验证。

security:

# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-

    firewalls:
    # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            stateless: true
            provider: customProvider
            guard:
                authenticators:
                    - App\Security\TokenAuthenticator

src/Security/TokenAuthenticator.php

namespace App\Security;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;

class TokenAuthenticator extends AbstractGuardAuthenticator

private $em;

public function __construct(EntityManagerInterface $em)

    $this->em = $em;


/**
 * Called on every request to decide if this authenticator should be
 * used for the request. Returning false will cause this authenticator
 * to be skipped.
 */
public function supports(Request $request)

    return true;


/**
 * Called on every request. Return whatever credentials you want to
 * be passed to getUser() as $credentials.
 */
public function getCredentials(Request $request)

    return [
        'token' => // recover token from cookies,
    ];


public function getUser($credentials, UserProviderInterface $userProvider)

    $token = $credentials['token'];

    if (null === $token) 
        return;
    

    // if a User object, checkCredentials() is called
    return $this->em->getRepository(User::class)
        ->findOneBy(['token' => $token]);


public function checkCredentials($credentials, UserInterface $user)

    // check credentials - e.g. make sure the password is valid
    // no credential check is needed in this case

    // return true to cause authentication success
    return true;


public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)

    // on success, let the request continue
    return null;


public function onAuthenticationFailure(Request $request, AuthenticationException $exception)

    $data = [
        'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

        // or to translate this message
        // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    ];

    return new JsonResponse($data, Response::HTTP_FORBIDDEN);


/**
 * Called when authentication is needed, but it's not sent
 */
public function start(Request $request, AuthenticationException $authException = null)

    $data = [
        // you might translate this message
        'message' => 'Authentication Required'
    ];

    return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);


public function supportsRememberMe()

    return false;


希望能解决你的问题

【讨论】:

以上是关于如果已经在其他应用程序中登录主域,如何使用 symfony 安全登录到子域?的主要内容,如果未能解决你的问题,请参考以下文章

求教“server2012主域控与辅域控”切换工作,以及用户登录问题

关于辅助域控问题

Windows Server 2012 R2/2016 此工作站和主域间的信任关系失败

求教“server2012主域控与辅域控”切换工作,以及用户登录问题

辅助域控如何抢占角色(主域控已经down机不可恢复了)

域和子域之间的 Firebase 身份验证共享