forked from Code-Sharp/uHttpSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicAuthenticationHandler.cs
More file actions
100 lines (82 loc) · 3.13 KB
/
Copy pathBasicAuthenticationHandler.cs
File metadata and controls
100 lines (82 loc) · 3.13 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using uhttpsharp.Headers;
namespace uhttpsharp.Handlers
{
public class BasicAuthenticationHandler : IHttpRequestHandler
{
private static readonly string BasicPrefix = "Basic ";
private static readonly int BasicPrefixLength = BasicPrefix.Length;
private readonly string _username;
private readonly string _password;
private readonly string _authenticationKey;
private readonly ListHttpHeaders _headers;
public BasicAuthenticationHandler(string realm, string username, string password)
{
_username = username;
_password = password;
_authenticationKey = "Authenticated." + realm;
_headers = new ListHttpHeaders(new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("WWW-Authenticate", string.Format(@"Basic realm=""{0}""", realm))
});
}
public Task Handle(IHttpContext context, Func<Task> next)
{
IDictionary<string, dynamic> session = context.State.Session;
dynamic ipAddress;
if (!session.TryGetValue(_authenticationKey, out ipAddress) || ipAddress != context.RemoteEndPoint)
{
if (TryAuthenticate(context, session))
{
return next();
}
context.Response =
StringHttpResponse.Create("Not Authenticated", HttpResponseCode.Unauthorized,
headers:
_headers);
return Task.Factory.GetCompleted();
}
return next();
}
private bool TryAuthenticate(IHttpContext context, IDictionary<string, dynamic> session)
{
string credentials;
if (context.Request.Headers.TryGetByName("Authorization", out credentials))
{
if (TryAuthenticate(credentials))
{
session[_authenticationKey] = context.RemoteEndPoint;
{
return true;
}
}
}
return false;
}
private bool TryAuthenticate(string credentials)
{
if (!credentials.StartsWith(BasicPrefix))
{
return false;
}
var basicCredentials = credentials.Substring(BasicPrefixLength);
var usernameAndPassword = Encoding.UTF8.GetString(Convert.FromBase64String(basicCredentials));
var nekudataimIndex = usernameAndPassword.IndexOf(':');
if (nekudataimIndex != -1)
{
var username = usernameAndPassword.Substring(0, nekudataimIndex);
var password = usernameAndPassword.Substring(nekudataimIndex + 1);
if (username == _username && password == _password)
{
return true;
}
}
return false;
}
}
}