diff options
author | Stephen Halter <halter73@gmail.com> | 2021-11-05 23:48:41 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-11-05 23:48:41 +0300 |
commit | b9fcd82fe9d0883e9828864a8e8b2231f469254f (patch) | |
tree | 370c668bf3720a141b47fb9f1d7aa386ab5058b5 /src/Http | |
parent | aa474ee8fe5b4bce91965a87158186423ffbc4d0 (diff) |
Improve exception messages for missing auth services (#38045)
Diffstat (limited to 'src/Http')
5 files changed, 149 insertions, 24 deletions
diff --git a/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs b/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs index e9d09e7e9d..5e6f4c8519 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Security.Claims; -using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication.Abstractions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -29,7 +29,7 @@ namespace Microsoft.AspNetCore.Authentication /// <param name="scheme">The name of the authentication scheme.</param> /// <returns>The <see cref="AuthenticateResult"/>.</returns> public static Task<AuthenticateResult> AuthenticateAsync(this HttpContext context, string? scheme) => - context.RequestServices.GetRequiredService<IAuthenticationService>().AuthenticateAsync(context, scheme); + GetAuthenticationService(context).AuthenticateAsync(context, scheme); /// <summary> /// Challenge the current request using the specified scheme. @@ -71,7 +71,7 @@ namespace Microsoft.AspNetCore.Authentication /// <param name="properties">The <see cref="AuthenticationProperties"/> properties.</param> /// <returns>The task.</returns> public static Task ChallengeAsync(this HttpContext context, string? scheme, AuthenticationProperties? properties) => - context.RequestServices.GetRequiredService<IAuthenticationService>().ChallengeAsync(context, scheme, properties); + GetAuthenticationService(context).ChallengeAsync(context, scheme, properties); /// <summary> /// Forbid the current request using the specified scheme. @@ -113,7 +113,7 @@ namespace Microsoft.AspNetCore.Authentication /// <param name="properties">The <see cref="AuthenticationProperties"/> properties.</param> /// <returns>The task.</returns> public static Task ForbidAsync(this HttpContext context, string? scheme, AuthenticationProperties? properties) => - context.RequestServices.GetRequiredService<IAuthenticationService>().ForbidAsync(context, scheme, properties); + GetAuthenticationService(context).ForbidAsync(context, scheme, properties); /// <summary> /// Sign in a principal for the specified scheme. @@ -155,7 +155,7 @@ namespace Microsoft.AspNetCore.Authentication /// <param name="properties">The <see cref="AuthenticationProperties"/> properties.</param> /// <returns>The task.</returns> public static Task SignInAsync(this HttpContext context, string? scheme, ClaimsPrincipal principal, AuthenticationProperties? properties) => - context.RequestServices.GetRequiredService<IAuthenticationService>().SignInAsync(context, scheme, principal, properties); + GetAuthenticationService(context).SignInAsync(context, scheme, principal, properties); /// <summary> /// Sign out a principal for the default authentication scheme. @@ -190,7 +190,7 @@ namespace Microsoft.AspNetCore.Authentication /// <param name="properties">The <see cref="AuthenticationProperties"/> properties.</param> /// <returns>The task.</returns> public static Task SignOutAsync(this HttpContext context, string? scheme, AuthenticationProperties? properties) => - context.RequestServices.GetRequiredService<IAuthenticationService>().SignOutAsync(context, scheme, properties); + GetAuthenticationService(context).SignOutAsync(context, scheme, properties); /// <summary> /// Authenticates the request using the specified scheme and returns the value for the token. @@ -200,7 +200,7 @@ namespace Microsoft.AspNetCore.Authentication /// <param name="tokenName">The name of the token.</param> /// <returns>The value of the token if present.</returns> public static Task<string?> GetTokenAsync(this HttpContext context, string? scheme, string tokenName) => - context.RequestServices.GetRequiredService<IAuthenticationService>().GetTokenAsync(context, scheme, tokenName); + GetAuthenticationService(context).GetTokenAsync(context, scheme, tokenName); /// <summary> /// Authenticates the request using the default authentication scheme and returns the value for the token. @@ -210,6 +210,14 @@ namespace Microsoft.AspNetCore.Authentication /// <param name="tokenName">The name of the token.</param> /// <returns>The value of the token if present.</returns> public static Task<string?> GetTokenAsync(this HttpContext context, string tokenName) => - context.RequestServices.GetRequiredService<IAuthenticationService>().GetTokenAsync(context, tokenName); + GetAuthenticationService(context).GetTokenAsync(context, tokenName); + + // This project doesn't reference AuthenticationServiceCollectionExtensions.AddAuthentication so we use a string. + private static IAuthenticationService GetAuthenticationService(HttpContext context) => + context.RequestServices.GetService<IAuthenticationService>() ?? + throw new InvalidOperationException(Resources.FormatException_UnableToFindServices( + nameof(IAuthenticationService), + nameof(IServiceCollection), + "AddAuthentication")); } } diff --git a/src/Http/Authentication.Abstractions/src/Resources.resx b/src/Http/Authentication.Abstractions/src/Resources.resx new file mode 100644 index 0000000000..5952d96b44 --- /dev/null +++ b/src/Http/Authentication.Abstractions/src/Resources.resx @@ -0,0 +1,123 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <data name="Exception_UnableToFindServices" xml:space="preserve"> + <value>Unable to find the required '{0}' service. Please add all the required services by calling '{1}.{2}' in the application startup code.</value> + </data> +</root>
\ No newline at end of file diff --git a/src/Http/Routing/src/EndpointMiddleware.cs b/src/Http/Routing/src/EndpointMiddleware.cs index 08e5bb1db7..41919ff00c 100644 --- a/src/Http/Routing/src/EndpointMiddleware.cs +++ b/src/Http/Routing/src/EndpointMiddleware.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Http; @@ -90,7 +88,7 @@ namespace Microsoft.AspNetCore.Routing throw new InvalidOperationException($"Endpoint {endpoint.DisplayName} contains authorization metadata, " + "but a middleware was not found that supports authorization." + Environment.NewLine + - "Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...)."); + "Configure your application startup by adding app.UseAuthorization() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAuthorization() must go between them."); } private static void ThrowMissingCorsMiddlewareException(Endpoint endpoint) @@ -98,7 +96,7 @@ namespace Microsoft.AspNetCore.Routing throw new InvalidOperationException($"Endpoint {endpoint.DisplayName} contains CORS metadata, " + "but a middleware was not found that supports CORS." + Environment.NewLine + - "Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. The call to app.UseCors() must appear between app.UseRouting() and app.UseEndpoints(...)."); + "Configure your application startup by adding app.UseCors() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseCors() must go between them."); } private static partial class Log diff --git a/src/Http/Routing/test/FunctionalTests/EndpointRoutingIntegrationTest.cs b/src/Http/Routing/test/FunctionalTests/EndpointRoutingIntegrationTest.cs index 9a1f826734..0d6f2f4fa7 100644 --- a/src/Http/Routing/test/FunctionalTests/EndpointRoutingIntegrationTest.cs +++ b/src/Http/Routing/test/FunctionalTests/EndpointRoutingIntegrationTest.cs @@ -20,13 +20,13 @@ namespace Microsoft.AspNetCore.Routing.FunctionalTests private static readonly RequestDelegate TestDelegate = async context => await Task.Yield(); private static readonly string AuthErrorMessage = "Endpoint / contains authorization metadata, but a middleware was not found that supports authorization." + Environment.NewLine + - "Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. " + - "The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...)."; + "Configure your application startup by adding app.UseAuthorization() in the application startup code. " + + "If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAuthorization() must go between them."; private static readonly string CORSErrorMessage = "Endpoint / contains CORS metadata, but a middleware was not found that supports CORS." + Environment.NewLine + - "Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. " + - "The call to app.UseCors() must appear between app.UseRouting() and app.UseEndpoints(...)."; + "Configure your application startup by adding app.UseCors() in the application startup code. " + + "If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseCors() must go between them."; [Fact] public async Task AuthorizationMiddleware_WhenNoAuthMetadataIsConfigured() diff --git a/src/Http/Routing/test/UnitTests/EndpointMiddlewareTest.cs b/src/Http/Routing/test/UnitTests/EndpointMiddlewareTest.cs index 5bdef13fe5..2f6482ec71 100644 --- a/src/Http/Routing/test/UnitTests/EndpointMiddlewareTest.cs +++ b/src/Http/Routing/test/UnitTests/EndpointMiddlewareTest.cs @@ -1,16 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; -using Xunit; namespace Microsoft.AspNetCore.Routing { @@ -101,8 +97,8 @@ namespace Microsoft.AspNetCore.Routing // Arrange var expected = "Endpoint Test contains authorization metadata, but a middleware was not found that supports authorization." + Environment.NewLine + - "Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. " + - "The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...)."; + "Configure your application startup by adding app.UseAuthorization() in the application startup code. " + + "If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAuthorization() must go between them."; var httpContext = new DefaultHttpContext { RequestServices = new ServiceProvider() @@ -198,8 +194,8 @@ namespace Microsoft.AspNetCore.Routing // Arrange var expected = "Endpoint Test contains CORS metadata, but a middleware was not found that supports CORS." + Environment.NewLine + - "Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. " + - "The call to app.UseCors() must appear between app.UseRouting() and app.UseEndpoints(...)."; + "Configure your application startup by adding app.UseCors() in the application startup code. " + + "If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseCors() must go between them."; var httpContext = new DefaultHttpContext { RequestServices = new ServiceProvider() |