Windows Doğrulama Ekranı Açma

Bazı durumlarda Windows’un kendi şifre sorma ekranını açmak gerekebiliyor. Bunun için aşağıdaki sınıfı kullanabiliriz:

 


using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
 
namespace Ctrl.Core.Security
{
public class WindowsAuth
{
[DllImport("ole32.dll")]
public static extern void CoTaskMemFree(IntPtr ptr);
 
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct CreduiInfo
{
public int cbSize;
public IntPtr hwndParent;
public string pszMessageText;
public string pszCaptionText;
public IntPtr hbmBanner;
}
[DllImport("credui.dll", CharSet = CharSet.Auto)]
private static extern bool CredUnPackAuthenticationBuffer(int dwFlags,
IntPtr pAuthBuffer,
uint cbAuthBuffer,
StringBuilder pszUserName,
ref int pcchMaxUserName,
StringBuilder pszDomainName,
ref int pcchMaxDomainame,
StringBuilder pszPassword,
ref int pcchMaxPassword);
 
[DllImport("credui.dll", CharSet = CharSet.Auto)]
private static extern int CredUIPromptForWindowsCredentials(ref CreduiInfo notUsedHere,
int authError,
ref uint authPackage,
IntPtr inAuthBuffer,
uint inAuthBufferSize,
out IntPtr refOutAuthBuffer,
out uint refOutAuthBufferSize,
ref bool fSave,
int flags);
 
public static void GetCredentialsVistaAndUp(out NetworkCredential networkCredential)
{
CreduiInfo credui = new CreduiInfo();
credui.pszCaptionText = "Kullanıcı Adı ve Şifre Giriniz";
credui.pszMessageText = "Uygulamayı kullanmak için giriş yapmanız gerekmektedir.";
credui.cbSize = Marshal.SizeOf(credui);
uint authPackage = 0;
IntPtr outCredBuffer = new IntPtr();
uint outCredSize;
bool save = false;
int result = CredUIPromptForWindowsCredentials(ref credui,
0,
ref authPackage,
IntPtr.Zero,
0,
out outCredBuffer,
out outCredSize,
ref save,
1 /* Generic */);
 
var usernameBuf = new StringBuilder(100);
var passwordBuf = new StringBuilder(100);
var domainBuf = new StringBuilder(100);
 
int maxUserName = 100;
int maxDomain = 100;
int maxPassword = 100;
if (result == 0)
{
if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
{
//TODO: ms documentation says we should call this but i can't get it to work
//SecureZeroMem(outCredBuffer, outCredSize);
 
//clear the memory allocated by CredUIPromptForWindowsCredentials
CoTaskMemFree(outCredBuffer);
networkCredential = new NetworkCredential()
{
UserName = usernameBuf.ToString(),
Password = passwordBuf.ToString(),
Domain = domainBuf.ToString()
};
return;
}
}
 
networkCredential = null;
}
}
}

Yorum Yapın

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑

%d blogcu bunu beğendi: