forked from aspnet-contrib/AspNet.Security.OAuth.Providers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSuperOfficeAuthenticationHandler.cs
173 lines (149 loc) · 7.37 KB
/
SuperOfficeAuthenticationHandler.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
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
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace AspNet.Security.OAuth.SuperOffice
{
/// <summary>
/// Defines a handler for authentication using SuperOffice.
/// </summary>
public class SuperOfficeAuthenticationHandler : OAuthHandler<SuperOfficeAuthenticationOptions>
{
public SuperOfficeAuthenticationHandler(
[NotNull] IOptionsMonitor<SuperOfficeAuthenticationOptions> options,
[NotNull] ILoggerFactory logger,
[NotNull] UrlEncoder encoder,
[NotNull] ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
/// <inheritdoc />
protected override async Task<AuthenticationTicket> CreateTicketAsync(
[NotNull] ClaimsIdentity identity,
[NotNull] AuthenticationProperties properties,
[NotNull] OAuthTokenResponse tokens)
{
var contextId = await ProcessIdTokenAndGetContactIdentifierAsync(tokens, properties, identity);
if (string.IsNullOrEmpty(contextId))
{
throw new InvalidOperationException("An error occurred trying to obtain the context identifier from the current user's identity claims.");
}
// Add contextId to the Options.UserInformationEndpoint (https://sod.superoffice.com/{0}/api/v1/user/currentPrincipal).
var userInfoEndpoint = string.Format(CultureInfo.InvariantCulture, Options.UserInformationEndpoint, contextId);
// Get the SuperOffice user principal.
using var request = new HttpRequestMessage(HttpMethod.Get, userInfoEndpoint);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken);
using var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted);
if (!response.IsSuccessStatusCode)
{
Logger.LogError("An error occurred while retrieving the user profile: the remote server " +
"returned a {Status} response with the following payload: {Headers} {Body}.",
/* Status: */ response.StatusCode,
/* Headers: */ response.Headers.ToString(),
/* Body: */ await response.Content.ReadAsStringAsync());
throw new HttpRequestException($"An error occurred when retrieving SuperOffice user information ({response.StatusCode}).");
}
using var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, payload.RootElement);
context.RunClaimActions();
await Events.CreatingTicket(context);
return new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name);
}
private async Task<string> ProcessIdTokenAndGetContactIdentifierAsync(
[NotNull] OAuthTokenResponse tokens,
[NotNull] AuthenticationProperties properties,
[NotNull] ClaimsIdentity identity)
{
var contextIdentifier = string.Empty;
var idToken = tokens.Response.RootElement.GetString("id_token");
if (Options.SaveTokens)
{
// Save id_token as well.
SaveIdToken(properties, idToken);
}
var tokenValidationResult = await ValidateAsync(idToken, Options.TokenValidationParameters.Clone());
foreach (var claim in tokenValidationResult.ClaimsIdentity.Claims)
{
if (claim.Type == SuperOfficeAuthenticationConstants.ClaimNames.ContextIdentifier)
{
contextIdentifier = claim.Value;
}
if (Options.IncludeIdTokenAsClaims)
{
// May be possible same claim names from UserInformationEndpoint and IdToken.
if (!identity.HasClaim(c => c.Type == claim.Type))
{
identity.AddClaim(claim);
}
}
}
return contextIdentifier;
}
/// <summary>
/// Store id_token in <paramref name="properties"/> token collection.
/// </summary>
/// <param name="properties">Authentication properties.</param>
/// <param name="idToken">The id_token JWT.</param>
private static void SaveIdToken(
[NotNull] AuthenticationProperties properties,
[NotNull] string idToken)
{
if (!string.IsNullOrWhiteSpace(idToken))
{
// Get the currently available tokens
var tokens = properties.GetTokens().ToList();
// Add the extra token
tokens.Add(new AuthenticationToken() { Name = "id_token", Value = idToken });
// Overwrite store with original tokens with the new additional token
properties.StoreTokens(tokens);
}
}
private async Task<TokenValidationResult> ValidateAsync(
[NotNull] string idToken,
[NotNull] TokenValidationParameters validationParameters)
{
if (Options.SecurityTokenHandler == null)
{
throw new InvalidOperationException("The options SecurityTokenHandler is null.");
}
if (!Options.SecurityTokenHandler.CanValidateToken)
{
throw new NotSupportedException($"The configured {nameof(JsonWebTokenHandler)} cannot validate tokens.");
}
if (Options.ConfigurationManager == null)
{
throw new InvalidOperationException($"An OpenID Connect configuration manager has not been set on the {nameof(SuperOfficeAuthenticationOptions)} instance.");
}
var openIdConnectConfiguration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
validationParameters.IssuerSigningKeys = openIdConnectConfiguration.JsonWebKeySet.Keys;
try
{
return Options.SecurityTokenHandler.ValidateToken(idToken, validationParameters);
}
catch (Exception ex)
{
throw new SecurityTokenValidationException(
"SuperOffice ID token validation failed for issuer and/or audience.", ex);
}
}
}
}