2017-02-23 157 views
0

我正在嘗試編寫一個Web應用程序,該程序可將用戶重定向到使用IWA(集成Windows身份驗證)的頁面。我不希望用戶與下面的對話框C#集成Windows身份驗證 - 使用代碼進行身份驗證而不顯示登錄提示

enter image description here

而是我想要的應用程序驗證用戶重定向到的頁面提示。

我真的沒有對如何讓這個開始一個好主意,任何幫助將不勝感激

**

  • UPDATE

**

因此,我嘗試訪問的URL沒有連接到Active Directory - 它實際上僅使用Windows身份驗證本地憑據,並且只有1個正在訪問的計算機上的用戶。

我想讓所有重定向到我的頁面的每個人都使用這1個用戶憑證自動進行身份驗證。憑據將根據數據庫中的用戶會話存在進行訪問。

IWA配置爲使用NTLM。

+0

這是ASP.Net Web窗體還是ASP.Net MVC?你在使用Active Directory嗎? – Win

+0

我打算使用web api?顯然,IWA是他們用於身份驗證的唯一東西? –

回答

3

我假設您將使用Active Directory進行身份驗證。如果是這樣,您可以使用PrincipalContextOWIN中間件

我在GitHub上創建了一個名爲AspNetMvcActiveDirectoryOwin的示例項目。你可以分叉它並運行它。 它最初是爲ASP.Net MVC編寫的,但您也可以使用ASP.Net Web API的相同業務邏輯。

您需要遵循幾個步驟。首先,您要使用Active Directory進行身份驗證。

注意:如果您使用其他類型的身份驗證方法,則需要修改此類中的邏輯。

public class ActiveDirectoryService : IActiveDirectoryService 
{ 
    public bool ValidateCredentials(string domain, string userName, string password) 
    { 
     using (var context = new PrincipalContext(ContextType.Domain, domain)) 
     { 
      return context.ValidateCredentials(userName, password); 
     } 
    } 

    public User GetUser(string domain, string userName) 
    { 
     User result = null; 
     using (var context = new PrincipalContext(ContextType.Domain, domain)) 
     { 
      var user = UserPrincipal.FindByIdentity(context, userName); 
      if (user != null) 
      { 
       result = new User 
       { 
        UserName = userName, 
        FirstName = user.GivenName, 
        LastName = user.Surname 
       }; 
      } 
     } 
     return result; 
    } 
} 

其次,您要創建將在Owin中間件使用要求。

public class OwinAuthenticationService : IAuthenticationService 
{ 
    private readonly HttpContextBase _context; 
    private const string AuthenticationType = "ApplicationCookie"; 

    public OwinAuthenticationService(HttpContextBase context) 
    { 
     _context = context; 
    } 

    public void SignIn(User user) 
    { 
     IList<Claim> claims = new List<Claim> 
     { 
      new Claim(ClaimTypes.Name, user.UserName), 
      new Claim(ClaimTypes.GivenName, user.FirstName), 
      new Claim(ClaimTypes.Surname, user.LastName), 
     }; 

     ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType); 

     IOwinContext context = _context.Request.GetOwinContext(); 
     IAuthenticationManager authenticationManager = context.Authentication; 

     authenticationManager.SignIn(identity); 
    } 

    public void SignOut() 
    { 
     IOwinContext context = _context.Request.GetOwinContext(); 
     IAuthenticationManager authenticationManager = context.Authentication; 

     authenticationManager.SignOut(AuthenticationType); 
    } 
}