[英]How to enable windows authentication in conjunction with Owin token authentication in web api?
我正在使用Web API應用程序,因此我需要檢查經過身份驗證的用戶,如下所示:
1)使用Windows身份驗證對用戶進行身份驗證
2)如果未在Windows中進行身份驗證。 我將嘗試使用Owin訪問令牌對用戶進行身份驗證。
我的代碼正常工作,但是當我啟用Windows身份驗證時,如下所示:
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;
}
然后在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);
}
如果嘗試使用Bearer令牌調用授權端點, 則會得到401 UnAuthorized 。
所以我的問題是:如何解決這種情況,並使兩種身份驗證方法一起工作?
我已經這樣解決了:
里面SimpleAuthorizationServerProvider類內部GrantResourceOwnerCredentials方法,我將使用下面的代碼來檢查用戶的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;
}
如果上述方法返回null,那么我將返回401 UnAuthorized。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.