2021年8月19日 星期四

職場小技巧

最近公司邀請鼎堅航太的創辦人分享
有幾個點覺得很不錯,紀錄一下
1.發生問題前提示 VS. 發生問題後找原因
2.系統不一定要最好,但比舊有的模式好,比現有流程好
3.不同付錢的人,對於功能需求不同
(管理方希望監控全盤數據,營造方想躲避違規數據)

切換檔案擁有者

在試驗存取遠端資料夾的時候
更改了資料夾的權限,但子資料夾的權限又不同步
試到後來導致連administrator都沒有權限存取
後來找到這個方法可以修改資料夾的權限
takeown /a /r /d Y /f C:\{foldername}


參考: 
https://www.petenetlive.com/KB/Article/0001200
https://ithelp.ithome.com.tw/articles/10238630

ASP.NET切換登入帳號存取資料夾

試了很久,連接網路上芳鄰的資料夾
後來找到這篇,可以成功存取檔案

// 參考: https://docs.microsoft.com/zh-TW/troubleshoot/aspnet/implement-impersonation

public class ImpersonateHelper {
    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_PROVIDER_DEFAULT = 0;

    WindowsImpersonationContext impersonationContext;

    [DllImport("advapi32.dll")]
    public static extern int LogonUserA(String lpszUserName,
    String lpszDomain,
    String lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    ref IntPtr phToken);
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int DuplicateToken(IntPtr hToken,
    int impersonationLevel,
    ref IntPtr hNewToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool RevertToSelf();

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);

    public bool impersonateValidUser(string userName, string password, string domain) {
        WindowsIdentity tempWindowsIdentity;
        IntPtr token = IntPtr.Zero;
        IntPtr tokenDuplicate = IntPtr.Zero;

        if (RevertToSelf()) {
            if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) {
                if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) {
                    tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                    impersonationContext = tempWindowsIdentity.Impersonate();
                    if (impersonationContext != null) {
                        CloseHandle(token);
                        CloseHandle(tokenDuplicate);
                        return true;
                    }
                }
            }
        }
        if (token != IntPtr.Zero)
            CloseHandle(token);
        if (tokenDuplicate != IntPtr.Zero)
            CloseHandle(tokenDuplicate);
        return false;
    }

    public void undoImpersonation() {
        impersonationContext.Undo();
    }
}