Azure active directory .NET Core 3.1到.NET 5的迁移-Microsoft Identity Web平台停止工作

Azure active directory .NET Core 3.1到.NET 5的迁移-Microsoft Identity Web平台停止工作,azure-active-directory,.net-5,microsoft-identity-platform,Azure Active Directory,.net 5,Microsoft Identity Platform,随着NET 5的正式发布,今晚我从NET Core 3.1迁移到NET 5,一切似乎都进展顺利,直到我尝试运行该应用程序,现在在startup.cs中找到了两条与Microsoft Identity Web平台相关的曲线。这显然是一个瞬间的失败!我将无法启动应用程序或登录Azure广告,直到我有这个固定 将csproj文件修改为NET5后,我转到nuget manager并更新了所有包 我完全不知道从哪里开始讨论这个问题:( 带波形的startup.cs文件的屏幕截图: csproj文件:

随着NET 5的正式发布,今晚我从NET Core 3.1迁移到NET 5,一切似乎都进展顺利,直到我尝试运行该应用程序,现在在startup.cs中找到了两条与Microsoft Identity Web平台相关的曲线。这显然是一个瞬间的失败!我将无法启动应用程序或登录Azure广告,直到我有这个固定

将csproj文件修改为NET5后,我转到nuget manager并更新了所有包

我完全不知道从哪里开始讨论这个问题:(

带波形的startup.cs文件的屏幕截图:

csproj文件:

具有更新包的Nuget Manager:

我注意到,自迁移以来,MS Identity Web的startup.cs文件顶部的包引用现在变灰:

startup.cs文件中的代码:

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

    public IConfiguration Configuration { get; }

    public TokenValidatedContext Context { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Added to original .net core template.
        // ASP.NET Core apps access the HttpContext through the IHttpContextAccessor interface and 
        // its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor 
        // when you need access to the HttpContext inside a service.
        // Example usage - we're using this to retrieve the details of the currrently logged in user in page model actions.
        services.AddHttpContextAccessor();

        // DO NOT DELETE (for now...)
        // This 'Microsoft.AspNetCore.Authentication.AzureAD.UI' library was originally used for Azure Ad authentication 
        // before we implemented the newer Microsoft.Identity.Web and Microsoft.Identity.Web.UI NuGet packages. 
        // Note after implememting the newer library for authetication, we had to modify the _LoginPartial.cshtml file.
        //services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        //    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

        ///////////////////////////////////

        // Add services required for using options.
        // e.g used for calling Graph Api from WebOptions class, from config file.
        services.AddOptions();

        // Sign-in users with the Microsoft identity platform
        services.AddSignIn(Configuration);

        // Token acquisition service based on MSAL.NET
        // and chosen token cache implementation
        services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { GraphScopes.UserRead })
            .AddInMemoryTokenCaches();

        // Add the MS Graph SDK Client as a service for Dependancy Injection.
        services.AddGraphService(Configuration);

        // Create a new instance of the class that stores the methods called
        // by OpenIdConnectEvents(); i.e. when a user logs in or out the app.
        // See section below :- 'services.Configure'
        OpenIdEvents openIdEvents = new OpenIdEvents();

        // The following lines code instruct the asp.net core middleware to use the data in the "roles" claim in the Authorize attribute and User.IsInrole()
        // See https://docs.microsoft.com/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 for more info.
        
        services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
        {
            // The claim in the Jwt token where App roles are available.
            options.TokenValidationParameters.RoleClaimType = "roles";
            // Advanced config - capturing user events. See OpenIdEvents class.
            options.Events ??= new OpenIdConnectEvents();
            options.Events.OnTokenValidated += openIdEvents.OnTokenValidatedFunc;
            // This is event is fired when the user is redirected to the MS Signout Page (before they've physically signed out)
            options.Events.OnRedirectToIdentityProviderForSignOut += openIdEvents.OnRedirectToIdentityProviderForSignOutFunc;
            // DO NOT DELETE - May use in the future.
            // OnSignedOutCallbackRedirect doesn't produce any user claims to read from for the user after they have signed out.
            options.Events.OnSignedOutCallbackRedirect += openIdEvents.OnSignedOutCallbackRedirectFunc;
        });

        // Adding authorization policies that enforce authorization using Azure AD roles. Polices defined in seperate classes.
        services.AddAuthorization(options =>
        {
            // This line may not work for razor at all, havent tried it but what was used in MVC from the MS Project example. Dont delete just yet...
            //options.AddPolicy(AuthorizationPolicies.AssignmentToUserReaderRoleRequired, policy => policy.RequireRole(AppRole.UserReaders));

            // NOTE BELOW - I had to change the syntax from RequireRole to RequireClaim
            options.AddPolicy(AuthorizationPolicies.AssignmentToEditRolesRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.EditRoles));
            options.AddPolicy(AuthorizationPolicies.AssignmentToViewLogsRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.ViewLogs));
            options.AddPolicy(AuthorizationPolicies.AssignmentToViewUsersRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.ViewUsers));
            options.AddPolicy(AuthorizationPolicies.AssignmentToCreateUsersRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.CreateUsers));
            options.AddPolicy(AuthorizationPolicies.AssignmentToEditUsersRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.EditUsers));
            options.AddPolicy(AuthorizationPolicies.AssignmentToDeleteUsersRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.DeleteUsers));
        });

        services.AddRazorPages().AddMvcOptions(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        }).AddMicrosoftIdentityUI();

        // Add the HttpClient factory into our dependancy injection system.
        // That way we can access it at any point.
        // Used for consuming REST Api throughout the Webb App.
        services.AddHttpClient();
        // Adds the service for creating the Jwt Token used for calling microservices.
        // Note we are using our independant bearer token issuer service here, NOT Azure AD
        services.AddScoped<JwtService>();
        // Add service for HttpContext Current User Repository.
        // Used fir fetching properties of the currently logged in user for logging.
        services.AddScoped<ICurrentUser, CurrentUser>();

        // The AddAntiforgery() method configures anti-forgery service to pick the anti-forgery 
        // token from request headers rather than request body. This is required because we will 
        // be issuing Ajax requests to the razor page and there won't be any full page post-backs.
        services.AddAntiforgery(options => options.HeaderName = "MY-XSRF-TOKEN");
    }
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
公共TokenValidatedContext上下文{get;set;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
//添加到原始.net核心模板。
//ASP.NET核心应用程序通过IHttpContextAccessor接口和
//它的默认实现HttpContextAccessor。只需要使用IHttpContextAccessor
//当您需要访问服务中的HttpContext时。
//用法示例-我们使用它在页面模型操作中检索当前登录用户的详细信息。
AddHttpContextAccessor();
//不要删除(暂时…)
//此“Microsoft.AspNetCore.Authentication.AzureAD.UI”库最初用于Azure Ad身份验证
//在我们实施较新的Microsoft.Identity.Web和Microsoft.Identity.Web.UI NuGet软件包之前。
//注意:在实现较新的库进行身份验证后,我们必须修改_LoginPartial.cshtml文件。
//services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
//.AddAzureAD(options=>Configuration.Bind(“AzureAd”,options));
///////////////////////////////////
//添加使用选项所需的服务。
//例如,用于从WebOptions类、配置文件调用图形Api。
services.AddOptions();
//使用Microsoft identity platform登录用户
服务。AddSignIn(配置);
//基于MSAL.NET的令牌获取服务
//并选择令牌缓存实现
services.AddWebAppCallsProtectedWebApi(配置,新字符串[]{GraphScopes.UserRead})
.AddInMemoryTokenCaches();
//将MS Graph SDK客户端添加为依赖性注入的服务。
服务。AddGraphService(配置);
//创建存储调用的方法的类的新实例
//通过OpenIdConnectEvents();即当用户登录或退出应用程序时。
//请参阅下面的部分:-“服务.配置”
OpenIdEvents OpenIdEvents=新的OpenIdEvents();
//下面几行代码指示asp.net核心中间件使用Authorize属性和User.IsInrole()中“roles”声明中的数据
//看https://docs.microsoft.com/aspnet/core/security/authorization/roles?view=aspnetcore-2.2了解更多信息。
配置(OpenIdConnectDefaults.AuthenticationScheme,选项=>
{
//Jwt令牌中应用程序角色可用的声明。
options.TokenValidationParameters.RoleClaimType=“角色”;
//高级配置-捕获用户事件。请参阅OpenIdeEvents类。
options.Events???=新的OpenIdConnectEvents();
options.Events.OnTokenValidated+=openIdEvents.OnTokenValidatedFunc;
//当用户重定向到MS注销页面时(在他们实际注销之前),会触发此事件
options.Events.OnRedirectToIdentityProviderForSignOut+=OpenIdeEvents.onRedirectToIdentityProviderForSignOutUNC;
//请勿删除-可能在将来使用。
//OnSignedOutCallbackRedirect不会在用户注销后为其生成任何要读取的用户声明。
options.Events.OnSignedOutCallbackRedirect+=OpenIdeEvents.OnSignedOutCallbackRedirectFunc;
});
//添加使用Azure AD角色强制授权的授权策略。在单独的类中定义的策略。
services.AddAuthorization(选项=>
{
//这一行可能根本不适用于razor,我还没有尝试过,但是MS项目示例中的MVC中使用了什么。。。
//options.AddPolicy(AuthorizationPolicys.AssignmentToUserReadErrorRequired,policy=>policy.RequireRole(AppRole.UserReaders));
//下面的注释-我不得不将语法从RequireRole更改为RequireRecall
options.AddPolicy(AuthorizationPolicies.AssignmentToEditRolesRoleRequired,policy=>policy.requirect(ClaimTypes.Role,approvle.EditRoles));
options.AddPolicy(AuthorizationPolicies.AssignmentToViewLogsRoleRequired,policy=>policy.requirect(ClaimTypes.Role,approvle.ViewLogs));
options.AddPolicy(AuthorizationPolicies.AssignmentToViewUsersRoleRequired,policy=>policy.requirect(ClaimTypes.Role,approvle.ViewUsers));
options.AddPolicy(AuthorizationPolicys.AssignmentToCreateUsersRoleRequired,policy=>policy.Required(ClaimTypes.Role,Approvle.CreateUsers));
options.AddPolicy(AuthorizationPolicys.AssignmentToEditUsersRoleRequired,policy=>policy.Required(ClaimTypes.Role,Approvle.EditUsers)
    // Sign-in users with the Microsoft identity platform
    services.AddSignIn(Configuration);

    // Token acquisition service based on MSAL.NET
    // and chosen token cache implementation
    services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { GraphScopes.UserRead })
        .AddInMemoryTokenCaches();
   // Sign-in users with the Microsoft identity platform
   //services.AddSignIn(Configuration);
   services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
   // Token acquisition service based on MSAL.NET and chosen token cache implementation
       .EnableTokenAcquisitionToCallDownstreamApi(new string[] { GraphScopes.UserRead })
       .AddInMemoryTokenCaches();