GFlisch / Arc4u

Apache License 2.0
22 stars 17 forks source link

Added default challenge scheme for JWT #95

Closed vvdb-architecture closed 7 months ago

vvdb-architecture commented 8 months ago

This corrects a bug for services implementing security using a call to AddJwtAuthentication.

Normally, when calling a protected endpoint without bearer token, the service should reply with 401 (Unauthorized).

Instead, you get an exception:

System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
   at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Arc4u.AspNetCore.Middleware.LogGrpcMonitoringTimeElapsedMiddleware.Invoke(HttpContext context) in D:\a\Arc4u\Arc4u\src\Arc4u.Standard.AspNetCore.gRpc\Middleware\LogGrpcMonitoringTimeElapsedMiddleware.cs:line 38
   at Arc4u.AspNetCore.Middleware.GrpcAuthenticationStatusCodeMiddleware.Invoke(HttpContext context) in D:\a\Arc4u\Arc4u\src\Arc4u.Standard.AspNetCore.gRpc\Middleware\GrpcAuthenticationStatusCodeMiddleware.cs:line 19
   at Arc4u.OAuth2.Middleware.LogMonitoringTimeElapsedMiddleware.Invoke(HttpContext context) in D:\a\Arc4u\Arc4u\src\Arc4u.Standard.OAuth2.AspNetCore\Middleware\LogMonitoringTimeElapsedMiddleware.cs:line 38
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

The reason is that there is no default challenge scheme defined, and no behavior for the challenge event.

For services behind an API gateway, this error is never noticed since it's the API gateway that takes care of the security challenge.

For the (admittedly uncommon) use case where we call such a service directly, this pull request will make it reply with the correct status code.