c# - 从程序集 Microsoft.IdentityModel.Protocols 派生的方法 'GetBaseConfigurationAsync' 无法减少访问

标签 c# .net azure azure-ad-b2c openid-connect

我正在尝试将 Azure Active Directory B2C 登录添加到旧应用程序。旧版应用程序当前使用 IdentityServer3并在 .NET 4.7.2 上运行。遗憾的是,我无法将代码放在公共(public)存储库上,因此复制此问题可能很困难。但如有任何帮助,我们将不胜感激!

我正在使用this sample添加 B2C 登录功能。我还没有创建 API,因为我只想先让登录正常工作。 我将示例中的以下内容添加到旧应用程序中。

启动时出现以下错误。

程序集“Microsoft.IdentityModel.Protocols,Version=6.14.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35”的类型“Microsoft.IdentityModel.Protocols.ConfigurationManager`1”中的派生方法“GetBaseConfigurationAsync”无法减少访问。

使用堆栈跟踪:

[TypeLoadException: Derived method 'GetBaseConfigurationAsync' in type 'Microsoft.IdentityModel.Protocols.ConfigurationManager`1' from assembly 'Microsoft.IdentityModel.Protocols, Version=6.14.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' cannot reduce access.]
   Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationMiddleware..ctor(OwinMiddleware next, IAppBuilder app, OpenIdConnectAuthenticationOptions options) +0
   lambda_method(Closure , OwinMiddleware , IAppBuilder , OpenIdConnectAuthenticationOptions ) +93

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +132
   System.Delegate.DynamicInvokeImpl(Object[] args) +160
   Microsoft.Owin.Builder.AppBuilder.BuildInternal(Type signature) +321
   Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +789
   Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +51
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +101
   System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +139
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +160
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +587
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +255
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +347

[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +552
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +122
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +737 

Web.config 包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral />
  </configSections>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <connectionStrings>
    <add name="Default" connectionString="Data Source=redacted" providerName="System.Data.SqlClient" />
    <add name="Log" connectionString="Data Source=redacted" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
  <add key="AppName" value="redacted" />
  <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    
    
    
    
    
    <!--AAD B2C Settings-->
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ida:Tenant" value="redacted.onmicrosoft.com" />
    <!--MSAL cache needs a tenantId along with the user's objectId to function. It retrieves these two from the claims returned in the id_token. 
        As tenantId is not guaranteed to be present in id_tokens issued by B2C unless the steps listed in this 
        document (https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/AAD-B2C-specifics#caching-with-b2c-in-msalnet). 
        If you are following the workarounds listed in the doc and tenantId claim (tid) is available in the user's token, then please change the 
        code in <ClaimsPrincipalsExtension.cs GetB2CMsalAccountId()> to let MSAL pick this from the claims instead -->
    <add key="ida:TenantId" value="redacted" />
    <add key="ida:ClientId" value="redacted" />
    <add key="ida:ClientSecret" value="redacted SFcv" />
    <add key="ida:AadInstance" value="https://redacted.b2clogin.com/tfp/{0}/{1}" />
    <add key="ida:RedirectUri" value="https://localhost:52969/" />
    <add key="ida:SignUpSignInPolicyId" value="b2c_1_normalsignin" />
    <add key="ida:EditProfilePolicyId" value="b2c_1_editprofile" />
    <add key="ida:ResetPasswordPolicyId" value="b2c_1_resetpw" />
    <add key="api:TaskServiceUrl" value="https://localhost:44332/" />
    <!-- The following settings is used for requesting access tokens -->
    <add key="api:ApiIdentifier" value="https://redacted.onmicrosoft.com/tasks-api" />
    <add key="api:ReadScope" value="read" />
    <add key="api:WriteScope" value="write" />
    
  </appSettings>
  <system.web>
    <httpCookies domain="" httpOnlyCookies="true" requireSSL="false" />
    <machineKey validationKey="redacted" decryptionKey="redacted" validation="redacted" decryption="redacted" />
    <xhtmlConformance mode="Strict" />
    <httpRuntime maxRequestLength="1048576" targetFramework="4.7.2" requestValidationMode="2.0" executionTimeout="600" enableVersionHeader="false" />
    <compilation debug="true" targetFramework="4.7.2" batch="false">
      <assemblies>
        <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" />
      </assemblies>
    </compilation>
    <customErrors mode="Off" />
    <pages maintainScrollPositionOnPostBack="true" controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID" enableEventValidation="false" validateRequest="false">
      <namespaces>
        <add namespace="Tools" />
        <add namespace="System.Web.Optimization" />
      </namespaces>
    </pages>
    <authentication mode="Windows" />
  </system.web>
  <system.web.extensions>
    <scripting>
      <scriptResourceHandler enableCompression="true" enableCaching="true" />
      <webServices>
        <jsonSerialization maxJsonLength="50000000" />
      </webServices>
    </scripting>
  </system.web.extensions>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" maxQueryString="332768" />
      </requestFiltering>
    </security>
    <handlers>
      <!-- only for debugging -->
      <add name="Browser Link for HTML" path="*.html" verb="*" type="System.Web.StaticFileHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" resourceType="File" preCondition="integratedMode" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web" preCondition="managedHandler" />
      <add name="PropertyInjection" type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web" preCondition="managedHandler" />
    </modules>
    <httpErrors>
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" prefixLanguageFilePath="" path="~/NotFound.htm" responseMode="ExecuteURL" />
    </httpErrors>
    <staticContent>
      <remove fileExtension=".mp4" />
      <mimeMap fileExtension=".mp4" mimeType="video/mpeg" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/x-woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="application/x-woff" />
      <remove fileExtension=".apk" />
      <mimeMap fileExtension=".apk" mimeType="application/apk" />
    </staticContent>
    <httpProtocol>
      <!--see https://blog.insiderattack.net/configuring-secure-iis-response-headers-in-asp-net-mvc-b38369030728-->
      <customHeaders>
        <remove name="X-Powered-By" />
        <!--<add name="Content-Security-Policy-Report-Only" value="default-src 'self'; report-uri /test/ContentSecurityPolicy/CspReport" />-->
        <add name="X-XSS-Protection" value="1; mode=block" />
        <add name="X-Content-Type-Options" value="nosniff" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocol.Extensions" publicKeyToken="31BF3856AD364E35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.0.40306.1554" newVersion="1.0.40306.1554" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.3.0.0" newVersion="6.3.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="MiniProfiler" publicKeyToken="b44f9351044011a3" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.15.1.0" newVersion="6.15.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="AngleSharp.Css" publicKeyToken="e83494dcdc6d31ea" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-0.16.1.0" newVersion="0.16.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocol.Extensions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.0.40306.1554" newVersion="1.0.40306.1554" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="AngleSharp" publicKeyToken="e83494dcdc6d31ea" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-0.16.1.0" newVersion="0.16.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.1" newVersion="6.0.0.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Logging" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.15.1.0" newVersion="6.15.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Tokens" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.15.1.0" newVersion="6.15.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocols" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.14.0.0" newVersion="6.14.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Xml" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.14.0.0" newVersion="6.14.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocols.OpenIdConnect" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.14.0.0" newVersion="6.14.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Identity.Client" publicKeyToken="0a613f4dd989e8ae" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.42.0.0" newVersion="4.42.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <basicHttpBinding>
        <binding name="redacted" closeTimeout="00:02:00" openTimeout="00:02:00" receiveTimeout="00:10:00" sendTimeout="00:02:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
        <binding name="redacted" closeTimeout="00:02:00" openTimeout="00:02:00" receiveTimeout="00:15:00" sendTimeout="00:02:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
        <binding name="redacted" closeTimeout="00:02:00" openTimeout="00:02:00" receiveTimeout="00:10:00" sendTimeout="00:02:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="Transport" />
        </binding>
        <binding name="redacted" closeTimeout="00:02:00" openTimeout="00:02:00" receiveTimeout="00:15:00" sendTimeout="00:02:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="Transport" />
        </binding>
        <binding name="redacted">
          <security mode="Transport">
            <transport clientCredentialType="Basic" />
          </security>
        </binding>
        <binding name="redacted" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2516384" maxBytesPerRead="4096" maxNameTableCharCount="2516384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
        <binding name="redacted" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2516384" maxBytesPerRead="4096" maxNameTableCharCount="2516384" />
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
        <binding name="redacted" maxReceivedMessageSize="11125536">
          <readerQuotas maxNameTableCharCount="1216384" />
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint binding="basicHttpBinding" bindingConfiguration="redacted" contract="redacted.redacted" name="redacted" />
redacted
    </client>
  </system.serviceModel>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler extension=".cs" language="c#;cs;csharp" warningLevel="4" compilerOptions="/langversion:7.3 /nowarn:1659;1699;1701;612;618" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=3.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <compiler extension=".vb" language="vb;vbs;visualbasic;vbscript" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008,40000,40008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=3.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </compilers>
  </system.codedom>
</configuration>


添加的所有其他文件与示例中给出的相同。我还将在下面添加 Startup.Auth.cs,因为它是在错误发生之前实际使用的唯一一个。

using System;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Identity.Client;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Host.SystemWeb;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Notifications;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using Redacted.Utils;
using System.Web;

namespace Redacted.App_Start
{
    public partial class Startup
    {
        /*
       * Configure the OWIN middleware
       */

        public void ConfigureAuthB2C(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                // ASP.NET web host compatible cookie manager
                CookieManager = new SystemWebChunkingCookieManager()
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Generate the metadata address using the tenant and policy information
                    MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.Tenant, Globals.DefaultPolicy),

                    RequireHttpsMetadata = false,

                    // These are standard OpenID Connect parameters, with values pulled from web.config
                    ClientId = Globals.ClientId,
                    RedirectUri = Globals.RedirectUri,
                    PostLogoutRedirectUri = Globals.RedirectUri,

                    // Specify the callbacks for each type of notifications
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                        AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                        AuthenticationFailed = OnAuthenticationFailed,
                    },

                    // Specify the claim type that specifies the Name property.
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = "name",
                        ValidateIssuer = false
                    },

                    // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
                    Scope = $"openid profile offline_access {Globals.ReadTasksScope} {Globals.WriteTasksScope}",

                    // ASP.NET web host compatible cookie manager
                    CookieManager = new SystemWebCookieManager()
                }
            );
        }

        /*
         *  On each call to Azure AD B2C, check if a policy (e.g. the profile edit or password reset policy) has been specified in the OWIN context.
         *  If so, use that policy when making the call. Also, don't request a code (since it won't be needed).
         */
        private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            var policy = notification.OwinContext.Get<string>("Policy");

            if (!string.IsNullOrEmpty(policy) && !policy.Equals(Globals.DefaultPolicy))
            {
                notification.ProtocolMessage.Scope = OpenIdConnectScope.OpenId;
                notification.ProtocolMessage.ResponseType = OpenIdConnectResponseType.IdToken;
                notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.ToLower().Replace(Globals.DefaultPolicy.ToLower(), policy.ToLower());
            }

            return Task.FromResult(0);
        }

        /*
         * Catch any failures received by the authentication middleware and handle appropriately
         */
        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            Empty for limited characters on Stackoverflow
        }

        /*
         * Callback function when an authorization code is received
         */
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            Empty for limited characters on Stackoverflow
        }
    }
}

最佳答案

我安装了以下软件包:

  • Microsoft.IdentityModel.Protocols 6.14.0.0
  • Microsoft.IdentityModel.Protocols.OpenIdConnect 6.14.0.0
  • Microsoft.IdentityModel.Tokens 6.15.1.0
  • Microsoft.IdentityModel.Logging 6.15.1.0

并非所有软件包都使用相同的版本。 token 和日志记录的版本都高于协议(protocol)和 OpenIdConnect。通常这应该没问题,但是一旦我将它们全部更新为使用 6.15.1,错误就消失了。

关于c# - 从程序集 Microsoft.IdentityModel.Protocols 派生的方法 'GetBaseConfigurationAsync' 无法减少访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71782519/

相关文章:

c# - 关键字 'this' (Me) 在调用基本构造函数时不可用

linux - 在 Azure 中部署的 RHEL 7.2 中无法使用 Gnome 查看 GUI

c# - 在 SQL Server(C# 客户端)中批量插入大量数据的最快方法是什么

c# - XmlWriter.WriteCData 引发 ArgumentException - 无效字符

c# - Entity Framework 错误 : An object with a null EntityKey value cannot be attached to an object context

c# - 我应该在 C# 中选择哪个通用集合来维护排序的 "list"

c# - 如何在不使用计时器的情况下在 Windows 服务中循环

c# - .net core 5 中具有参数依赖关系的全局过滤器

asp.net-mvc-3 - 从 Azure 中的辅助角色部署 Web 角色

azure - 在 Azure Devops CI/CD 管道中为 MS Edge 浏览器运行 Protractor E2E 测试