-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpipeline.cs
71 lines (63 loc) · 3.48 KB
/
pipeline.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System.Threading.Tasks;
using System.Security.Principal;
using Microsoft.AspNetCore.Http;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
namespace AspNetCore.Impersonation
{
public partial class Impersonate
{
//This is the primary function which is run by the middleware pipeline for every request
public async Task Invoke(HttpContext context)
{
bool methodStatus = false;
//Checks if the value is a valid boolean and if its true, otherwise just passes the call on and does not wrap it in impersonation
if (
//Checks the file exists with the information before we continue to check if its valid
shouldRunImpersonation &&
//Checks the value is a valid boolean and that its true
bool.TryParse(Configuration.GetSection("impersonation:is_enabled").Value, out bool isEnabled) && isEnabled &&
//Checks the credentials are not empty
Configuration.GetSection("impersonation:credentials:domain") != null && !string.IsNullOrWhiteSpace(Configuration.GetSection("impersonation:credentials:domain").Value) &&
Configuration.GetSection("impersonation:credentials:username") != null && !string.IsNullOrWhiteSpace(Configuration.GetSection("impersonation:credentials:username").Value) &&
Configuration.GetSection("impersonation:credentials:password") != null && !string.IsNullOrWhiteSpace(Configuration.GetSection("impersonation:credentials:password").Value)
)
{
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
// Call LogonUser to obtain a handle to an access token.
methodStatus = LogonUser(Configuration.GetSection("impersonation:credentials:username").Value,
Configuration.GetSection("impersonation:credentials:domain").Value,
Configuration.GetSection("impersonation:credentials:password").Value,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
out SafeAccessTokenHandle safeAccessTokenHandle);
//Checks if it was a successful logon
if (methodStatus)
{
await WindowsIdentity.RunImpersonated(safeAccessTokenHandle, async () =>
{
await next.Invoke(context);
});
}
else
{
//This can be used to help debug what the problem is by flagging that you want it to throw the output
//Note: should not be active for production!
if (throwException)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
}
}
//Checks if the status is false and if so then just forwards the call on without any identity impersonation
if (!methodStatus)
{
//Just forwards the call without changing the user identity
await next.Invoke(context);
}
}
}
}