Skip to content

Commit 3246aad

Browse files
Use C# 12 features (#806)
- Use primary constructors where relevant. - Use collection literals where relevant. - Add helper method to reduce duplicative tests. - Apply some IDE suggestions. - Remove redundant using statements. - Fix some typos. - Hide shared files from the Visual Studio project explorer.
1 parent 54962db commit 3246aad

File tree

161 files changed

+418
-1973
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

161 files changed

+418
-1973
lines changed

Directory.Build.props

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@
7878
</PropertyGroup>
7979

8080
<ItemGroup>
81-
<AdditionalFiles Include="$(MSBuildThisFileDirectory)stylecop.json" Link="stylecop.json" />
81+
<AdditionalFiles Include="$(MSBuildThisFileDirectory)stylecop.json" Link="stylecop.json" Visible="false" />
8282
<PackageReference Include="StyleCop.Analyzers" PrivateAssets="All" />
8383
</ItemGroup>
8484

@@ -98,7 +98,7 @@
9898
</ItemGroup>
9999

100100
<ItemGroup>
101-
<None Include="$(MSBuildThisFileDirectory)$(PackageReadmeFile)" Pack="True" PackagePath="" />
101+
<None Include="$(MSBuildThisFileDirectory)$(PackageReadmeFile)" Pack="True" PackagePath="" Visible="false" />
102102
</ItemGroup>
103103

104104
</Project>

samples/Mvc.Client/Controllers/AuthenticationController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public class AuthenticationController : Controller
1919
public async Task<IActionResult> SignIn([FromForm] string provider)
2020
{
2121
// Note: the "provider" parameter corresponds to the external
22-
// authentication provider choosen by the user agent.
22+
// authentication provider chosen by the user agent.
2323
if (string.IsNullOrWhiteSpace(provider))
2424
{
2525
return BadRequest();

samples/Mvc.Client/Startup.cs

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,8 @@
99

1010
namespace Mvc.Client;
1111

12-
public class Startup
12+
public class Startup(IConfiguration configuration, IHostEnvironment hostingEnvironment)
1313
{
14-
public Startup(IConfiguration configuration, IHostEnvironment hostingEnvironment)
15-
{
16-
Configuration = configuration;
17-
HostingEnvironment = hostingEnvironment;
18-
}
19-
20-
public IConfiguration Configuration { get; }
21-
22-
private IHostEnvironment HostingEnvironment { get; }
23-
2414
public void ConfigureServices(IServiceCollection services)
2515
{
2616
services.AddRouting();
@@ -38,21 +28,21 @@ public void ConfigureServices(IServiceCollection services)
3828

3929
.AddGoogle(options =>
4030
{
41-
options.ClientId = Configuration["Google:ClientId"] ?? string.Empty;
42-
options.ClientSecret = Configuration["Google:ClientSecret"] ?? string.Empty;
31+
options.ClientId = configuration["Google:ClientId"] ?? string.Empty;
32+
options.ClientSecret = configuration["Google:ClientSecret"] ?? string.Empty;
4333
})
4434

4535
.AddTwitter(options =>
4636
{
47-
options.ClientId = Configuration["Twitter:ClientId"] ?? string.Empty;
48-
options.ClientSecret = Configuration["Twitter:ClientSecret"] ?? string.Empty;
37+
options.ClientId = configuration["Twitter:ClientId"] ?? string.Empty;
38+
options.ClientSecret = configuration["Twitter:ClientSecret"] ?? string.Empty;
4939
})
5040

5141
.AddGitHub(options =>
5242
{
53-
options.ClientId = Configuration["GitHub:ClientId"] ?? string.Empty;
54-
options.ClientSecret = Configuration["GitHub:ClientSecret"] ?? string.Empty;
55-
options.EnterpriseDomain = Configuration["GitHub:EnterpriseDomain"] ?? string.Empty;
43+
options.ClientId = configuration["GitHub:ClientId"] ?? string.Empty;
44+
options.ClientSecret = configuration["GitHub:ClientSecret"] ?? string.Empty;
45+
options.EnterpriseDomain = configuration["GitHub:EnterpriseDomain"] ?? string.Empty;
5646
options.Scope.Add("user:email");
5747
})
5848

@@ -69,16 +59,16 @@ public void ConfigureServices(IServiceCollection services)
6959

7060
.AddDropbox(options =>
7161
{
72-
options.ClientId = Configuration["Dropbox:ClientId"] ?? string.Empty;
73-
options.ClientSecret = Configuration["Dropbox:ClientSecret"] ?? string.Empty;
62+
options.ClientId = configuration["Dropbox:ClientId"] ?? string.Empty;
63+
options.ClientSecret = configuration["Dropbox:ClientSecret"] ?? string.Empty;
7464
});
7565

7666
services.AddMvc();
7767
}
7868

7969
public void Configure(IApplicationBuilder app)
8070
{
81-
if (HostingEnvironment.IsDevelopment())
71+
if (hostingEnvironment.IsDevelopment())
8272
{
8373
IdentityModelEventSource.ShowPII = true;
8474
}

src/AspNet.Security.OAuth.AdobeIO/AdobeIOAuthenticationHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ protected override async Task<AuthenticationTicket> CreateTicketAsync(
2929
[NotNull] AuthenticationProperties properties,
3030
[NotNull] OAuthTokenResponse tokens)
3131
{
32-
string address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "client_id", Options.ClientId);
32+
var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "client_id", Options.ClientId);
3333

3434
using var request = new HttpRequestMessage(HttpMethod.Get, address);
3535
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

src/AspNet.Security.OAuth.Amazon/AmazonAuthenticationHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ protected override async Task<AuthenticationTicket> CreateTicketAsync(
3939
[NotNull] AuthenticationProperties properties,
4040
[NotNull] OAuthTokenResponse tokens)
4141
{
42-
string endpoint = Options.UserInformationEndpoint;
42+
var endpoint = Options.UserInformationEndpoint;
4343

4444
if (Options.Fields.Count > 0)
4545
{

src/AspNet.Security.OAuth.AmoCrm/AmoCrmAuthenticationHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ protected override async Task<AuthenticationTicket> CreateTicketAsync(
3838
[NotNull] AuthenticationProperties properties,
3939
[NotNull] OAuthTokenResponse tokens)
4040
{
41-
string endpoint = Options.UserInformationEndpoint;
41+
var endpoint = Options.UserInformationEndpoint;
4242

4343
using var request = new HttpRequestMessage(HttpMethod.Get, endpoint);
4444
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

src/AspNet.Security.OAuth.Apple/AppleAuthenticationEvents.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,15 @@ public class AppleAuthenticationEvents : OAuthEvents
1414
/// <summary>
1515
/// Gets or sets the delegate that is invoked when the <see cref="GenerateClientSecret"/> method is invoked.
1616
/// </summary>
17-
public Func<AppleGenerateClientSecretContext, Task> OnGenerateClientSecret { get; set; } = async context =>
17+
public Func<AppleGenerateClientSecretContext, Task> OnGenerateClientSecret { get; set; } = static async context =>
1818
{
1919
context.Options.ClientSecret = await context.Options.ClientSecretGenerator.GenerateAsync(context);
2020
};
2121

2222
/// <summary>
2323
/// Gets or sets the delegate that is invoked when the <see cref="ValidateIdToken"/> method is invoked.
2424
/// </summary>
25-
public Func<AppleValidateIdTokenContext, Task> OnValidateIdToken { get; set; } = async context =>
25+
public Func<AppleValidateIdTokenContext, Task> OnValidateIdToken { get; set; } = static async context =>
2626
{
2727
await context.Options.TokenValidator.ValidateAsync(context);
2828
};

src/AspNet.Security.OAuth.Apple/AppleAuthenticationHandler.cs

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,14 @@ namespace AspNet.Security.OAuth.Apple;
1919
/// <summary>
2020
/// Defines a handler for authentication using Apple.
2121
/// </summary>
22-
public partial class AppleAuthenticationHandler : OAuthHandler<AppleAuthenticationOptions>
22+
/// <param name="options">The authentication options.</param>
23+
/// <param name="logger">The logger to use.</param>
24+
/// <param name="encoder">The URL encoder to use.</param>
25+
public partial class AppleAuthenticationHandler(
26+
[NotNull] IOptionsMonitor<AppleAuthenticationOptions> options,
27+
[NotNull] ILoggerFactory logger,
28+
[NotNull] UrlEncoder encoder) : OAuthHandler<AppleAuthenticationOptions>(options, logger, encoder)
2329
{
24-
/// <summary>
25-
/// Initializes a new instance of the <see cref="AppleAuthenticationHandler"/> class.
26-
/// </summary>
27-
/// <param name="options">The authentication options.</param>
28-
/// <param name="logger">The logger to use.</param>
29-
/// <param name="encoder">The URL encoder to use.</param>
30-
public AppleAuthenticationHandler(
31-
[NotNull] IOptionsMonitor<AppleAuthenticationOptions> options,
32-
[NotNull] ILoggerFactory logger,
33-
[NotNull] UrlEncoder encoder)
34-
: base(options, logger, encoder)
35-
{
36-
}
37-
3830
/// <summary>
3931
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
4032
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
@@ -133,7 +125,7 @@ protected virtual IEnumerable<Claim> ExtractClaimsFromToken([NotNull] string tok
133125

134126
var claims = new List<Claim>(securityToken.Claims)
135127
{
136-
new Claim(ClaimTypes.NameIdentifier, securityToken.Subject, ClaimValueTypes.String, ClaimsIssuer),
128+
new(ClaimTypes.NameIdentifier, securityToken.Subject, ClaimValueTypes.String, ClaimsIssuer),
137129
};
138130

139131
var emailClaim = claims.Find((p) => string.Equals(p.Type, "email", StringComparison.Ordinal));
@@ -283,19 +275,19 @@ private async Task<HandleRequestResult> HandleRemoteAuthenticateAsync(
283275

284276
if (Options.SaveTokens)
285277
{
286-
var authTokens = new List<AuthenticationToken>()
287-
{
288-
new AuthenticationToken() { Name = "access_token", Value = tokens.AccessToken },
289-
};
278+
List<AuthenticationToken> authTokens =
279+
[
280+
new() { Name = "access_token", Value = tokens.AccessToken },
281+
];
290282

291283
if (!string.IsNullOrEmpty(tokens.RefreshToken))
292284
{
293-
authTokens.Add(new AuthenticationToken() { Name = "refresh_token", Value = tokens.RefreshToken });
285+
authTokens.Add(new() { Name = "refresh_token", Value = tokens.RefreshToken });
294286
}
295287

296288
if (!string.IsNullOrEmpty(tokens.TokenType))
297289
{
298-
authTokens.Add(new AuthenticationToken() { Name = "token_type", Value = tokens.TokenType });
290+
authTokens.Add(new() { Name = "token_type", Value = tokens.TokenType });
299291
}
300292

301293
if (!string.IsNullOrEmpty(tokens.ExpiresIn))
@@ -306,7 +298,7 @@ private async Task<HandleRequestResult> HandleRemoteAuthenticateAsync(
306298
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
307299
var expiresAt = TimeProvider.GetUtcNow().AddSeconds(value);
308300

309-
authTokens.Add(new AuthenticationToken()
301+
authTokens.Add(new()
310302
{
311303
Name = "expires_at",
312304
Value = expiresAt.ToString("o", CultureInfo.InvariantCulture),
@@ -318,7 +310,7 @@ private async Task<HandleRequestResult> HandleRemoteAuthenticateAsync(
318310

319311
if (!string.IsNullOrEmpty(idToken))
320312
{
321-
authTokens.Add(new AuthenticationToken() { Name = "id_token", Value = idToken });
313+
authTokens.Add(new() { Name = "id_token", Value = idToken });
322314
}
323315

324316
properties.StoreTokens(authTokens);

src/AspNet.Security.OAuth.Apple/AppleEmailClaimAction.cs

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,8 @@
1010

1111
namespace AspNet.Security.OAuth.Apple;
1212

13-
internal sealed class AppleEmailClaimAction : ClaimAction
13+
internal sealed class AppleEmailClaimAction(AppleAuthenticationOptions options) : ClaimAction(ClaimTypes.Email, ClaimValueTypes.String)
1414
{
15-
private readonly AppleAuthenticationOptions _options;
16-
17-
internal AppleEmailClaimAction(AppleAuthenticationOptions options)
18-
: base(ClaimTypes.Email, ClaimValueTypes.String)
19-
{
20-
_options = options;
21-
}
22-
2315
public override void Run(JsonElement userData, ClaimsIdentity identity, string issuer)
2416
{
2517
if (!identity.HasClaim((p) => string.Equals(p.Type, ClaimType, StringComparison.OrdinalIgnoreCase)))
@@ -28,7 +20,7 @@ public override void Run(JsonElement userData, ClaimsIdentity identity, string i
2820

2921
if (!string.IsNullOrEmpty(emailClaim?.Value))
3022
{
31-
identity.AddClaim(new Claim(ClaimType, emailClaim.Value, ValueType, _options.ClaimsIssuer));
23+
identity.AddClaim(new Claim(ClaimType, emailClaim.Value, ValueType, options.ClaimsIssuer));
3224
}
3325
}
3426
}

src/AspNet.Security.OAuth.Apple/AppleGenerateClientSecretContext.cs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,12 @@ namespace AspNet.Security.OAuth.Apple;
1111
/// <summary>
1212
/// Contains information about the current request.
1313
/// </summary>
14-
public class AppleGenerateClientSecretContext : BaseContext<AppleAuthenticationOptions>
14+
/// <param name="context">The HTTP context.</param>
15+
/// <param name="scheme">The authentication scheme.</param>
16+
/// <param name="options">The authentication options associated with the scheme.</param>
17+
public class AppleGenerateClientSecretContext(
18+
HttpContext context,
19+
AuthenticationScheme scheme,
20+
AppleAuthenticationOptions options) : BaseContext<AppleAuthenticationOptions>(context, scheme, options)
1521
{
16-
/// <summary>
17-
/// Creates a new instance of the <see cref="AppleGenerateClientSecretContext"/> class.
18-
/// </summary>
19-
/// <param name="context">The HTTP context.</param>
20-
/// <param name="scheme">The authentication scheme.</param>
21-
/// <param name="options">The authentication options associated with the scheme.</param>
22-
public AppleGenerateClientSecretContext(HttpContext context, AuthenticationScheme scheme, AppleAuthenticationOptions options)
23-
: base(context, scheme, options)
24-
{
25-
}
2622
}

0 commit comments

Comments
 (0)