Search code examples
c#asp.net-web-apiasp.net-identity

web api can't read claims on request


I'm using WebApi 2.0 with Identity 2.0

I have ApplicationCookie authentication defined in startup.auth.cs like this :

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

        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

I have action in AccountController to login :

        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();

So far so good , cookie was received in client on login request. But when i make new request , claims are empty ? I don't want to use standart login and tables and etc.. i just want to some claims on fake login and read it in next request .. What i'm missing ?


Solution

  • Finnaly found what's going wrong
    .. From Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2

    Find this :

    In particular, the MVC portion of your app might use forms authentication, which stores credentials in a cookie. Cookie-based authentication requires the use of anti-forgery tokens, to prevent CSRF attacks. That’s a problem for web APIs, because there is no convenient way for the web API to send the anti-forgery token to the client. (For more background on this issue, see Preventing CSRF Attacks in Web API.) Calling SuppressDefaultHostAuthentication ensures that Web API is not vulnerable to CSRF attacks from credentials stored in cookies.

    So in WebApiConfig find this // Configure Web API to use only bearer token authentication. //config.SuppressDefaultHostAuthentication();

    which creates a problem for me .. In other word you can't use cookie authentication in WebApi securly ..