tgstation-server
The /tg/station 13 server suite
WindowsSystemIdentity.cs
Go to the documentation of this file.
1 using System;
2 using System.DirectoryServices.AccountManagement;
3 using System.Security.Principal;
4 using System.Threading;
5 using System.Threading.Tasks;
6 
7 namespace Tgstation.Server.Host.Security
8 {
13  {
15  public string Uid => (userPrincipal?.Sid ?? identity.User).ToString();
16 
18  public string Username => userPrincipal?.Name ?? identity.Name;
19 
23  readonly WindowsIdentity identity;
24 
28  readonly UserPrincipal userPrincipal;
29 
34  public WindowsSystemIdentity(WindowsIdentity identity)
35  {
36  this.identity = identity ?? throw new ArgumentNullException(nameof(identity));
37  }
38 
43  public WindowsSystemIdentity(UserPrincipal userPrincipal)
44  {
45  this.userPrincipal = userPrincipal ?? throw new ArgumentNullException(nameof(userPrincipal));
46  }
47 
49  public void Dispose()
50  {
51  if (identity != null)
52  identity.Dispose();
53  else
54  {
55  var context = userPrincipal.Context;
56  userPrincipal.Dispose();
57  context.Dispose();
58  }
59  }
60 
63  {
64  if (identity != null)
65  {
66  //var newIdentity = (WindowsIdentity)identity.Clone(); //doesn't work because of https://github.com/dotnet/corefx/issues/31841
67 
68  var newIdentity = new WindowsIdentity(identity.Token); //the handle is cloned internally
69 
70  return new WindowsSystemIdentity(newIdentity);
71  }
72  //can't clone a UP, shouldn't be trying to anyway, cloning is for impersonation
73  throw new InvalidOperationException("Cannot clone a UserPrincipal based WindowsSystemIdentity!");
74  }
75 
77  public Task RunImpersonated(Action action, CancellationToken cancellationToken) => Task.Factory.StartNew(() =>
78  {
79  if (action == null)
80  throw new ArgumentNullException(nameof(action));
81  if (identity == null)
82  throw new InvalidOperationException("Impersonate using a UserPrincipal based WindowsSystemIdentity!");
83  WindowsIdentity.RunImpersonated(identity.AccessToken, action);
84  }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
85  }
86 }
Represents a user on the current System.Runtime.InteropServices.OSPlatform
WindowsSystemIdentity(WindowsIdentity identity)
Construct a WindowsSystemIdentity using a WindowsIdentity
WindowsSystemIdentity(UserPrincipal userPrincipal)
Construct a WindowsSystemIdentity using a UserPrincipal
ISystemIdentity Clone()
Clone the ISystemIdentity creating another copy that must have IDisposable.Dispose called on it ...
readonly WindowsIdentity identity
The WindowsIdentity for the WindowsSystemIdentity
readonly UserPrincipal userPrincipal
The UserPrincipal for the WindowsSystemIdentity