Search code examples
c#asp.net-web-apiowinthinktecture-ident-modelthinktecture

Using Thinktecture.IdentityModel lib using UseBasicAuthentication with Webapi and OWIN the Identity in my controllers has no claims


I am using Thinktecture.IdentityModel and trying to use the Owin.BasicAuthentication lib with the UseBasicAuthentication with Webapi and OWIN. The Identity in my controllers has no claims and shows not authenticated.

I setup the owin config with this in Startup.Auth.cs

        app.SetDefaultSignInAsAuthenticationType("Basic");

        //app.Use(typeof (BasicAuthentication), new[] {_container.Resolve<UserAccountService>()});
        app.UseBasicAuthentication(new BasicAuthenticationOptions("realm", ValidationFunction)
        {
            AuthenticationType = "Basic",
            AuthenticationMode = AuthenticationMode.Active
        });

        var oauthServerConfig = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            Provider = new MembershipRebootProvider(_container.Resolve<UserAccountService>()),
            TokenEndpointPath = new PathString("/token")
        };
        app.UseOAuthAuthorizationServer(oauthServerConfig);

        var oauthConfig = new OAuthBearerAuthenticationOptions
        {
            AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
            AuthenticationType = "Bearer"
        };
        app.UseOAuthBearerAuthentication(oauthConfig);

    private static Task<IEnumerable<Claim>> ValidationFunction(string userName, string password)
    {
        IEnumerable<Claim> claims = null;
        UserAccount user;
        string tenant = "";

        if (userName.Contains("\\"))
        {
            var parts = userName.Split('\\');
            tenant = parts[0];
            userName = parts[1];
        }
        else
        {
            throw new Exception("Cannot determine tenant and username.");
        }

        var userAccountService = _container.Resolve<UserAccountService>();
        if (userAccountService.Authenticate(tenant, userName, password, out user))
        {
            claims = user.GetAllClaims();
        }

        return Task.FromResult(claims);
    }

the claims are returned from membership reboot as expected.

But when I view it in my controller method there are no claims and it says not authenticated..

var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

What am i missing?


Solution

  • I did have the suppress SuppressDefaultHostAuthentication in the config but when checking this I noticed I did not have a filter for "Basic" only Oauth BearerToken. I added that and now it works!

            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            config.Filters.Add(new HostAuthenticationFilter("Basic"));