Program Tip

사용자가 컨트롤러 내부에서 Symfony2에 로그인했는지 확인하는 방법은 무엇입니까?

programtip 2020. 10. 22. 22:20
반응형

사용자가 컨트롤러 내부에서 Symfony2에 로그인했는지 확인하는 방법은 무엇입니까?


여기 에서 Symfony2 기반 웹 사이트의 나뭇 가지 템플릿 내에서 사용자의 로그인 상태를 확인하는 방법을 읽었습니다 . 하지만 사용자가 컨트롤러 내부에서 로그인했는지 확인하는 방법을 알아야합니다. 다음 코드가 옳다고 확신했습니다.

$user = $this->get('security.context')->getToken()->getUser();

그러나 항상 무언가를 반환합니다 (예 : 로그인 한 사용자 또는 익명 사용자).

어떤 생각? 미리 감사드립니다.


경고 : 'IS_AUTHENTICATED_FULLY'사용자가 "기억하기"기능을 사용하여 로그인 한 경우 단독으로 선택하면 false가 반환됩니다.

Symfony 2 문서에 따르면 다음과 같은 세 가지 가능성이 있습니다.

IS_AUTHENTICATED_ANONYMOUSLY- 사이트의 방화벽으로 보호 된 부분에 있지만 실제로 로그인하지 않은 사용자에게 자동으로 할당됩니다. 익명 액세스가 허용 된 경우에만 가능합니다.

IS_AUTHENTICATED_REMEMBERED - Remember me 쿠키를 통해 인증 된 사용자에게 자동으로 할당됩니다.

IS_AUTHENTICATED_FULLY- 현재 세션 동안 로그인 세부 정보를 제공 한 사용자에게 자동으로 할당됩니다.

이러한 역할은 세 가지 수준의 인증을 나타냅니다.

IS_AUTHENTICATED_REMEMBERED역할 이있는 경우 역할도 있습니다 IS_AUTHENTICATED_ANONYMOUSLY. 당신이있는 경우 IS_AUTHENTICATED_FULLY역할을, 당신은 또한 다른 두 가지 역할이있다. 즉, 이러한 역할은 인증의 "강도"가 증가하는 세 가지 수준을 나타냅니다.

"기억하기"기능을 사용했던 시스템 사용자가에만 확인한 페이지에 전혀 로그인하지 않은 것처럼 취급되는 문제가 발생했습니다 'IS_AUTHENTICATED_FULLY'.

정답은 완전히 인증되지 않은 경우 다시 로그인하도록 요구하거나 기억 된 역할을 확인하는 것입니다.

$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
    // authenticated REMEMBERED, FULLY will imply REMEMBERED (NON anonymous)
}

바라건대, 이것은 내가 저지른 똑같은 실수를 저 지르지 않도록 누군가를 구할 것입니다. 누군가가 Symfony 2에 로그인했는지 확인하는 방법을 찾을 때 바로이 게시물을 참조로 사용했습니다.

출처 : http://symfony.com/doc/2.3/cookbook/security/remember_me.html#forcing-the-user-to-re-authenticate-before-accessing-certain-resources


SecurityContext는 다음에서 더 이상 사용되지 않습니다. Symfony 3.0

이전에 Symfony 2.6당신은 사용합니다 SecurityContext.
SecurityContext에서 더 이상 사용되지 않습니다 Symfony 3.0의 찬성 AuthorizationChecker.

들어 Symfony 2.6+& Symfony 3.0사용 AuthorizationChecker.


Symfony 2.6 (이하)

// Get our Security Context Object - [deprecated in 3.0]
$security_context = $this->get('security.context');
# e.g: $security_context->isGranted('ROLE_ADMIN');

// Get our Token (representing the currently logged in user)
$security_token = $security_context->getToken();
# e.g: $security_token->getUser();
# e.g: $security_token->isAuthenticated();
# [Careful]             ^ "Anonymous users are technically authenticated"

// Get our user from that security_token
$user = $security_token->getUser();
# e.g: $user->getEmail(); $user->isSuperAdmin(); $user->hasRole();

// Check for Roles on the $security_context
$isRoleAdmin = $security_context->isGranted('ROLE_ADMIN');
# e.g: (bool) true/false

Symfony 3.0 이상 (및 Symfony 2.6 이상)

security.context됩니다 security.authorization_checker.
이제 우리는 security.token_storage대신security.context

// [New 3.0] Get our "authorization_checker" Object
$auth_checker = $this->get('security.authorization_checker');
# e.g: $auth_checker->isGranted('ROLE_ADMIN');

// Get our Token (representing the currently logged in user)
// [New 3.0] Get the `token_storage` object (instead of calling upon `security.context`)
$token = $this->get('security.token_storage')->getToken();
# e.g: $token->getUser();
# e.g: $token->isAuthenticated();
# [Careful]            ^ "Anonymous users are technically authenticated"

// Get our user from that token
$user = $token->getUser();
# e.g (w/ FOSUserBundle): $user->getEmail(); $user->isSuperAdmin(); $user->hasRole();

// [New 3.0] Check for Roles on the $auth_checker
$isRoleAdmin = $auth_checker->isGranted('ROLE_ADMIN');
// e.g: (bool) true/false

자세한 내용은 다음 문서를 참조하십시오. 나뭇 가지에서이 작업을 수행하는 방법? : Symfony 2 : 템플릿 내에서 사용자가 로그인하지 않았는지 어떻게 확인합니까?AuthorizationChecker


이 시도:

if( $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
    // authenticated (NON anonymous)
}

추가 정보 :

"익명 사용자는 기술적으로 인증됩니다. 즉, 익명 사용자 객체의 isAuthenticated () 메서드가 true를 반환합니다. 사용자가 실제로 인증되었는지 확인하려면 IS_AUTHENTICATED_FULLY 역할을 확인하십시오."

출처 : http://symfony.com/doc/current/book/security.html


에서 보안 주석을 SensioFrameworkExtraBundle사용하는 경우 몇 가지 표현식 (에서 정의 됨 \Symfony\Component\Security\Core\Authorization\ExpressionLanguageProvider) 을 사용할 수 있습니다 .

  • @Security("is_authenticated()"): to check that the user is authed and not anonymous
  • @Security("is_anonymous()"): to check if the current user is the anonymous user
  • @Security("is_fully_authenticated()"): equivalent to is_granted('IS_AUTHENTICATED_FULLY')
  • @Security("is_remember_me()"): equivalent to is_granted('IS_AUTHENTICATED_REMEMBERED')

If you using roles you could check for ROLE_USER that is the solution i use:

if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
    // user is logged in
} 

To add to answer given by Anil, In symfony3, you can use $this->getUser() to determine if the user is logged in, a simple condition like if(!$this->getUser()) {} will do.

If you look at the source code which is available in base controller, it does the exact same thing defined by Anil.

참고URL : https://stackoverflow.com/questions/10271570/how-to-check-if-an-user-is-logged-in-symfony2-inside-a-controller

반응형