c# - Azure B2c 登录未连接到帐户 Controller

标签 c# asp.net-core razor azure-active-directory azure-ad-b2c

我有一个使用 Azure B2C 的 Razor 应用程序,我已经开发了一段时间了。登录按钮没有用,所以我使用默认向导创建了一个新应用程序,如果我在 Azure 应用程序中更改本地主机,该应用程序就可以正常工作。我试图找出这两个应用程序之间的区别。

它们都有相同的 _LoginPartial.cshtml 文件和相同的登录按钮布局文件设置,但不起作用的那个没有 href 数据来调用帐户。当我查看 f12 调试器时,登录链接呈现如下:<a class="nav-link text-dark" href>Sign in</a> 可用的应用程序将其呈现为:<a class="nav-link text-dark" href="/AzureADB2C/Account/SignIn">Sign in</a>这显然要好得多。

两者都通过 nuget 包运行 Microsoft.AspNetCore.Authentication.AzureADB2C.UI。

损坏的应用程序显然还有很多新应用程序没有的东西,telerik、azure 存储、sql、 Entity Framework 等,但围绕登录的配置等一切看起来都一样。我在下面包含了损坏版本的启动等,以防有帮助。任何人都可以发现问题吗?

登录部分:

@using Microsoft.AspNetCore.Authentication.AzureADB2C.UI
@using Microsoft.Extensions.Options
@inject IOptionsMonitor<AzureADB2COptions> AzureADB2COptions

@{
    var options = AzureADB2COptions.Get(AzureADB2CDefaults.AuthenticationScheme);
}


<ul class="navbar-nav">
@if (User.Identity.IsAuthenticated)
{
        @if (!string.IsNullOrEmpty(options.EditProfilePolicyId))
        {
            <li class="nav-item">
                <a class="nav-link text-dark" asp-area="AzureADB2C" asp-controller="Account" asp-action="EditProfile">
                    <span class="text-dark">Hello @User.Identity.Name!</span>
                </a>
            </li>
        }
        else
        {
            <li class="nav-item">
                <span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
            </li>
        }
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="AzureADB2C" asp-controller="Account" asp-action="SignOut">Sign out</a>
        </li>
}
else
{
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="AzureADB2C" asp-controller="Account" asp-action="SignIn">Sign in</a>
        </li>
}
</ul>

启动设置

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:50209",
      "sslPort": 44370
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "FliveRetry": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

应用设置

{
  "AzureAdB2C": {
    "Instance": "https://xxxx.b2clogin.com/tfp/",
    "ClientId": "xxxx-xx-xx-xx-xx",
    "CallbackPath": "/signin-oidc",
    "Domain": "xxxx.onmicrosoft.com",
    "SignUpSignInPolicyId": "B2C_1_signupsignin",
    "ResetPasswordPolicyId": "B2C_1_resetpassword",
    "EditProfilePolicyId": "B2C_1_editprofile"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "FliveRetryContext": "Server=(localdb)\\mssqllocaldb;Database=xxxx-566cf99c-25d6-42a3-9260-5626bc8829b2;Trusted_Connection=True;MultipleActiveResultSets=true",

  }
}

启动.cs

using System;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using System.Globalization;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using FliveRetry.Models;
using FliveRetry.Models.PTs;
using FliveRetry.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.HttpsPolicy;


namespace FliveRetry
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();

            services.Configure<CookiePolicyOptions>(options =>
            {                
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
                options.Cookie.Name = ".Flive";
            });
            services.AddMemoryCache();
            services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
                .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));
            services.AddRazorPages().AddNewtonsoftJson
                    (options => {
                        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                    });

            services.AddDbContext<FliveRetryContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("xxxxx")));


            services.AddRazorPages();
            services.AddMvc()
                .AddNewtonsoftJson(options =>
                       options.SerializerSettings.ContractResolver =
                          new DefaultContractResolver());
            services.AddMvc();
            services.AddMvc().AddRazorRuntimeCompilation();

            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

            services.AddScoped<IPtNoteRepository, PtNoteRepository>();
            //services.AddSingleton<PtNoteRepository>();

            // Add Kendo UI services to the services container
            services.AddKendo();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var supportedCultures = new[] { new CultureInfo("en-AU") };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-AU"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            });
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");

                app.UseHsts();
            }
            app.UseHttpsRedirection();
            //app.UseHttpContextItemsMiddleware();

            app.UseRouting();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });

            app.UseStaticFiles();

            app.UseSession();

        }
    }
}

最佳答案

Microsoft.AspNetCore.Authentication.AzureADB2C.UI Nuget 包似乎已被标记为过时,Microsoft 建议开始使用 Microsoft.Identity.Web而是打包。

https://learn.microsoft.com/en-us/dotnet/core/compatibility/aspnetcore#authentication-azureadui-and-azureadb2cui-apis-and-packages-marked-obsolete

我的内置 Controller (例如/AzureADB2C/Account/SignIn)在 .NET Core 2.2 网络应用程序上运行,但一旦我升级到 3.1,它们就停止工作(404 错误)。

解决方案是删除所有对 Microsoft.AspNetCore.Authentication.AzureADB2C.UI 的引用并替换为 Microsoft.Identity.Web.UI 包。

然后您必须更改 Razor 页面中的以下实例:

asp-area="AzureADB2C"

与:

asp-area="MicrosoftIdentity"

如果您想要引用设置,请查看此示例: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/1-WebApp-OIDC/1-5-B2C

关于c# - Azure B2c 登录未连接到帐户 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61495102/

相关文章:

c# - 在 VS2008 中用花括号 {} 包围代码块的任何方法?

asp.net-core - 使用空路由指定可选格式扩展名

docker - 使用 Nginx 反向代理时无法获取客户端的真实 IP

c# - Azure KeyVault - 签署 JWT token

c# - 在 ASP.net 中通过 Razor 输出电子邮件的语法

javascript - jquery 自动完成 - 字符串数组

c# - 如何用c#中的一些特殊字符替换字符串中的多个空格

c# - 如何在网页上搜索一些文字?

c# - 过于复杂的工厂方法 - 任何解决方案?

jquery - 如何使用通过模型列表发送的数据在 javascript 中填充数组