-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathBankIdAuthHandler.cs
More file actions
253 lines (202 loc) · 9.58 KB
/
BankIdAuthHandler.cs
File metadata and controls
253 lines (202 loc) · 9.58 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
using System.Security.Claims;
using System.Text.Encodings.Web;
using ActiveLogin.Authentication.BankId.Api.Models;
using ActiveLogin.Authentication.BankId.AspNetCore.ClaimsTransformation;
using ActiveLogin.Authentication.BankId.AspNetCore.Cookies;
using ActiveLogin.Authentication.BankId.AspNetCore.DataProtection;
using ActiveLogin.Authentication.BankId.AspNetCore.Helpers;
using ActiveLogin.Authentication.BankId.AspNetCore.Models;
using ActiveLogin.Authentication.BankId.Core.Events;
using ActiveLogin.Authentication.BankId.Core.Events.Infrastructure;
using ActiveLogin.Authentication.BankId.Core.SupportedDevice;
using ActiveLogin.Identity.Swedish;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
namespace ActiveLogin.Authentication.BankId.AspNetCore.Auth;
public class BankIdAuthHandler : RemoteAuthenticationHandler<BankIdAuthOptions>
{
private const string StateCookieNameParameterName = "StateCookie.Name";
private readonly PathString _authPath = new($"/{BankIdConstants.Routes.ActiveLoginAreaName}/{BankIdConstants.Routes.BankIdPathName}/{BankIdConstants.Routes.BankIdAuthControllerPath}");
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IAntiforgery _antiforgery;
private readonly IBankIdUiStateProtector _uiStateProtector;
private readonly IBankIdUiResultProtector _uiResultProtector;
private readonly IBankIdEventTrigger _bankIdEventTrigger;
private readonly IBankIdSupportedDeviceDetector _bankIdSupportedDeviceDetector;
private readonly IBankIdUiOptionsCookieManager _uiOptionsCookieManager;
private readonly List<IBankIdClaimsTransformer> _bankIdClaimsTransformers;
public BankIdAuthHandler(
IHttpContextAccessor httpContextAccessor,
IAntiforgery antiforgery,
IOptionsMonitor<BankIdAuthOptions> options,
ILoggerFactory loggerFactory,
UrlEncoder encoder,
IBankIdUiStateProtector uiStateProtector,
IBankIdUiResultProtector uiResultProtector,
IBankIdEventTrigger bankIdEventTrigger,
IBankIdSupportedDeviceDetector bankIdSupportedDeviceDetector,
IBankIdUiOptionsCookieManager uiOptionsCookieManager,
IEnumerable<IBankIdClaimsTransformer> bankIdClaimsTransformers)
: base(options, loggerFactory, encoder)
{
_httpContextAccessor = httpContextAccessor;
_antiforgery = antiforgery;
_uiStateProtector = uiStateProtector;
_uiResultProtector = uiResultProtector;
_bankIdEventTrigger = bankIdEventTrigger;
_bankIdSupportedDeviceDetector = bankIdSupportedDeviceDetector;
_uiOptionsCookieManager = uiOptionsCookieManager;
_bankIdClaimsTransformers = bankIdClaimsTransformers.ToList();
}
protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
{
var detectedDevice = _bankIdSupportedDeviceDetector.Detect();
var state = GetStateFromCookie();
if (state == null)
{
return await HandleRemoteAuthenticateFail(BankIdConstants.ErrorMessages.InvalidStateCookie, detectedDevice);
}
DeleteStateCookie();
DeleteUiOptionsCookie();
if (!Request.HasFormContentType)
{
await HandleRemoteAuthenticateFail(BankIdConstants.ErrorMessages.InvalidUiResult, detectedDevice);
throw new ArgumentException(BankIdConstants.ErrorMessages.InvalidUiResult);
}
var httpContext = _httpContextAccessor.HttpContext ?? throw new InvalidOperationException(BankIdConstants.ErrorMessages.CouldNotAccessHttpContext);
await _antiforgery.ValidateRequestAsync(httpContext);
var protectedUiResult = Request.Form[BankIdConstants.FormParameters.UiResult];
if (StringValues.IsNullOrEmpty(protectedUiResult))
{
return await HandleRemoteAuthenticateFail(BankIdConstants.ErrorMessages.InvalidUiResult, detectedDevice);
}
var uiResult = _uiResultProtector.Unprotect(protectedUiResult.ToString());
if (!uiResult.IsSuccessful)
{
return await HandleRemoteAuthenticateFail(BankIdConstants.ErrorMessages.InvalidUiResult, detectedDevice);
}
var properties = state.AuthenticationProperties;
var ticket = await GetAuthenticationTicket(uiResult, properties);
await _bankIdEventTrigger.TriggerAsync(new BankIdAspNetAuthenticateSuccessEvent(
PersonalIdentityNumber.Parse(uiResult.PersonalIdentityNumber),
detectedDevice
));
return HandleRequestResult.Success(ticket);
}
private async Task<HandleRequestResult> HandleRemoteAuthenticateFail(string reason, BankIdSupportedDevice detectedDevice)
{
await _bankIdEventTrigger.TriggerAsync(new BankIdAspNetAuthenticateFailureEvent(reason, detectedDevice));
return HandleRequestResult.Fail(reason);
}
private async Task<AuthenticationTicket> GetAuthenticationTicket(BankIdUiResult uiAuthResult, AuthenticationProperties properties)
{
if (Options.TokenExpiresIn.HasValue)
{
if (Options.TimeProvider == null)
{
throw new InvalidOperationException(BankIdConstants.ErrorMessages.TimeProviderNotSet);
}
properties.ExpiresUtc = Options.TimeProvider?.GetUtcNow().Add(Options.TokenExpiresIn.Value);
}
var claims = await GetClaims(uiAuthResult);
var identity = new ClaimsIdentity(claims, Scheme.Name, BankIdClaimTypes.Name, BankIdClaimTypes.Role);
var principal = new ClaimsPrincipal(identity);
return new AuthenticationTicket(principal, properties, Scheme.Name);
}
private async Task<IEnumerable<Claim>> GetClaims(BankIdUiResult uiAuthResult)
{
var context = new BankIdClaimsTransformationContext(
Options,
uiAuthResult.BankIdOrderRef,
uiAuthResult.PersonalIdentityNumber,
uiAuthResult.Name,
uiAuthResult.GivenName,
uiAuthResult.Surname,
uiAuthResult.GetCompletionData()
);
foreach (var transformer in _bankIdClaimsTransformers)
{
await transformer.TransformClaims(context);
}
return context.Claims;
}
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
AppendStateCookie(properties);
var uiOptions = new BankIdUiOptions(
Options.BankIdCertificatePolicies,
Options.BankIdSameDevice,
Options.BankIdRequirePinCode,
Options.BankIdRequireMrtd,
Options.BankIdReturnRisk,
BankIdHandlerHelper.GetCancelReturnUrl(properties.Items),
Options.StateCookie.Name ?? string.Empty,
Options.CardReader
);
AppendUiOptionsCookie(uiOptions);
var detectedDevice = _bankIdSupportedDeviceDetector.Detect();
await _bankIdEventTrigger.TriggerAsync(new BankIdAspNetChallengeSuccessEvent(detectedDevice, uiOptions.ToBankIdFlowOptions()));
var loginUrl = GetInitUiUrl();
Response.Redirect(loginUrl);
}
private string GetInitUiUrl()
{
var pathBase = Context.Request.PathBase;
var authUrl = pathBase.Add(_authPath);
var returnUrl = pathBase.Add(Options.CallbackPath);
var queryBuilder = new QueryBuilder(new Dictionary<string, string>
{
{ BankIdConstants.QueryStringParameters.ReturnUrl, returnUrl }
});
return $"{authUrl}{queryBuilder.ToQueryString()}";
}
private void AppendStateCookie(AuthenticationProperties properties)
{
Validators.ThrowIfNullOrWhitespace(Options.StateCookie.Name, StateCookieNameParameterName);
if (Options.TimeProvider == null)
{
throw new InvalidOperationException(BankIdConstants.ErrorMessages.TimeProviderNotSet);
}
var state = new BankIdUiAuthState(properties);
var cookieOptions = Options.StateCookie.Build(Context, Options.TimeProvider.GetUtcNow());
var cookieValue = _uiStateProtector.Protect(state);
Response.Cookies.Append(Options.StateCookie.Name, cookieValue, cookieOptions);
}
private void AppendUiOptionsCookie(BankIdUiOptions uiOptions)
{
if (Options.TimeProvider == null)
{
throw new InvalidOperationException(BankIdConstants.ErrorMessages.TimeProviderNotSet);
}
_uiOptionsCookieManager.Store(uiOptions, Options.TimeProvider.GetUtcNow());
}
private BankIdUiAuthState? GetStateFromCookie()
{
Validators.ThrowIfNullOrWhitespace(Options.StateCookie.Name, StateCookieNameParameterName);
var protectedState = Request.Cookies[Options.StateCookie.Name];
if (string.IsNullOrEmpty(protectedState))
{
return null;
}
return _uiStateProtector.Unprotect(protectedState) as BankIdUiAuthState;
}
private void DeleteStateCookie()
{
Validators.ThrowIfNullOrWhitespace(Options.StateCookie.Name, StateCookieNameParameterName);
if (Options.TimeProvider == null)
{
throw new InvalidOperationException(BankIdConstants.ErrorMessages.TimeProviderNotSet);
}
var cookieOptions = Options.StateCookie.Build(Context, Options.TimeProvider.GetUtcNow());
Response.Cookies.Delete(Options.StateCookie.Name, cookieOptions);
}
private void DeleteUiOptionsCookie()
{
_uiOptionsCookieManager.Delete();
}
}