【问题标题】:web api can't read claims on requestweb api 无法根据请求读取声明
【发布时间】:2016-08-31 14:17:45
【问题描述】:

我正在使用带有 Identity 2.0 的 WebApi 2.0

我在 startup.auth.cs 中定义了 ApplicationCookie 身份验证,如下所示:

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            CookieName = "MyAppCookieName"
        });

        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

我在 AccountController 中有登录操作:

        var claims = new List<Claim>();

        // create required claims
        claims.Add(new Claim(ClaimTypes.NameIdentifier, "harryb"));
        claims.Add(new Claim(ClaimTypes.Name, "harryb"));

        var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

        AuthenticationManager.SignIn(new AuthenticationProperties()
        {
            AllowRefresh = true,
            IsPersistent = true,
            ExpiresUtc = DateTime.UtcNow.AddDays(7),
        }, identity);

        return Ok();

到目前为止一切顺利,客户端在登录请求时收到了 cookie。但是当我提出新的要求时,索赔是空的?我不想使用标准登录和表格等。我只想对假登录提出一些要求,并在下一个请求中阅读它。我错过了什么?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-identity


    【解决方案1】:

    Finnaly 发现了问题所在.. 从这里:http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

    找到这个:

    特别是,您的应用的 MVC 部分可能会使用表单 身份验证,它将凭据存储在 cookie 中。基于 Cookie 身份验证需要使用防伪令牌,以防止 CSRF 攻击。这对 Web API 来说是个问题,因为没有 Web API 将防伪令牌发送到 客户。 (有关此问题的更多背景信息,请参阅防止 CSRF Web API 中的攻击。)调用 SuppressDefaultHostAuthentication 确保 Web API 不易受到来自存储凭据的 CSRF 攻击 在 cookie 中。

    所以在 WebApiConfig 中找到这个 // 将 Web API 配置为仅使用不记名令牌身份验证。 //config.SuppressDefaultHostAuthentication();

    这给我带来了一个问题..换句话说,您不能在 WebApi 安全中使用 cookie 身份验证..

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 2018-12-10
      • 2022-12-24
      • 2019-01-19
      • 1970-01-01
      相关资源
      最近更新 更多