Search code examples
c#asp.net-web-apiowinwindows-authenticationaccess-token

How to enable windows authentication in conjunction with Owin token authentication in web api?


I am working on a web api application and I have requirement to check for authenticated users as following:

1) Authenticate user using Windows Authentication

2) If not authenticated in Windows. I will try to authenticate users using Owin access-token.

My code is working but when I enable Windows authentication as following:

 public static IAppBuilder EnableWindowsAuthentication(this IAppBuilder app)
    {
        if (!app.Properties.TryGetValue("System.Net.HttpListener", out var val))
            return app;

        if (val is HttpListener listener)
        {
            listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
        }
        return app;
    }

Then inside Startup.cs:

public void Configuration(IAppBuilder app)
    {
        OnAppDisposing(app);
        ConfigureOAuth(app);

        var config = new HttpConfiguration();
        var webApiConfiguration = WebApiConfig.Register(config);

        app.UseCors(CorsOptions.AllowAll);
        app.EnableWindowsAuthentication();
        //here some owin middlewares

        app.UseWebApi(webApiConfiguration);

    }
 private void ConfigureOAuth(IAppBuilder app)
    {
        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/api/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
            Provider = new SimpleAuthorizationServerProvider()
        };

        // Token Generation

        app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
      }

If I try to call an authorized endpoint using Bearer token I get 401 UnAuthorized .

So my question is: how to work around this scenario and get both authentication methods working together?


Solution

  • I have solved it this way:

    Inside SimpleAuthorizationServerProvider class inside GrantResourceOwnerCredentials method I will use the following code to check for user inside Active Directory:

    public string FindUser(string activeDirectoryPath ,string userName, string password)
        {
            try
            {
    
                    using (var searcher = new DirectorySearcher(new DirectoryEntry(activeDirectoryPath, userName, password)))
                    {
                        searcher.Filter = string.Format("(&(objectClass=user)(name={0}))", userName);
                        searcher.PropertiesToLoad.Add("name");// username
                        var activeDirectoryStaff = searcher.FindOne();
                        if (activeDirectoryStaff != null)
                        {
                            return (string)activeDirectoryStaff.Properties["name"][0];
                        }
                        else
                            return null;
                    }
                }
    
            }
            catch (Exception ex)
            {
                this.Log().Error(ex, ex.Message);
                return null;
            }
            return null;
        }
    

    if the above method returns null, then I will return 401 UnAuthorized .