【问题标题】:User.Identity.IsAuthenticated in Web API 2 doesn't work with CORSWeb API 2 中的 User.Identity.IsAuthenticated 不适用于 CORS
【发布时间】:2015-02-11 18:17:20
【问题描述】:

我正在使用 ASP.NET MVC5 和 WEB API 2.2 开发一个网站。在我的 web api 控制器中,我有一个 if 条件来检查用户是否已登录:

    if (!User.Identity.IsAuthenticated)
    {
        return BadRequest("NotLoggedIn");
    }

如果我的域名前面没有“www”,这很好用。但是如果将“www”添加到我的域名中,它将返回BadRequest("NotLoggedIn")。例如,我的域是 example.com。如果用户输入 www.example.com,网页将向 example.com/api/controller 发出 AJAX 请求,User.Identity.IsAuthenticated 将返回 false。如果用户只输入 example.com,它将返回 ture。

我已在全局级别启用 CORS:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
        config.EnableCors(cors);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

有人知道如何解决这个问题吗?

【问题讨论】:

  • 你试过直接用 http 代替 www 吗?所以像 http://www_.example.com_ 没有取消标记
  • 我在上面添加了下划线,因为 html 中的格式化程序会删除 url 的 http 和 www 部分,所以删除它们并尝试,因为只是 www 不是有效的 url,它需要 http。
  • 嗨 Omar,我所有的 ajax 请求 url 前面都有 http
  • 在你做任何事情之前,将 http 添加到这个 EnableCorsAttribute("www.example.com", "", ""
  • 嗨 Omar,我确实在 EnableCorsAttribute 中添加了 http。我只是忘记输入了。我已经编辑了我的帖子。

标签: security asp.net-mvc-5 cors asp.net-web-api2 asp.net-identity-2


【解决方案1】:

我已经解决了这个问题。

我需要用以下方式装饰 api 控制器:

[EnableCorsAttribute("http://www.example.com" , "*", "*", SupportsCredentials = true)]

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 2015-02-21
    • 2015-09-08
    • 2015-11-03
    • 2016-06-04
    • 2015-07-16
    • 2019-10-22
    • 2017-11-10
    • 2016-10-15
    相关资源
    最近更新 更多