2012-06-28 114 views
13

我正在尝试开发一个简单的Web服务,以使用Windows标识框架对桌面应用程序的用户进行身份验证,目前我通过post变量传递由WindowsIdentity.GetCurrent().Token生成的令牌(它已加密并且ssl'd ,鉴于我们域的布局和服务器的配置,Windows身份验证不是一个选项)。我正在将该令牌恢复正常并将其转回IntPtr验证Windows标识令牌

我对如何验证令牌以确保它是由特定的Active Directory(或任何相关事件)生成的丢失。我试图创建一个新的WindowsIdentity实例,但只会产生一个异常(消息:用于模拟的无效令牌 - 它不能被复制)。

如果任何人都可以提供任何帮助,甚至提示,我将不胜感激,在此先感谢。

+0

当使用令牌访问资源时,是否可以使用令牌并将验证留在Windows上? –

+2

在我的情况下,我使用自定义套接字客户端/服务器解决方案,我想使用Windows身份验证来验证用户。因此,我需要传输一个令牌或类似的服务器进行身份验证,但我不明白如何。 MSDN不是很有帮助。 – jgauffin

+0

客户端和服务器在同一个域上吗?登录到Windows时,客户端是否对域进行身份验证? –

回答

-1

好,

如果我理解正确的话你的问题,我知道这是可能做到这一点做的直接API调用。 Advapi32.dll中的LogonUser就是答案。下面的代码段为我工作

public class ActiveDirectoryHelper 
{ 
    [DllImport("advapi32.dll", SetLastError = true)] 
    private static extern bool LogonUser(
     string lpszUsername, 
     string lpszDomain, 
     string lpszPassword, 
     int dwLogonType, 
     int dwLogonProvider, 
     out IntPtr phToken 
     ); 

    [DllImport("kernel32.dll", SetLastError = true)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    public static extern bool CloseHandle(IntPtr hObject); 

    public static bool Authenticate(string userName, string password, string domain) 
    { 
     IntPtr token; 
     LogonUser(userName, domain, password, 2, 0, out token); 

     bool isAuthenticated = token != IntPtr.Zero; 

     CloseHandle(token); 

     return isAuthenticated; 
    } 

    public static IntPtr GetAuthenticationHandle(string userName, string password, string domain) 
    { 
     IntPtr token; 
     LogonUser(userName, domain, password, 2, 0, out token); 
     return token; 
    } 


} 
1
public bool DoesUserExist(string userName) 
{ 
    using (var domainContext = new PrincipalContext(ContextType.Domain, "DOMAIN")) 
    { 
     using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName)) 
     { 
      return foundUser != null; 
     } 
    } 
} 

为了实现检查用户是否存在。这来自System.DirectoryServices.AccountManagement命名空间和程序集。

只需传入您的用户名,您可以从WindowsIdentity.GetCurrent()获得该用户名,如果用户在用户组中,则该用户将返回true/false。 (用你需要的组名替换DOMAIN)