Azure B2C身份验证屏幕未显示

发布于 2025-02-13 20:17:17 字数 3409 浏览 0 评论 0 原文

我有一个用vb.net编写的ASP.NET 4.7 WebForms旧应用程序。我需要添加Azure B2C身份验证。因此,我用Azure注册了一个应用程序,并添加了OWIN中间件Nuget软件包,并进行了所有必要的配置更改。我希望在应用程序运行时会看到屏幕上的登录屏幕,但没有发生。该应用程序仅在没有任何身份验证的情况下运行。我想念什么?

这是代码:

startup.vb:

Imports System.Threading.Tasks
Imports Microsoft.IdentityModel.Protocols.OpenIdConnect
Imports Microsoft.IdentityModel.Tokens
Imports Microsoft.Owin
Imports Microsoft.Owin.Security
Imports Microsoft.Owin.Security.Cookies
Imports Microsoft.Owin.Security.Notifications
Imports Microsoft.Owin.Security.OpenIdConnect
Imports Owin

<Assembly: OwinStartup(GetType(InfoWebCore.Startup))>
Namespace InfoWebCore
Public Class Startup
    Private Shared clientId As String = ConfigurationManager.AppSettings("ida:ClientId")
    Private Shared aadInstance As String = ConfigurationManager.AppSettings("ida:AadInstance")
    Private Shared tenant As String = ConfigurationManager.AppSettings("ida:Tenant")
    Private Shared redirectUri As String = ConfigurationManager.AppSettings("ida:RedirectUri")
    Public Shared SignInPolicyId As String = ConfigurationManager.AppSettings("ida:SignInPolicyId")

    Public Sub Configuration(ByVal app As IAppBuilder)
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
        app.UseCookieAuthentication(New CookieAuthenticationOptions())
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId))
    End Sub

    Private Function AuthenticationFailed(ByVal notification As AuthenticationFailedNotification(Of OpenIdConnectMessage, OpenIdConnectAuthenticationOptions)) As Task
        notification.HandleResponse()

        If notification.Exception.Message = "access_denied" Then
            notification.Response.Redirect("/")
        Else
            notification.Response.Redirect("/Home/Error?message=" & notification.Exception.Message)
        End If

        Return Task.FromResult(0)
    End Function

    Private Function CreateOptionsFromPolicy(ByVal policy As String) As OpenIdConnectAuthenticationOptions
        Dim options = New OpenIdConnectAuthenticationOptions With {
            .MetadataAddress = String.Format(aadInstance, tenant, policy),
            .AuthenticationType = policy,
            .ClientId = clientId,
            .RedirectUri = redirectUri,
            .PostLogoutRedirectUri = redirectUri,
            .Notifications = New OpenIdConnectAuthenticationNotifications With {
                .AuthenticationFailed = AddressOf AuthenticationFailed
            },
            .Scope = "openid",
            .ResponseType = "id_token",
            .TokenValidationParameters = New TokenValidationParameters With {
                .NameClaimType = "name"
            }
        }
        Return options
    End Function
End Class
End Namespace

web.config:

<authentication mode="None" />

...

    <!-- Azure AD B2C Settings -->
    <add key="ida:Tenant" value="laticreteb2c.onmicrosoft.com" />
    <add key="ida:ClientId" value="8hq22y21-f12g-4a2d-b170-fdaa0b2dc467" />
    <add key="ida:AadInstance" value="https://login.microsoftonline.com/{0}/v2.0/.well-known/openid-configuration?p={1}" />
    <add key="ida:RedirectUri" value="https://localhost:44379/signin-oidc" />
    <add key="ida:SignInPolicyId" value="B2C_1_signin" />

执行确实是configuration()方法...

I have an Asp.Net 4.7 WebForms legacy application written in vb.net. I need to add Azure B2C authentication. So I registred an app with Azure, and added OWIN middleware NuGet packages, and made all necessary configuration changes. I expect to see the log in screen when the application runs, and yet it does not happen. The application just runs without any authentication. What am I missing?

Here is the code:

Startup.vb:

Imports System.Threading.Tasks
Imports Microsoft.IdentityModel.Protocols.OpenIdConnect
Imports Microsoft.IdentityModel.Tokens
Imports Microsoft.Owin
Imports Microsoft.Owin.Security
Imports Microsoft.Owin.Security.Cookies
Imports Microsoft.Owin.Security.Notifications
Imports Microsoft.Owin.Security.OpenIdConnect
Imports Owin

<Assembly: OwinStartup(GetType(InfoWebCore.Startup))>
Namespace InfoWebCore
Public Class Startup
    Private Shared clientId As String = ConfigurationManager.AppSettings("ida:ClientId")
    Private Shared aadInstance As String = ConfigurationManager.AppSettings("ida:AadInstance")
    Private Shared tenant As String = ConfigurationManager.AppSettings("ida:Tenant")
    Private Shared redirectUri As String = ConfigurationManager.AppSettings("ida:RedirectUri")
    Public Shared SignInPolicyId As String = ConfigurationManager.AppSettings("ida:SignInPolicyId")

    Public Sub Configuration(ByVal app As IAppBuilder)
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
        app.UseCookieAuthentication(New CookieAuthenticationOptions())
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId))
    End Sub

    Private Function AuthenticationFailed(ByVal notification As AuthenticationFailedNotification(Of OpenIdConnectMessage, OpenIdConnectAuthenticationOptions)) As Task
        notification.HandleResponse()

        If notification.Exception.Message = "access_denied" Then
            notification.Response.Redirect("/")
        Else
            notification.Response.Redirect("/Home/Error?message=" & notification.Exception.Message)
        End If

        Return Task.FromResult(0)
    End Function

    Private Function CreateOptionsFromPolicy(ByVal policy As String) As OpenIdConnectAuthenticationOptions
        Dim options = New OpenIdConnectAuthenticationOptions With {
            .MetadataAddress = String.Format(aadInstance, tenant, policy),
            .AuthenticationType = policy,
            .ClientId = clientId,
            .RedirectUri = redirectUri,
            .PostLogoutRedirectUri = redirectUri,
            .Notifications = New OpenIdConnectAuthenticationNotifications With {
                .AuthenticationFailed = AddressOf AuthenticationFailed
            },
            .Scope = "openid",
            .ResponseType = "id_token",
            .TokenValidationParameters = New TokenValidationParameters With {
                .NameClaimType = "name"
            }
        }
        Return options
    End Function
End Class
End Namespace

Web.config:

<authentication mode="None" />

...

    <!-- Azure AD B2C Settings -->
    <add key="ida:Tenant" value="laticreteb2c.onmicrosoft.com" />
    <add key="ida:ClientId" value="8hq22y21-f12g-4a2d-b170-fdaa0b2dc467" />
    <add key="ida:AadInstance" value="https://login.microsoftonline.com/{0}/v2.0/.well-known/openid-configuration?p={1}" />
    <add key="ida:RedirectUri" value="https://localhost:44379/signin-oidc" />
    <add key="ida:SignInPolicyId" value="B2C_1_signin" />

Execution does come to the Configuration() method...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰火雁神 2025-02-20 20:17:17

看起来都不错,请确保您的web.config与此相似:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
   https://go.microsoft.com/fwlink/?LinkId=301880

  -->
<configuration>
  <location path="Account">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <system.web>
    <authorization>
      <deny users="?" />
    </authorization>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Tokens" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocols.OpenIdConnect" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocols" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="ida:ClientId" value="c1874cf1-a4e5-4af1-bd43-b13f59dfbee3" />
    <add key="ida:MetadataAddress" value="https://alfredorevillaatmsftb.b2clogin.com/tfp/alfredorevillaatmsftb.onmicrosoft.com/B2C_1_SI/v2.0/.well-known/openid-configuration" />
    <add key="ida:RedirectUri" value="https://localhost:44321/signin-oidc" />
  </appSettings>
</configuration>

startupauth.vb与:

Imports System.Security.Claims
Imports System.Threading.Tasks
Imports Microsoft.IdentityModel.Protocols.OpenIdConnect
Imports Microsoft.IdentityModel.Tokens
Imports Microsoft.Owin.Extensions
Imports Microsoft.Owin.Security
Imports Microsoft.Owin.Security.Cookies
Imports Microsoft.Owin.Security.OpenIdConnect
Imports Owin

Partial Public Class Startup
    Private Shared clientId As String = ConfigurationManager.AppSettings("ida:ClientId")
    Private Shared aadInstance As String = ConfigurationManager.AppSettings("ida:AadInstance")
    Private Shared tenant As String = ConfigurationManager.AppSettings("ida:Tenant")
    Private Shared redirectUri As String = ConfigurationManager.AppSettings("ida:RedirectUri")
    Public Shared SignInPolicyId As String = ConfigurationManager.AppSettings("ida:SignInPolicyId")

    Public Sub ConfigureAuth(app As IAppBuilder)
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)

        app.UseCookieAuthentication(New CookieAuthenticationOptions())

        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId))

        app.UseStageMarker(PipelineStage.Authenticate)
    End Sub

    Private Function CreateOptionsFromPolicy(ByVal policy As String) As OpenIdConnectAuthenticationOptions
        Dim options = New OpenIdConnectAuthenticationOptions With {
            .MetadataAddress = "https://alfredorevillaatmsftb.b2clogin.com/tfp/alfredorevillaatmsftb.onmicrosoft.com/B2C_1_SI/v2.0/.well-known/openid-configuration",
            .RedirectUri = redirectUri,
            .PostLogoutRedirectUri = redirectUri,
            .ClientId = clientId,
            .Scope = "openid",
            .ResponseType = "id_token"
        }
        Return options
    End Function

    Private Function AuthenticationFailed(ByVal notification As Notifications.AuthenticationFailedNotification(Of OpenIdConnectMessage, OpenIdConnectAuthenticationOptions)) As Task
        notification.HandleResponse()

        If notification.Exception.Message = "access_denied" Then
            notification.Response.Redirect("/")
        Else
            notification.Response.Redirect("/Home/Error?message=" & notification.Exception.Message)
        End If

        Return Task.FromResult(0)
    End Function

    Private Shared Function EnsureTrailingSlash(ByRef value As String) As String
        If (IsNothing(value)) Then
            value = String.Empty
        End If

        If (Not value.EndsWith("/", StringComparison.Ordinal)) Then
            Return value & "/"
        End If

        Return value
    End Function
End Class

另外,很快就会被弃用。请使用

All looks good, please ensure your web.config is similar to this:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
   https://go.microsoft.com/fwlink/?LinkId=301880

  -->
<configuration>
  <location path="Account">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <system.web>
    <authorization>
      <deny users="?" />
    </authorization>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Tokens" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocols.OpenIdConnect" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocols" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="ida:ClientId" value="c1874cf1-a4e5-4af1-bd43-b13f59dfbee3" />
    <add key="ida:MetadataAddress" value="https://alfredorevillaatmsftb.b2clogin.com/tfp/alfredorevillaatmsftb.onmicrosoft.com/B2C_1_SI/v2.0/.well-known/openid-configuration" />
    <add key="ida:RedirectUri" value="https://localhost:44321/signin-oidc" />
  </appSettings>
</configuration>

And your StartupAuth.vb is similar to:

Imports System.Security.Claims
Imports System.Threading.Tasks
Imports Microsoft.IdentityModel.Protocols.OpenIdConnect
Imports Microsoft.IdentityModel.Tokens
Imports Microsoft.Owin.Extensions
Imports Microsoft.Owin.Security
Imports Microsoft.Owin.Security.Cookies
Imports Microsoft.Owin.Security.OpenIdConnect
Imports Owin

Partial Public Class Startup
    Private Shared clientId As String = ConfigurationManager.AppSettings("ida:ClientId")
    Private Shared aadInstance As String = ConfigurationManager.AppSettings("ida:AadInstance")
    Private Shared tenant As String = ConfigurationManager.AppSettings("ida:Tenant")
    Private Shared redirectUri As String = ConfigurationManager.AppSettings("ida:RedirectUri")
    Public Shared SignInPolicyId As String = ConfigurationManager.AppSettings("ida:SignInPolicyId")

    Public Sub ConfigureAuth(app As IAppBuilder)
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)

        app.UseCookieAuthentication(New CookieAuthenticationOptions())

        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId))

        app.UseStageMarker(PipelineStage.Authenticate)
    End Sub

    Private Function CreateOptionsFromPolicy(ByVal policy As String) As OpenIdConnectAuthenticationOptions
        Dim options = New OpenIdConnectAuthenticationOptions With {
            .MetadataAddress = "https://alfredorevillaatmsftb.b2clogin.com/tfp/alfredorevillaatmsftb.onmicrosoft.com/B2C_1_SI/v2.0/.well-known/openid-configuration",
            .RedirectUri = redirectUri,
            .PostLogoutRedirectUri = redirectUri,
            .ClientId = clientId,
            .Scope = "openid",
            .ResponseType = "id_token"
        }
        Return options
    End Function

    Private Function AuthenticationFailed(ByVal notification As Notifications.AuthenticationFailedNotification(Of OpenIdConnectMessage, OpenIdConnectAuthenticationOptions)) As Task
        notification.HandleResponse()

        If notification.Exception.Message = "access_denied" Then
            notification.Response.Redirect("/")
        Else
            notification.Response.Redirect("/Home/Error?message=" & notification.Exception.Message)
        End If

        Return Task.FromResult(0)
    End Function

    Private Shared Function EnsureTrailingSlash(ByRef value As String) As String
        If (IsNothing(value)) Then
            value = String.Empty
        End If

        If (Not value.EndsWith("/", StringComparison.Ordinal)) Then
            Return value & "/"
        End If

        Return value
    End Function
End Class

Also, https://login.microsoftonline.com is going to get deprecated soon. Please use b2login.com as detailed in Set redirect URLs to b2clogin.com for Azure Active Directory B2C.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文