WinAuth.cs
资源名称:FtpServer.rar [点击查看]
上传用户:xuelanruo
上传日期:2015-04-02
资源大小:163k
文件大小:2k
源码类别:
Ftp服务器
开发平台:
C#
- using System;
- using System.Runtime.InteropServices;
- using System.Security;
- using System.Security.Principal;
- namespace FtpServerLibrary
- {
- /// <summary>
- /// Classe prenant en charge l'authentification Windows
- /// </summary>
- public class WinAuth
- {
- //Importation des dll permettant l'authentification Windows
- [DllImport("advapi32.dll", SetLastError=true)]
- public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
- int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
- [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
- private extern static bool CloseHandle(IntPtr handle);
- [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
- private extern static bool DuplicateToken(IntPtr ExistingTokenHandle,int SECURITY_IMPERSONATION_LEVEL,ref IntPtr DuplicateTokenHandle);
- /// <summary>
- /// Cette m閠hode permet l'authentification de l'utilisateur, ainsi que le changement des droits
- /// et permissions en fonction de l'utilisateur pour le thread courrant
- /// </summary>
- /// <param name="userName">login</param>
- /// <param name="password">mot de passe</param>
- /// <returns>true si l'authentification a r閡ssi</returns>
- public static bool Auth(string userName,string password)
- {
- try
- {
- IntPtr tokenHandle = new IntPtr(0);
- IntPtr dupeTokenHandle = new IntPtr(0);
- //Param鑤res des fonctions LogonUser et DuplicateToken
- const int LOGON32_PROVIDER_DEFAULT = 0;
- const int LOGON32_LOGON_INTERACTIVE = 2;
- const int SecurityImpersonation = 2;
- tokenHandle = IntPtr.Zero;
- dupeTokenHandle = IntPtr.Zero;
- // On appelle LogonUser pour avoir acc鑣 ?un token d'identit?
- if(!LogonUser(userName,"",password,LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,ref tokenHandle))
- {
- return false;
- }
- if(!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle))
- {
- CloseHandle(tokenHandle);
- return false;
- }
- // A partir du token d'identit? on impersonalise le thread.
- WindowsIdentity newId = new WindowsIdentity(tokenHandle);
- WindowsImpersonationContext impersonatedUser = newId.Impersonate();
- }
- catch
- {
- return false;
- }
- return true;
- }
- }
- }