Symfony2 JWT Authentication Returning 404 on Prefl

2019-08-10 12:32发布

问题:

I've just implemented the Symfony2 LexikJWTAuthenticationBundle, and when I attempt to authenticate a user, I keep getting the following response,

XMLHttpRequest cannot load http://api.example.trunk/api/login_check. Response for preflight has invalid HTTP status code 404

What's weird, is that the request does work via Postman, and I get a token, so I'm thinking that this could have something to do with CORS?

I have honestly googled and researched every possible thing I could think of, but I am no closer to figuring out what could be causing this.

security.yml

security:

    encoders:
        User\UserBundle\Entity\User: sha512

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

    providers:

        database_users:
            entity: { class: UserBundle:User }

        in_memory:
            memory:
                users:
                    ryan:
                        password: ryanpass
                        roles: 'ROLE_USER'
                    admin:
                        password: kitten
                        roles: 'ROLE_ADMIN'

    firewalls:
        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            form_login:
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false

        api:
            pattern:   ^/api
            stateless: true
            lexik_jwt: ~

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

    access_control:
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

example.trunk.conf

<VirtualHost *:80>
  ServerName api.example.trunk
  DocumentRoot /Users/user/Sites/example/web
  UseCanonicalName Off
  ErrorLog "/Users/user/Sites/logs/example-error_log"
  CustomLog "/Users/user/Sites/logs/example-access_log" common
  DirectoryIndex app_dev.php

  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
  Header always set Access-Control-Allow-Headers "x-requested-with, content-type, origin, authorization, accept, client-security-token"
  Header always set Access-Control-Max-Age "1000"

  RewriteEngine On
  RewriteCond %{HTTP:Authorization} ^(.*)
  RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

  <Directory "/Users/user/Sites/example/web">
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Request / Response Headers

General headers:
  Request URL:http://api.example.trunk/api/login_check
  Request Method:OPTIONS
  Status Code:404 Not Found
  Remote Address:127.0.0.1:80

Response headers:
  HTTP/1.1 404 Not Found
  Access-Control-Allow-Origin: *
  Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
  Access-Control-Allow-Headers: x-requested-with, content-type, origin,
  authorization, accept, client-security-token
  Access-Control-Max-Age: 1000
  Cache-Control: no-cache
  Keep-Alive: timeout=5, max=100
  Connection: Keep-Alive
  Transfer-Encoding: chunked
  Content-Type: text/html; charset=UTF-8

Request headers:
  OPTIONS /api/login_check HTTP/1.1
  Host: api.example.trunk
  Connection: keep-alive
  Access-Control-Request-Method: POST
  Origin: http://localhost:3000
  Access-Control-Request-Headers: accept, content-type
  Accept: */*
  Referer: http://localhost:3000/

回答1:

For anyone out there having this problem, here is a NOT RECOMMENDED workaround, (I say not recommended because I believe there must be a better solution)

1. Add a onKernelResponse event listener and pass $filterResponseEvent to its arguments

2. Override the default header status code when the request method is OPTIONS:

<?php
/**
 * Created by PhpStorm.
 * User: aien
 * Date: 8/19/16
 * Time: 1:22 AM
 */

namespace Administration\SystemBundle\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class ApiHeaderListener
{
    public function onKernelResponse(FilterResponseEvent $filterResponseEvent)
    {
        $headers = $filterResponseEvent->getResponse()->headers;

        if ($filterResponseEvent->getRequest()->getMethod() == 'OPTIONS')
        {
            $res = $filterResponseEvent->getResponse();
            $res->setStatusCode(200);
            $filterResponseEvent->setResponse($res);
        }

        $headers->set('Access-Control-Allow-Origin', '*');
        $headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
        $headers->set('Access-Control-Allow-Headers', 'X-Requested-With, origin, content-type, accept');
    }
}