Skip to content

Add AuthN/AuthZ metrics #59557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ public static IServiceCollection AddAuthenticationCore(this IServiceCollection s
{
ArgumentNullException.ThrowIfNull(services);

services.AddMetrics();
services.TryAddScoped<IAuthenticationService, AuthenticationService>();
services.TryAddSingleton<IClaimsTransformation, NoopClaimsTransformation>(); // Can be replaced with scoped ones that use DbContext
services.TryAddScoped<IAuthenticationHandlerProvider, AuthenticationHandlerProvider>();
services.TryAddSingleton<IAuthenticationSchemeProvider, AuthenticationSchemeProvider>();
services.TryAddSingleton<AuthenticationMetrics>();
return services;
}

Expand Down
105 changes: 105 additions & 0 deletions src/Http/Authentication.Core/src/AuthenticationMetrics.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Diagnostics.Metrics;

namespace Microsoft.AspNetCore.Authentication;

internal sealed class AuthenticationMetrics : IDisposable
{
public const string MeterName = "Microsoft.AspNetCore.Authentication";

private readonly Meter _meter;
private readonly Counter<long> _authenticatedRequestCount;
private readonly Counter<long> _challengeCount;
private readonly Counter<long> _forbidCount;
private readonly Counter<long> _signInCount;
private readonly Counter<long> _signOutCount;

public AuthenticationMetrics(IMeterFactory meterFactory)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be great to have a doc describing the meaning and format of each metric and hopefully add them to https://github.com/open-telemetry/semantic-conventions/blob/main/docs/dotnet/dotnet-aspnetcore-metrics.md. Happy to help if necessary.

{
_meter = meterFactory.Create(MeterName);

_authenticatedRequestCount = _meter.CreateCounter<long>(
"aspnetcore.authentication.authenticated_requests",
unit: "{request}",
description: "The total number of authenticated requests");

_challengeCount = _meter.CreateCounter<long>(
"aspnetcore.authentication.challenges",
unit: "{request}",
description: "The total number of times a scheme is challenged");

_forbidCount = _meter.CreateCounter<long>(
"aspnetcore.authentication.forbids",
unit: "{request}",
description: "The total number of times an authenticated user attempts to access a resource they are not permitted to access");

_signInCount = _meter.CreateCounter<long>(
"aspnetcore.authentication.sign_ins",
unit: "{request}",
description: "The total number of times a principal is signed in");

_signOutCount = _meter.CreateCounter<long>(
"aspnetcore.authentication.sign_outs",
unit: "{request}",
description: "The total number of times a scheme is signed out");
}

public void AuthenticatedRequest(string scheme, AuthenticateResult result)
{
if (_authenticatedRequestCount.Enabled)
{
var resultTagValue = result switch
{
{ Succeeded: true } => "success",
{ Failure: not null } => "failure",
{ None: true } => "none",
_ => throw new UnreachableException($"Could not determine the result state of the {nameof(AuthenticateResult)}"),
};

_authenticatedRequestCount.Add(1, [
new("aspnetcore.authentication.scheme", scheme),
new("aspnetcore.authentication.result", resultTagValue),
]);
}
}

public void Challenge(string scheme)
{
if (_challengeCount.Enabled)
{
_challengeCount.Add(1, [new("aspnetcore.authentication.scheme", scheme)]);
}
}

public void Forbid(string scheme)
{
if (_forbidCount.Enabled)
{
_forbidCount.Add(1, [new("aspnetcore.authentication.scheme", scheme)]);
}
}

public void SignIn(string scheme)
{
if (_signInCount.Enabled)
{
_signInCount.Add(1, [new("aspnetcore.authentication.scheme", scheme)]);
}
}

public void SignOut(string scheme)
{
if (_signOutCount.Enabled)
{
_signOutCount.Add(1, [new("aspnetcore.authentication.scheme", scheme)]);
}
}

public void Dispose()
{
_meter.Dispose();
}
}
41 changes: 39 additions & 2 deletions src/Http/Authentication.Core/src/AuthenticationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Authentication;
Expand All @@ -13,6 +14,8 @@ namespace Microsoft.AspNetCore.Authentication;
/// </summary>
public class AuthenticationService : IAuthenticationService
{
private readonly AuthenticationMetrics? _metrics;

private HashSet<ClaimsPrincipal>? _transformCache;

/// <summary>
Expand All @@ -22,12 +25,36 @@ public class AuthenticationService : IAuthenticationService
/// <param name="handlers">The <see cref="IAuthenticationHandlerProvider"/>.</param>
/// <param name="transform">The <see cref="IClaimsTransformation"/>.</param>
/// <param name="options">The <see cref="AuthenticationOptions"/>.</param>
public AuthenticationService(IAuthenticationSchemeProvider schemes, IAuthenticationHandlerProvider handlers, IClaimsTransformation transform, IOptions<AuthenticationOptions> options)
public AuthenticationService(
IAuthenticationSchemeProvider schemes,
IAuthenticationHandlerProvider handlers,
IClaimsTransformation transform,
IOptions<AuthenticationOptions> options)
: this(schemes, handlers, transform, options, services: null)
{
}

/// <summary>
/// Constructor.
/// </summary>
/// <param name="schemes">The <see cref="IAuthenticationSchemeProvider"/>.</param>
/// <param name="handlers">The <see cref="IAuthenticationHandlerProvider"/>.</param>
/// <param name="transform">The <see cref="IClaimsTransformation"/>.</param>
/// <param name="options">The <see cref="AuthenticationOptions"/>.</param>
/// <param name="services">The <see cref="IServiceProvider"/>.</param>
public AuthenticationService(
IAuthenticationSchemeProvider schemes,
IAuthenticationHandlerProvider handlers,
IClaimsTransformation transform,
IOptions<AuthenticationOptions> options,
IServiceProvider? services)
{
Schemes = schemes;
Handlers = handlers;
Transform = transform;
Options = options.Value;

_metrics = services?.GetService<AuthenticationMetrics>();
}

/// <summary>
Expand Down Expand Up @@ -77,11 +104,13 @@ public virtual async Task<AuthenticateResult> AuthenticateAsync(HttpContext cont
// Handlers should not return null, but we'll be tolerant of null values for legacy reasons.
var result = (await handler.AuthenticateAsync()) ?? AuthenticateResult.NoResult();

_metrics?.AuthenticatedRequest(scheme, result);

if (result.Succeeded)
{
var principal = result.Principal!;
var doTransform = true;
_transformCache ??= new HashSet<ClaimsPrincipal>();
_transformCache ??= [];
if (_transformCache.Contains(principal))
{
doTransform = false;
Expand Down Expand Up @@ -122,6 +151,8 @@ public virtual async Task ChallengeAsync(HttpContext context, string? scheme, Au
throw await CreateMissingHandlerException(scheme);
}

_metrics?.Challenge(scheme);

await handler.ChallengeAsync(properties);
}

Expand Down Expand Up @@ -150,6 +181,8 @@ public virtual async Task ForbidAsync(HttpContext context, string? scheme, Authe
throw await CreateMissingHandlerException(scheme);
}

_metrics?.Forbid(scheme);

await handler.ForbidAsync(properties);
}

Expand Down Expand Up @@ -199,6 +232,8 @@ public virtual async Task SignInAsync(HttpContext context, string? scheme, Claim
throw await CreateMismatchedSignInHandlerException(scheme, handler);
}

_metrics?.SignIn(scheme);

await signInHandler.SignInAsync(principal, properties);
}

Expand Down Expand Up @@ -233,6 +268,8 @@ public virtual async Task SignOutAsync(HttpContext context, string? scheme, Auth
throw await CreateMismatchedSignOutHandlerException(scheme, handler);
}

_metrics?.SignOut(scheme);

await signOutHandler.SignOutAsync(properties);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@
<Reference Include="Microsoft.AspNetCore.Http.Extensions" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Microsoft.AspNetCore.Authentication.Test" />
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions src/Http/Authentication.Core/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticationService(Microsoft.AspNetCore.Authentication.IAuthenticationSchemeProvider! schemes, Microsoft.AspNetCore.Authentication.IAuthenticationHandlerProvider! handlers, Microsoft.AspNetCore.Authentication.IClaimsTransformation! transform, Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.Authentication.AuthenticationOptions!>! options, System.IServiceProvider? services) -> void
Loading
Loading