1

使用 JWT 令牌从角度访问 Symfony REST API 时,我遇到了 CORS 问题。

IIS 服务器已配置为使用域名和 IP 地址访问应用程序。前端代码在 Symfony 的同一目录中。

前端调用带域名的 API。使用 JWT 令牌从 IP 地址访问应用程序会产生 CORS 问题,因为 API 指向域名。

我已经在内核侦听器中设置了具有以下选项的响应标头。

我正在使用 lexik/jwt-authentication-bundle 生成令牌

$responseHeaders->set('Access-Control-Allow-Headers', 'origin, content-type, accept,authorization');
$responseHeaders->set('Access-Control-Allow-Origin', '*');
$responseHeaders->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
$responseHeaders->set('Access-Control-Allow-Credentials', true);

我还使用以下选项设置了 Nelmio CORS 捆绑包

enter code hernelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~        
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
        '^/':
            allow_origin: ['*']
            allow_headers: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600e

响应标头:

允许
OPTIONS, TRACE, GET, HEAD, POST content-length
0 日期
Mon, 13 Nov 2017 16:03:22 GMT public
OPTIONS, TRACE, GET, HEAD, POST server
Microsoft-IIS/10.0 X-Firefox-Spdy
h2

提前致谢!

4

1 回答 1

3

我的 web.config(Symfony 4):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <rewrite>
        <rules>
            <rule name="Imported Rule 1" stopProcessing="true">
                <match url="^(.*)$" ignoreCase="false" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                </conditions>
                <action type="Rewrite" url="index.php" appendQueryString="true" />
            </rule>
        </rules>
    </rewrite>
    <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Headers" value="origin, content-type, accept,authorization" />
       <add name="Access-Control-Allow-Origin" value="*" />
       <add name="Access-Control-Allow-Methods" value="POST, GET, PUT, DELETE, PATCH, OPTIONS" />
       <add name="Access-Control-Allow-Credentials" value="true" />
     </customHeaders>
   </httpProtocol>
</system.webServer>
</configuration>
于 2019-03-23T19:28:30.940 回答