asp.net web.api 2 "defaults" to WindowsIdentity

时间:2017-06-15 10:07:20

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

I'm trying to build a custom middleware to authenticatate user by cookies with a claim based approach. In the process i discovered that the default identity is WindowsIdentiy, and not ClaimsIdentity as i would expect.

The application is hosted on local IIS, with "Anonymous Authentication" enabled, and "Windows Authentication" disabled.

So i really have no idea why this is a windowsidentity.

enter image description here

To make the WindowsIdentity go away, i tried following:

Added authorization to web.config to force Anonymous Authentication:

<authorization>
      <allow users="?"/>
    </authorization>

Added to WebApiConfig.cs Register method to suppress authentication setting on IIS:

config.SuppressHostPrincipal();

But still the WindowsIdentity showed up.

Can anyone point me in direction on how to acheive a claim based solution?


Complete code:

Startup.cs

using System.Web.Http;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(ThgCatalogApi.Startup))]

namespace ThgCatalogApi
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            //app.UseOwinExceptionHandler();            
            GlobalConfiguration.Configure(WebApiConfig.Register);

            ConfigureAuth(app);
        }
    }
}

Startup.Auth.cs

using ThgCatalogApi.Security;
using Owin;

namespace ThgCatalogApi
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {

            app.Use(typeof(ApiCookieAuthMiddleware));
        }
    }
}

ApiCookieAuthMiddleware.cs

using System.Threading.Tasks;
using Microsoft.Owin;

namespace ThgCatalogApi.Security
{
    public class ApiCookieAuthMiddleware : OwinMiddleware
    {
        public ApiCookieAuthMiddleware(OwinMiddleware next) : base(next)
        {

        }

        public override async Task Invoke(IOwinContext context)
        {
            var user = context.Authentication.User;
        }
    }
}

WebApiConfig.cs

using System.Web.Http;

namespace ThgCatalogApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            config.SuppressHostPrincipal();

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

0 个答案:

没有答案