IT이야기

프로그래밍 방식으로 사용자를 로그인 / 인증하는 방법

cyworld 2021. 3. 30. 21:35
반응형

프로그래밍 방식으로 사용자를 로그인 / 인증하는 방법은 무엇입니까?


로그인 양식을 거치지 않고 등록 과정 직후에 사용자를 로그인하고 싶습니다.

이게 가능해 ? 에서 해결책을 찾았 FOSUserBundle지만 실제로 작업중인 프로젝트에서 사용하지 않습니다.

내 security.yml은 두 개의 방화벽으로 작업하고 있습니다. 일반 텍스트 인코더는 테스트 용입니다.

security:
    encoders:
        Symfony\Component\Security\Core\User\User: plaintext
        Ray\CentralBundle\Entity\Client: md5

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    providers:
        in_memory:
            users:
                admin: { password: admin, roles: [ 'ROLE_ADMIN' ] }
        entity:
            entity: { class: Ray\CentralBundle\Entity\Client, property: email }

    firewalls:
        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

        user_login:
            pattern:    ^/user/login$
            anonymous:  ~

        admin_login:
            pattern:    ^/admin/login$
            anonymous:  ~

        admin:
            pattern:    ^/admin
            provider: in_memory
            form_login:
                check_path: /admin/login/process
                login_path: /admin/login
                default_target_path: /admin/dashboard
            logout:
                path:   /admin/logout
                target: /

        site:
            pattern:    ^/
            provider: entity
            anonymous:  ~
            form_login:
                check_path: /user/login/process
                login_path: /user/login
                default_target_path: /user
            logout:
                path:   /user/logout
                target: /

    access_control:
        - { path: ^/user/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/user, roles: ROLE_USER }
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }

예, 다음과 유사한 방법으로이를 수행 할 수 있습니다.

use Symfony\Component\EventDispatcher\EventDispatcher,
    Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken,
    Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

public function registerAction()
{
    // ...
    if ($this->get("request")->getMethod() == "POST")
    {
        // ... Do any password setting here etc

        $em->persist($user);
        $em->flush();

        // Here, "public" is the name of the firewall in your security.yml
        $token = new UsernamePasswordToken($user, $user->getPassword(), "public", $user->getRoles());

        // For older versions of Symfony, use security.context here
        $this->get("security.token_storage")->setToken($token);

        // Fire the login event
        // Logging the user in above the way we do it doesn't do this automatically
        $event = new InteractiveLoginEvent($request, $token);
        $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);

        // maybe redirect out here
    }
}

마지막에 발생하는 이벤트는 컨텍스트에 토큰을 설정할 때 자동으로 수행되지 않지만 일반적으로 로그인 양식 등을 사용할 때 발생합니다. 따라서 여기에 포함하는 이유입니다. 사용 사례에 따라 사용되는 토큰 유형을 조정해야 할 수 있습니다. UsernamePasswordToken위에 표시된 것은 핵심 토큰이지만 필요한 경우 다른 토큰을 사용할 수 있습니다.

편집 : 위의 코드를 조정하여 '공개'매개 변수를 설명하고 아래 Franco의 의견에 따라 토큰 생성에 사용자 역할을 추가했습니다.


허용 된 버전은 Symfony 3.3에서 작동하지 않습니다. 사용자는 현재 요청이 아닌 다음 요청에서 인증됩니다. 그 이유는 ContextListener가 이전 세션 존재를 확인하고 존재하지 않는 경우 보안 TokenStorage를 지우기 때문입니다. 이 문제를 해결하는 유일한 방법은 현재 요청에서 세션 (및 쿠키)을 수동으로 초기화하여 이전 세션의 존재를 위조하는 것입니다.

더 나은 해결책을 찾으면 알려주세요.

BTW 이것이 허용 된 솔루션과 병합되어야하는지 확실하지 않습니다.

private function logUserIn(User $user)
{
    $token = new UsernamePasswordToken($user, null, "common", $user->getRoles());
    $request = $this->requestStack->getMasterRequest();

    if (!$request->hasPreviousSession()) {
        $request->setSession($this->session);
        $request->getSession()->start();
        $request->cookies->set($request->getSession()->getName(), $request->getSession()->getId());
    }

    $this->tokenStorage->setToken($token);
    $this->session->set('_security_common', serialize($token));

    $event = new InteractiveLoginEvent($this->requestStack->getMasterRequest(), $token);
    $this->eventDispatcher->dispatch("security.interactive_login", $event);
}

위의 코드는 방화벽 이름 (또는 공유 컨텍스트 이름)이라고 가정합니다 common.


다음을 시도해보십시오. Symfony 3 사용자 의 경우 암호가 동일한 지 테스트하기 위해 수정하는 것을 잊지 마십시오 (이 링크에서 암호를 테스트하는 방법이 작동하지 않기 때문에).

$current_password = $user->getPassword();
$user_entry_password = '_got_from_a_form';

$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($user_entry_password, $user->getSalt());

if(hash_equals($current_password, $password)){
//Continue there
}

// I hash the equality process for more security

+ 정보 : hash_equals_function

참조 URL : https://stackoverflow.com/questions/9550079/how-to-programmatically-login-authenticate-a-user

반응형