1

随着 NET 5 的正式发布,今晚我从 Net Core 3.1 迁移到 NET 5,一切似乎都很顺利,直到我尝试运行该应用程序,现在在 startup.cs 中的两个项目下发现了几条波浪线与 Microsoft Identity Web 平台相关联。这显然是一时的失败!在修复此问题之前,我将无法启动应用程序或登录 Azure AD。

将csproj文件修改为NET5后,我去nuget manager更新了所有的包。

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

带有波浪线的 startup.cs 文件的屏幕截图:

启动.cs 文件

csproj 文件:

在此处输入图像描述

带有更新包的 Nuget 管理器:

在此处输入图像描述

我注意到,自迁移以来,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");
    }

我只是不知道如何解决这个问题......

4

1 回答 1

0

好的,开始工作了。第一个问题我从另一个帖子中得到了答案:

services.AddSignIn() 在 Microsoft.Identity.Web 的 nuget 包中可用,最高版本 0.1.5 预览版,以上版本不包含 services.AddSignIn()

就我而言,我使用的是 Microsoft.Identity.Web 版本 1.3.0

我将下面直接显示的代码替换为底部的代码部分:

旧代码:

    // 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();

我已经进行了一些快速检查,以确保我能够对使用 MS Graph 的用户配置文件进行更改,所以我很满意这解决了我的问题。

于 2020-11-13T01:28:14.350 回答