-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAuthenticationBuilderExtensions.cs
More file actions
191 lines (175 loc) · 8.49 KB
/
AuthenticationBuilderExtensions.cs
File metadata and controls
191 lines (175 loc) · 8.49 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
namespace Logto.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Extension methods to configure Logto authentication.
/// </summary>
/// <remarks>
/// <para>
/// Logto is an identity layer on top of the Open ID Connect protocol. This extension leverages the Open ID Connect
/// authentication handler but adds additional functionality to support Logto's requirements.
/// </para>
/// </remarks>
public static class AuthenticationBuilderExtensions
{
/// <summary>
/// Adds Logto authentication to <see cref="AuthenticationBuilder"/> using the default scheme.
/// The default scheme is specified by <see cref="LogtoDefaults.AuthenticationScheme"/>, which is "Logto";
/// The default cookie scheme is specified by <see cref="LogtoDefaults.CookieScheme"/>, which is "Logto.Cookie";
/// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
/// <param name="configureOptions">A delegate to configure <see cref="LogtoOptions"/>.</param>
/// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
public static AuthenticationBuilder AddLogto(this AuthenticationBuilder builder, Action<LogtoOptions> configureOptions)
=> builder.AddLogto(LogtoDefaults.AuthenticationScheme, configureOptions);
/// <summary>
/// Adds Logto authentication to <see cref="AuthenticationBuilder"/> using the specified scheme.
/// The default cookie scheme is specified by <see cref="LogtoDefaults.CookieScheme"/>, which is "Logto.Cookie";
/// </summary>
/// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
/// <param name="authenticationScheme">The authentication scheme.</param>
/// <param name="configureOptions">A delegate to configure <see cref="LogtoOptions"/>.</param>
/// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
public static AuthenticationBuilder AddLogto(this AuthenticationBuilder builder, string authenticationScheme, Action<LogtoOptions> configureOptions)
=> builder.AddLogto(authenticationScheme, LogtoDefaults.CookieScheme, configureOptions);
/// <summary>
/// Adds Logto authentication to <see cref="AuthenticationBuilder"/> using the specified scheme and cookie scheme.
/// </summary>
/// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
/// <param name="authenticationScheme">The authentication scheme.</param>
/// <param name="cookieScheme">The cookie scheme.</param>
/// <param name="configureOptions">A delegate to configure <see cref="LogtoOptions"/>.</param>
/// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
public static AuthenticationBuilder AddLogto(this AuthenticationBuilder builder, string authenticationScheme, string cookieScheme, Action<LogtoOptions> configureOptions)
{
var logtoOptions = new LogtoOptions();
configureOptions(logtoOptions);
builder.Services.Configure(authenticationScheme, configureOptions);
builder.Services
.AddOptions<CookieAuthenticationOptions>(cookieScheme)
.Configure((options) => ConfigureCookieOptions(authenticationScheme, options, logtoOptions));
builder.AddCookie(cookieScheme);
builder.AddOpenIdConnect(authenticationScheme, oidcOptions => ConfigureOpenIdConnectOptions(oidcOptions, logtoOptions, cookieScheme));
return builder;
}
/// <summary>
/// Configures the cookie options for Logto authentication. This method will mutate the `options` parameter.
/// </summary>
private static void ConfigureCookieOptions(string authenticationScheme, CookieAuthenticationOptions options, LogtoOptions logtoOptions)
{
options.Cookie.Name = $"Logto.Cookie.{logtoOptions.AppId}";
options.SlidingExpiration = true;
options.Cookie.Domain = logtoOptions.CookieDomain;
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = context => new LogtoCookieContextManager(authenticationScheme, context).Handle()
};
}
/// <summary>
/// Configures the OpenID Connect options for Logto authentication. This method will mutate the `options` parameter.
/// </summary>
/// <param name="options">The OpenID Connect options to configure.</param>
/// <param name="logtoOptions">The Logto options to use for configuration.</param>
private static void ConfigureOpenIdConnectOptions(OpenIdConnectOptions options, LogtoOptions logtoOptions, string cookieScheme)
{
options.Authority = logtoOptions.Endpoint + "oidc";
options.ClientId = logtoOptions.AppId;
options.ClientSecret = logtoOptions.AppSecret;
options.ResponseType = OpenIdConnectResponseType.Code;
options.SaveTokens = true;
options.UsePkce = true;
options.Prompt = logtoOptions.Prompt;
options.CallbackPath = new PathString(logtoOptions.CallbackPath);
options.SignedOutCallbackPath = new PathString(logtoOptions.SignedOutCallbackPath);
options.GetClaimsFromUserInfoEndpoint = logtoOptions.GetClaimsFromUserInfoEndpoint;
options.MapInboundClaims = false;
options.ClaimActions.MapAllExcept("nbf", "nonce", "c_hash", "at_hash");
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = context =>
{
if (context.Properties.Parameters.TryGetValue("first_screen", out var firstScreen))
{
context.ProtocolMessage.Parameters.Add("first_screen", firstScreen?.ToString());
}
if (context.Properties.Parameters.TryGetValue("identifiers", out var identifiers))
{
var identifierArray = System.Text.Json.JsonSerializer.Deserialize<string[]>(
identifiers?.ToString() ?? "[]"
);
if (identifierArray?.Length > 0)
{
context.ProtocolMessage.Parameters.Add("identifier", string.Join(" ", identifierArray));
}
}
if (context.Properties.Parameters.TryGetValue("direct_sign_in", out var directSignIn))
{
var directSignInOption = System.Text.Json.JsonSerializer.Deserialize<LogtoParameters.Authentication.DirectSignIn>(
directSignIn?.ToString() ?? "{}"
);
if (directSignInOption != null && !string.IsNullOrEmpty(directSignInOption.Method) && !string.IsNullOrEmpty(directSignInOption.Target))
{
context.ProtocolMessage.Parameters.Add("direct_sign_in", $"{directSignInOption.Method}:{directSignInOption.Target}");
}
}
if (context.Properties.Parameters.TryGetValue("extra_params", out var extraParams))
{
var parameters = System.Text.Json.JsonSerializer.Deserialize<LogtoParameters.Authentication.ExtraParams>(
extraParams?.ToString() ?? "{}"
);
if (parameters != null)
{
foreach (var param in parameters)
{
context.ProtocolMessage.Parameters.Add(param.Key, param.Value);
}
}
}
return Task.CompletedTask;
},
OnRedirectToIdentityProviderForSignOut = async context =>
{
// Clean up the cookie when signing out.
await context.HttpContext.SignOutAsync(cookieScheme);
// Rebuild parameters since we use <c>client_id</c> for sign-out, no need to use <c>id_token_hint</c>.
context.ProtocolMessage.Parameters.Remove(OpenIdConnectParameterNames.IdTokenHint);
context.ProtocolMessage.Parameters.Add(OpenIdConnectParameterNames.ClientId, logtoOptions.AppId);
},
};
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "roles",
ValidateAudience = true,
ValidAudience = logtoOptions.AppId,
ValidateIssuer = true,
ValidIssuer = logtoOptions.Endpoint + "oidc",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
};
// Handle scopes
var scopes = new HashSet<string>(logtoOptions.Scopes)
{
"openid",
"offline_access",
"profile"
};
options.Scope.Clear();
foreach (var scope in scopes)
{
options.Scope.Add(scope);
}
// Handle resource
if (!string.IsNullOrEmpty(logtoOptions.Resource))
{
options.Resource = logtoOptions.Resource;
}
}
}