成功登录后,Symfony2重定向到/ login_check(产生404错误)

时间:2017-01-12 14:41:42

标签: php symfony authentication redirect login

我遇到的最奇怪的问题。上个月我将防火墙从^ / portal /更改为^ /。从那时起,我一直遇到问题,系统将在成功验证后重定向回/ login /或/ login_check /。对于我的生活,我无法弄清楚为什么系统在登录后不会正确重定向。

404的屏幕截图。提交登录表单时会发生这种情况

(请参阅探查器栏作为底部。在发生错误之前,用户已成功进行身份验证) 404 error after submitting login form and being logged in

security.yml:

security:
    role_hierarchy:
        ROLE_ADMIN:             ROLE_QC
        ROLE_QC:                ROLE_ACCOUNTADMIN
        ROLE_ACCOUNTADMIN:      ROLE_ACCOUNTTRACER
        ROLE_ACCOUNTTRACER:     ROLE_SALESREP
        ROLE_SALESREP:          ROLE_ACCOUNTCAPTURER
        ROLE_ACCOUNTCAPTURER:   ROLE_CLIENTUSER
        ROLE_CLIENTUSER:        ROLE_USER

    providers:
        main:
            entity:
                class: TraceGenie\PortalBundle\Entity\User
                property: email

    firewalls:
        secured_area:
            pattern:    ^/
            anonymous:  ~
            form_login:
                login_path: portal_login
                check_path:  login_check
                default_target_path: portalDashboard
                require_previous_session: false
                success_handler: authentication_handler
                failure_handler: authentication_handler
            logout:
                path:   portal_logout
                target: home
            http_basic:
                realm: "TraceGenie Portal"  
    encoders:
        TraceGenie\PortalBundle\Entity\User: sha512

    access_control:
        - { path: ^/login/$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/_wdt/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/contact/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetPassword/$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/account/save/$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, roles: ROLE_ADMIN }
        - { path: ^/qc/, roles: ROLE_QC }
        - { path: ^/accountadmin/, roles: ROLE_ACCOUNTADMIN }
        - { path: ^/, roles: ROLE_USER }

routing.yml EXTRACT

home:
    pattern:   /
    defaults:  { _controller: TraceGeniePortalBundle:User:login }

portal_login:
    pattern:   /login/ # Authenticated Anonymously
    defaults:  { _controller: TraceGeniePortalBundle:User:login }

portal_logout:
    pattern:   /logout/

login_check:
    pattern:   /login_check/

身份验证处理程序:

namespace TraceGenie\PortalBundle\Handler;

use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
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\Routing\Router;
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;

class AuthenticationHandler
implements AuthenticationSuccessHandlerInterface,
           AuthenticationFailureHandlerInterface
{
    private $router;
    private $doctrine;

    public function __construct(Router $router, Doctrine $doctrine)
    {
        $this->router = $router;
        $this->doctrine = $doctrine;
    }

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

        $user = $token->getUser();
        $user->setLastLogin(new \DateTime());

        $this->doctrine->getManager()->flush();

        if ($request->isXmlHttpRequest()) 
        {
            $result = array('success' => true);
            return new Response(json_encode($result));
        } 
        else 
        {
            if ($targetPath = $request->getSession()->get('_security.secured_area.target_path')) 
            {
                # THE BELOW WAS ADDED TO TRY AND RESOLVE INCORRECT REDIRECTION
                if ($targetPath != $this->router->generate('login') && $targetPath != $this->router->generate('home') && $targetPath != $this->router->generate('login_check')) $url = $targetPath;
                else $url = $this->router->generate('portalDashboard');
            }
            else $url = $this->router->generate('portalDashboard');

            return new RedirectResponse($url);   
        }
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if ($request->isXmlHttpRequest()) 
        {
            $result = array('success' => false);
            return new Response(json_encode($result));
        } 
        else 
        {
            $request->getSession()->getFlashBag()->add('error', $exception->getMessage());
            $url = $this->router->generate('portal_login');

            return new RedirectResponse($url);
        }
    }
}

login.html.twig

{% extends '::web_layout.html.twig' %}

{% block content %}
<div class="row">
    <div class="col-md-5 main-content" style="float: none; margin: 0 auto;">
        <div class="panel panel-default">
            <div class="panel-heading">USER LOGIN <a href="{{ url("register") }}" style="float: right; padding-top: 0; padding-right: 0px;" class="btn btn-xs">REGISTER COMPANY</a></div>
            <form id="loginForm" action="{{ url('login_check') }}" method="POST">
                <div class="panel-body">
                    <div class="alert alert-success" style="font-size: 80%; font-style: italic;">
                        <p>Need Help? Try our new "HELP" feature after logging in at the top right corner of your screen. Each page has different help, with more help to be added in time.</p>
                        <p>If you feel that a specific feature needs its own help tutorial, please let us know via the helpdesk.</p>
                    </div>
                    <div class="form-group">
                            <input class="form-control" type="text" id="username" name="_username" placeholder="EMAIL ADDRESS" value="{{ last_username }}" data-validation-error-msg="Please enter a valid email address" data-validation="email">
                    </div>
                    <div class="form-group">
                        <input class="form-control" type="password" id="password" name="_password" placeholder="PASSWORD" data-validation-error-msg="Please enter a password" data-validation="length" data-validation-length="min1">
                    </div>
                </div>

                <div class="panel-footer">
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="btn btn-danger btn-sm" style="float:left;" onclick="$('#email').val($('#username').val()); $('#forgotPassword').modal({ backdrop: 'static', keyboard: false });">FORGOT PASSWORD</div>
                            <button class="btn btn-default btn-sm" id="log-in-user" style="float: right;">SIGN IN</button>
                        </div>
                    </div>
                    <br>
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="alert alert-danger text-center"><em>Please note that passwords are "CaSe SenSiTiVe"</em></div>
                        </div>
                    </div>
                </div>
            </form> 
        </div>
    </div>
</div>

<!-- FORGOT PASSWORD MODAL -->
<div class="modal fade" id="forgotPassword" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4>FORGOT PASSWORD</h4>
            </div>
            <form id="forgotPasswordForm" role="form" method="POST" class="form">   
                <input type="hidden" id="user_id" name="user_id">   
                <div class="modal-body">
                    <fieldset>
                        <div class="form-group">
                            <label for="email" class="control-label">Please enter your email address:</label>
                            <input type="text" id="email" name="email" class="form-control" placeholder="Email Address" data-validation-error-msg="Please enter a valid email address" data-validation="length" data-validation-length="min5" onblur="this.value = $.trim(this.value);">
                        </div>
                    </fieldset>
                    <div class="row text-center">
                        <button class="btn btn-default">RESET PASSWORD</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- END: FORGOT PASSWORD MODAL -->

<script>

$(document).ready(function()
{
    $.validate(
    {           
        onSuccess : function($form)
        {
            if ($form.attr('id') == 'loginForm' || $form.attr('id') == 'headerLoginForm')
            {
                return true;
            }
            if ($form.attr('id') == 'forgotPasswordForm')
            {           
                $.post('{{ url("resetPassword") }}', $('#forgotPasswordForm').serialize())
                .done(function(data)
                {
                    if (typeof(data.error) != 'undefined')
                    {
                        $('#errorMsg').html(data.error);
                        $('#pageError').modal('show');
                    }
                    else
                    {
                        $('#successMsg').html('Your password has been succesfully reset and sent to your email address');
                        $('#pageSuccess').modal('show');
                        $('#forgotPassword').modal('hide');
                    }
                }); 
            }
            return false;
        },
        onError: function()
        {
            $('#errorMsg').html('Please ensure that all required fields have been filled in.');
            $('#pageError').modal('show');
        }
    });

    {% if error %}
        $('#errorMsg').html('{{error.message}}');
        $('#pageError').modal('show');
    {% endif %}
});
</script>
{% endblock %}

UserController的::则loginAction()

public function loginAction() #Route /login/
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY'))
        {
            return $this->redirect($this->generateUrl('portalDashboard'));
        }

        # If AJAX request, do not load Login page.
        if ($request->isXmlHttpRequest()) return $this->createJsonResponse(array('error' => 'Not Logged in'));

        # Get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) 
        {
            $error = $request->attributes->get(
                SecurityContext::AUTHENTICATION_ERROR
            );
        } 
        else 
        {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        $flashError = $session->getFlashBag()->get('error');
        if (!empty($flashError)) 
            foreach($flashError as $message)
                $error = array('message' => $message);

        return $this->render(
            'TraceGeniePortalBundle:User:login.html.twig',
            array(
                'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                'error'         => $error,
            )
        );
    }

0 个答案:

没有答案