forked from dotnet/Kerberos.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KerberosEndToEndMiddleware.cs
72 lines (55 loc) · 2.06 KB
/
KerberosEndToEndMiddleware.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
72
using Kerberos.NET;
using Kerberos.NET.Crypto;
using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using NextFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;
namespace KerberosWebSample
{
internal class KerberosEndToEndMiddleware
{
private readonly KerberosValidator validator;
private readonly NextFunc next;
public KerberosEndToEndMiddleware(NextFunc next)
{
this.next = next;
// NOTE: ValidateAfterDecrypt is a dangerous flag. It should only be used for samples
validator = new KerberosValidator(new KerberosKey("P@ssw0rd!")) { ValidateAfterDecrypt = ValidationActions.None };
}
public async Task Invoke(IDictionary<string, object> environment)
{
var context = new OwinContext(environment);
//validator.Logger = context.TraceOutput.Write;
if (await ParseKerberosHeader(context))
{
await next.Invoke(environment);
}
}
private async Task<bool> ParseKerberosHeader(OwinContext context)
{
string[] authzHeader = null;
if (!context.Request.Headers.TryGetValue("Authorization", out authzHeader) || authzHeader.Length != 1)
{
context.Response.Headers.Add("WWW-Authenticate", new[] { "Negotiate" });
context.Response.StatusCode = 401;
return false;
}
var header = authzHeader.First();
try
{
var authenticator = new KerberosAuthenticator(validator);
var identity = await authenticator.Authenticate(header);
context.Request.User = new ClaimsPrincipal(identity);
return true;
}
catch (Exception ex)
{
context.TraceOutput.WriteLine(ex);
return false;
}
}
}
}