Skip to content
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

Add AuthN/AuthZ metrics #59557

Merged
merged 9 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
204 changes: 204 additions & 0 deletions src/Http/Authentication.Core/src/AuthenticationMetrics.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
// 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 AuthenticatedRequestCompleted(string? scheme, AuthenticateResult? result, Exception? exception, long startTimestamp, long currentTimestamp)
{
if (_authenticatedRequestDuration.Enabled)
{
AuthenticatedRequestCompletedCore(scheme, result, exception, startTimestamp, currentTimestamp);
}
}

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

if (scheme is not null)
{
AddSchemeTag(ref tags, scheme);
}

if (result is not null)
{
tags.Add("aspnetcore.authentication.result", 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.
});
}

if (exception is not null)
{
AddErrorTag(ref tags, exception);
}

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

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

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

if (scheme is not null)
{
AddSchemeTag(ref tags, scheme);
}

if (exception is not null)
{
AddErrorTag(ref tags, exception);
}

_challengeCount.Add(1, tags);
}

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

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

if (scheme is not null)
{
AddSchemeTag(ref tags, scheme);
}

if (exception is not null)
{
AddErrorTag(ref tags, exception);
}

_forbidCount.Add(1, tags);
}

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

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

if (scheme is not null)
{
AddSchemeTag(ref tags, scheme);
}

if (exception is not null)
{
AddErrorTag(ref tags, exception);
}

_signInCount.Add(1, tags);
}

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

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

if (scheme is not null)
{
AddSchemeTag(ref tags, scheme);
}

if (exception is not null)
{
AddErrorTag(ref tags, exception);
}

_signOutCount.Add(1, tags);
}

private static void AddSchemeTag(ref TagList tags, string scheme)
{
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