MVC 应用程序中生成的 AccessToken 在跨域中无效 API

AccessToken generated in MVC application is not valid in Crossdomain API

您好,我创建了一个启用了个人帐户的 MVC SPA 应用程序,并且能够在注册过程后成功获取访问令牌

我还创建了一个启用了个人帐户的 WEB API 项目。并在本地主机中托管 MVC 和 API 项目。

我尝试使用保存在我的会话存储中的 Bearer 令牌从 MVC 应用程序访问 API。只要两个项目都在 localhost 中,它就可以正常工作。我在 Azure 中托管了 API 项目,如果我尝试使用 Web 应用程序创建的承载令牌从本地主机 MVC 应用程序访问它,API 总是调用 returns 'Unauthorized' .

示例代码:

MVC 应用程序:

$.ajax({
        url: 'https://azureapi/api/getProducts',
        headers: {
            'Authorization': 'Bearer ' + accesstoken,
            'Content-Type': 'application/json; charset=utf-8'
        },
        type: "POST", /* or type:"GET" or type:"PUT" */
        dataType: "json",
        data:  JSON.stringify(model),
        success: function (result) {


        },
        error: function (e) {
            debugger;
            console.log(e.responseText);
        }
    });

API 项目:

[Authorize] 
    [Route("getProducts")]
    [HttpPost]
    public HttpResponseMessage GetProducts(ProductCriteria model)
    {}

在 WEB 中启用 CORS API

 // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        var enableCORS = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(enableCORS);

正如 Chris 在他的评论中提到的,要允许站点 A 将令牌传递给站点 B 并将站点 B 传递给 'verify' 或 'authorise' 它,两个站点必须共享相同的 MachineKey。

我相信这可以在两个站点的 Web.Config 文件中设置,但我没有尝试过(因为害怕破坏我的站点!)。

这里有讨论:How to set machineKey on Azure Website

作为更大任务的一部分,我在这里问了一个类似的问题:ASP.NET Identity 2.0 - Is the expiry timespan stored in the token & different sub-domains