-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBasicAuthMiddleware.cs
More file actions
76 lines (62 loc) · 2.2 KB
/
BasicAuthMiddleware.cs
File metadata and controls
76 lines (62 loc) · 2.2 KB
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
73
74
75
76
using Microsoft.Owin;
using System;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace AMC.Owin
{
public class BasicAuthMiddleware : OwinMiddleware
{
public const string AuthMode = "Basic";
public BasicAuthMiddleware(OwinMiddleware next)
: base(next)
{
}
public BasicAuthMiddleware(OwinMiddleware next, Func<string, string, Task<IIdentity>> validationCallback)
: this(next)
{
IndentityVerificationCallback = validationCallback;
}
Func<string, string, Task<IIdentity>> IndentityVerificationCallback
{
get;
set;
}
public override async Task Invoke(IOwinContext context)
{
var request = context.Request;
var response = context.Response;
response.OnSendingHeaders(o =>
{
var rResp = (IOwinResponse)o;
if (rResp.StatusCode == 401)
{
rResp.Headers["WWW-Authenticate"] = AuthMode;
}
}, response);
var header = request.Headers["Authorization"];
if (!string.IsNullOrWhiteSpace(header))
{
var authHeader = AuthenticationHeaderValue.Parse(header);
if (AuthMode.Equals(authHeader.Scheme, StringComparison.OrdinalIgnoreCase))
{
var parameter = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter));
var parts = parameter.Split(':');
var userName = parts[0];
var password = parts[1];
if (IndentityVerificationCallback != null)
{
var identity = await IndentityVerificationCallback.Invoke(userName, password);
if (identity != null)
{
request.User = new ClaimsPrincipal(identity);
}
}
}
}
await Next.Invoke(context);
}
}
}