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 8 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.TryAddScoped<IAuthenticationService, AuthenticationService>();
services.AddMetrics();
services.TryAddScoped<IAuthenticationService, AuthenticationServiceImpl>();
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
248 changes: 248 additions & 0 deletions src/Http/Authentication.Core/src/AuthenticationMetrics.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
// 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;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Authentication;

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

private readonly Meter _meter;
private readonly Histogram<double> _authenticatedRequestDuration;
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);

_authenticatedRequestDuration = _meter.CreateHistogram<double>(
"aspnetcore.authentication.authenticate.duration",
unit: "s",
description: "The authentication duration for a request.",
advice: new() { HistogramBucketBoundaries = MetricsConstants.ShortSecondsBucketBoundaries });

_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 AuthenticatedRequestSucceeded(string? scheme, AuthenticateResult result, long startTimestamp, long currentTimestamp)
{
if (_authenticatedRequestDuration.Enabled)
{
AuthenticatedRequestSucceededCore(scheme, result, startTimestamp, currentTimestamp);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void AuthenticatedRequestSucceededCore(string? scheme, AuthenticateResult result, long startTimestamp, long currentTimestamp)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);

var resultTagValue = result switch
{
{ None: true } => "none",
{ Succeeded: true } => "success",
{ Failure: not null } => "failure",
_ => "_OTHER", // _OTHER is commonly used fallback for an extra or unexpected value. Shouldn't reach here.
};
tags.Add("aspnetcore.authentication.result", resultTagValue);

var duration = Stopwatch.GetElapsedTime(startTimestamp, currentTimestamp);
_authenticatedRequestDuration.Record(duration.TotalSeconds, tags);
}

public void AuthenticatedRequestFailed(string? scheme, Exception exception, long startTimestamp, long currentTimestamp)
{
if (_authenticatedRequestDuration.Enabled)
{
AuthenticatedRequestFailedCore(scheme, exception, startTimestamp, currentTimestamp);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void AuthenticatedRequestFailedCore(string? scheme, Exception exception, long startTimestamp, long currentTimestamp)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);
AddErrorTag(ref tags, exception);

var duration = Stopwatch.GetElapsedTime(startTimestamp, currentTimestamp);
_authenticatedRequestDuration.Record(duration.TotalSeconds, tags);
}

public void ChallengeSucceeded(string? scheme)
{
if (_challengeCount.Enabled)
{
ChallengeSucceededCore(scheme);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void ChallengeSucceededCore(string? scheme)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);

_challengeCount.Add(1, tags);
}

public void ChallengeFailed(string? scheme, Exception exception)
{
if (_challengeCount.Enabled)
{
ChallengeFailedCore(scheme, exception);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void ChallengeFailedCore(string? scheme, Exception exception)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);
AddErrorTag(ref tags, exception);

_challengeCount.Add(1, tags);
}

public void ForbidSucceeded(string? scheme)
{
if (_forbidCount.Enabled)
{
ForbidSucceededCore(scheme);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void ForbidSucceededCore(string? scheme)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);
_forbidCount.Add(1, tags);
}

public void ForbidFailed(string? scheme, Exception exception)
{
if (_forbidCount.Enabled)
{
ForbidFailedCore(scheme, exception);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void ForbidFailedCore(string? scheme, Exception exception)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);
AddErrorTag(ref tags, exception);

_forbidCount.Add(1, tags);
}

public void SignInSucceeded(string? scheme)
{
if (_signInCount.Enabled)
{
SignInSucceededCore(scheme);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void SignInSucceededCore(string? scheme)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);
_signInCount.Add(1, tags);
}

public void SignInFailed(string? scheme, Exception exception)
{
if (_signInCount.Enabled)
{
SignInFailedCore(scheme, exception);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void SignInFailedCore(string? scheme, Exception exception)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);
AddErrorTag(ref tags, exception);

_signInCount.Add(1, tags);
}

public void SignOutSucceeded(string? scheme)
{
if (_signOutCount.Enabled)
{
SignOutSucceededCore(scheme);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void SignOutSucceededCore(string? scheme)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);
_signOutCount.Add(1, tags);
}

public void SignOutFailed(string? scheme, Exception exception)
{
if (_signOutCount.Enabled)
{
SignOutFailedCore(scheme, exception);
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void SignOutFailedCore(string? scheme, Exception exception)
{
var tags = new TagList();
TryAddSchemeTag(ref tags, scheme);
AddErrorTag(ref tags, exception);

_signOutCount.Add(1, tags);
}

private static void TryAddSchemeTag(ref TagList tags, string? scheme)
{
if (scheme is not null)
{
tags.Add("aspnetcore.authentication.scheme", scheme);
}
}

private static void AddErrorTag(ref TagList tags, Exception exception)
{
tags.Add("error.type", exception.GetType().FullName);
}
}
49 changes: 14 additions & 35 deletions src/Http/Authentication.Core/src/AuthenticationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ 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)
{
Schemes = schemes;
Handlers = handlers;
Expand Down Expand Up @@ -68,11 +72,7 @@ public virtual async Task<AuthenticateResult> AuthenticateAsync(HttpContext cont
}
}

var handler = await Handlers.GetHandlerAsync(context, scheme);
if (handler == null)
{
throw await CreateMissingHandlerException(scheme);
}
var handler = await Handlers.GetHandlerAsync(context, scheme) ?? throw await CreateMissingHandlerException(scheme);

// Handlers should not return null, but we'll be tolerant of null values for legacy reasons.
var result = (await handler.AuthenticateAsync()) ?? AuthenticateResult.NoResult();
Expand All @@ -81,7 +81,7 @@ public virtual async Task<AuthenticateResult> AuthenticateAsync(HttpContext cont
{
var principal = result.Principal!;
var doTransform = true;
_transformCache ??= new HashSet<ClaimsPrincipal>();
_transformCache ??= [];
if (_transformCache.Contains(principal))
{
doTransform = false;
Expand All @@ -94,6 +94,7 @@ public virtual async Task<AuthenticateResult> AuthenticateAsync(HttpContext cont
}
return AuthenticateResult.Success(new AuthenticationTicket(principal, result.Properties, result.Ticket!.AuthenticationScheme));
}

return result;
}

Expand All @@ -116,12 +117,7 @@ public virtual async Task ChallengeAsync(HttpContext context, string? scheme, Au
}
}

var handler = await Handlers.GetHandlerAsync(context, scheme);
if (handler == null)
{
throw await CreateMissingHandlerException(scheme);
}

var handler = await Handlers.GetHandlerAsync(context, scheme) ?? throw await CreateMissingHandlerException(scheme);
await handler.ChallengeAsync(properties);
}

Expand All @@ -144,12 +140,7 @@ public virtual async Task ForbidAsync(HttpContext context, string? scheme, Authe
}
}

var handler = await Handlers.GetHandlerAsync(context, scheme);
if (handler == null)
{
throw await CreateMissingHandlerException(scheme);
}

var handler = await Handlers.GetHandlerAsync(context, scheme) ?? throw await CreateMissingHandlerException(scheme);
await handler.ForbidAsync(properties);
}

Expand Down Expand Up @@ -187,14 +178,8 @@ public virtual async Task SignInAsync(HttpContext context, string? scheme, Claim
}
}

var handler = await Handlers.GetHandlerAsync(context, scheme);
if (handler == null)
{
throw await CreateMissingSignInHandlerException(scheme);
}

var signInHandler = handler as IAuthenticationSignInHandler;
if (signInHandler == null)
var handler = await Handlers.GetHandlerAsync(context, scheme) ?? throw await CreateMissingSignInHandlerException(scheme);
if (handler is not IAuthenticationSignInHandler signInHandler)
{
throw await CreateMismatchedSignInHandlerException(scheme, handler);
}
Expand All @@ -221,14 +206,8 @@ public virtual async Task SignOutAsync(HttpContext context, string? scheme, Auth
}
}

var handler = await Handlers.GetHandlerAsync(context, scheme);
if (handler == null)
{
throw await CreateMissingSignOutHandlerException(scheme);
}

var signOutHandler = handler as IAuthenticationSignOutHandler;
if (signOutHandler == null)
var handler = await Handlers.GetHandlerAsync(context, scheme) ?? throw await CreateMissingSignOutHandlerException(scheme);
if (handler is not IAuthenticationSignOutHandler signOutHandler)
{
throw await CreateMismatchedSignOutHandlerException(scheme, handler);
}
Expand Down
Loading
Loading