forked from blowdart/idunno.Authentication
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicAuthenticationHandler.cs
More file actions
170 lines (145 loc) · 6.98 KB
/
Copy pathBasicAuthenticationHandler.cs
File metadata and controls
170 lines (145 loc) · 6.98 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Copyright (c) Barry Dorrans. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
namespace idunno.Authentication.Basic
{
internal class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
private const string _Scheme = "Basic";
private readonly UTF8Encoding _utf8ValidatingEncoding = new UTF8Encoding(false, true);
public BasicAuthenticationHandler(
IOptionsMonitor<BasicAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock) : base(options, logger, encoder, clock)
{
}
/// <summary>
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
protected new BasicAuthenticationEvents Events
{
get { return (BasicAuthenticationEvents)base.Events; }
set { base.Events = value; }
}
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new BasicAuthenticationEvents());
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string authorizationHeader = Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authorizationHeader))
{
return AuthenticateResult.NoResult();
}
// Exact match on purpose, rather than using string compare
// asp.net request parsing will always trim the header and remove trailing spaces
if (_Scheme == authorizationHeader)
{
const string noCredentialsMessage = "Authorization scheme was Basic but the header had no credentials.";
Logger.LogInformation(noCredentialsMessage);
return AuthenticateResult.Fail(noCredentialsMessage);
}
if (!authorizationHeader.StartsWith(_Scheme + ' ', StringComparison.OrdinalIgnoreCase))
{
return AuthenticateResult.NoResult();
}
string encodedCredentials = authorizationHeader.Substring(_Scheme.Length).Trim();
try
{
string decodedCredentials = string.Empty;
byte[] base64DecodedCredentials;
try
{
base64DecodedCredentials = Convert.FromBase64String(encodedCredentials);
}
catch (FormatException)
{
const string failedToDecodeCredentials = "Cannot convert credentials from Base64.";
Logger.LogInformation(failedToDecodeCredentials);
return AuthenticateResult.Fail(failedToDecodeCredentials);
}
try
{
decodedCredentials = _utf8ValidatingEncoding.GetString(base64DecodedCredentials);
}
catch (Exception ex)
{
const string failedToDecodeCredentials = "Cannot build credentials from decoded base64 value, exception {ex.Message} encountered.";
Logger.LogInformation(failedToDecodeCredentials, ex.Message);
return AuthenticateResult.Fail(ex.Message);
}
var delimiterIndex = decodedCredentials.IndexOf(":", StringComparison.OrdinalIgnoreCase);
if (delimiterIndex == -1)
{
const string missingDelimiterMessage = "Invalid credentials, missing delimiter.";
Logger.LogInformation(missingDelimiterMessage);
return AuthenticateResult.Fail(missingDelimiterMessage);
}
var username = decodedCredentials.Substring(0, delimiterIndex);
var password = decodedCredentials.Substring(delimiterIndex + 1);
var validateCredentialsContext = new ValidateCredentialsContext(Context, Scheme, Options)
{
Username = username,
Password = password
};
await Events.ValidateCredentials(validateCredentialsContext);
if (validateCredentialsContext.Result != null &&
validateCredentialsContext.Result.Succeeded)
{
var ticket = new AuthenticationTicket(validateCredentialsContext.Principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
if (validateCredentialsContext.Result != null &&
validateCredentialsContext.Result.Failure != null)
{
return AuthenticateResult.Fail(validateCredentialsContext.Result.Failure);
}
return AuthenticateResult.NoResult();
}
catch (Exception ex)
{
var authenticationFailedContext = new BasicAuthenticationFailedContext(Context, Scheme, Options)
{
Exception = ex
};
await Events.AuthenticationFailed(authenticationFailedContext).ConfigureAwait(true);
if (authenticationFailedContext.Result != null)
{
return authenticationFailedContext.Result;
}
throw;
}
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (!Request.IsHttps && !Options.AllowInsecureProtocol)
{
const string insecureProtocolMessage = "Request is HTTP, Basic Authentication will not respond.";
Logger.LogInformation(insecureProtocolMessage);
// 421 Misdirected Request
// The request was directed at a server that is not able to produce a response.
// This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
Response.StatusCode = StatusCodes.Status421MisdirectedRequest;
}
else
{
Response.StatusCode = 401;
if (!Options.SuppressWWWAuthenticateHeader)
{
var headerValue = _Scheme + $" realm=\"{Options.Realm}\"";
Response.Headers.Append(HeaderNames.WWWAuthenticate, headerValue);
}
}
return Task.CompletedTask;
}
}
}