【问题标题】:Blazor WebAssembly: builder.Services.AddMsalAuthentication throws Exception => Cannot read property 'join' of undefinedBlazor WebAssembly:builder.Services.AddMsalAuthentication 抛出异常 => 无法读取未定义的属性“加入”
【发布时间】:2020-09-14 15:30:57
【问题描述】:

我第一次尝试使用 MSAL 授权,但在 Blazor 中失败了。任何线索(我认为这将是一个简单的答案?)

小仓库可用here

客户端文件:Program.cs

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");

builder.Services.AddMsalAuthentication(options => //THROWS EXCEPTION!!!!!
{
    options.ProviderOptions.AdditionalScopesToConsent.Add($"https://graph.microsoft.com/User.Read");
});

var baseAddress = builder.HostEnvironment.BaseAddress;
builder.Services.AddHttpClient(baseAddress, client => client.BaseAddress = new Uri(baseAddress))
        .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

意外结果:抛出异常

暴击:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常呈现组件:无法读取未定义的属性“加入” TypeError:无法读取未定义的属性“加入” 在 Function.createUserManager (https://localhost:44391/_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js:1:6020) 在 Function.initializeCore (https://localhost:44391/_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js:1:5035) 在 Function.init (https://localhost:44391/_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js:1:4575) 在https://localhost:44391/_framework/blazor.webassembly.js:1:9873 在新的承诺 () 在 Object.beginInvokeJSFromDotNet (https://localhost:44391/_framework/blazor.webassembly.js:1:9841) 在 _mono_wasm_invoke_js_marshalled (https://localhost:44391/_framework/wasm/dotnet.3.2.0.js:1:171294) 在 do_icall (wasm-function[6049]:0x10f8b1) 在 do_icall_wrapper (wasm-function[1896]:0x50b6a) 在 interp_exec_method (wasm-function[1120]:0x2588e)

【问题讨论】:

    标签: blazor webassembly msal


    【解决方案1】:

    试试这样的...

    builder.Services.AddMsalAuthentication(options =>
    {
        ...
    
        options.ProviderOptions.AdditionalScopesToConsent.Add(
            "https://graph.microsoft.com/Mail.Send");
        options.ProviderOptions.AdditionalScopesToConsent.Add(
            "https://graph.microsoft.com/User.Read");
    }

    https://docs.microsoft.com/en-us/aspnet/core/security/blazor/webassembly/additional-scenarios?view=aspnetcore-3.1#request-additional-access-tokens

    希望对你有帮助!

    编辑 1: 我的客户Program.cs

    using System.Net.Http; using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

    Index.html页面中添加以下引用

    <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
    
    public static async Task Main(string[] args)
            {
                var builder = WebAssemblyHostBuilder.CreateDefault(args);
                builder.RootComponents.Add<App>("app");
    
                builder.Services.AddHttpClient("BlazorWasmAADMsal.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
    
                // Supply HttpClient instances that include access tokens when making requests to the server project
                builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("BlazorWasmAADMsal.ServerAPI"));
    
                builder.Services.AddMsalAuthentication(options =>
                {
                    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
                    options.ProviderOptions.DefaultAccessTokenScopes.Add("api://XXXXXXXXXXXXXXXXXX/API.Access");
                });
    
                await builder.Build().RunAsync();
            }
    

    编辑 2: 做了一些小改动。工作项目已上传here。在答案中添加了成功登录屏幕截图以供参考。 :-)

    编辑 3:

    应用需要 Azure Active Directory (AAD) Microsoft Graph API 范围来读取用户数据和发送邮件。在 Azure AAD 门户中添加 Microsoft Graph API 权限后,将在客户端应用中配置其他范围。

    上次我错过启用下面的行,我在Program.cs启用它

      builder.Services.AddMsalAuthentication(options =>
           {
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
         }

    这是一个奇怪的错误,没想到而且已经看到了。

    Index.html 中 AuthenticationService.js 的引用不正确。我已将其更正为...

    <script src="_content/Microsoft.Authentication.WebAssembly.Msal/AuthenticationService.js"></script>
    

    我也上传了最新的代码here

    IAccessTokenProvider.RequestToken 方法提供了一个重载,允许应用提供具有给定范围集的访问令牌。

    在 Razor 组件中,您可以编写如下内容:

    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
    @inject IAccessTokenProvider TokenProvider
    
    ...
    
    var tokenResult = await TokenProvider.RequestAccessToken(
        new AccessTokenRequestOptions
        {
            Scopes = new[] { "https://graph.microsoft.com/Mail.Send", 
                "https://graph.microsoft.com/User.Read" }
        });
    
    if (tokenResult.TryGetToken(out var token))
    {
        ...
    }

    AccessTokenResult.TryGetToken 返回:

    true 使用令牌。 false 如果未检索到令牌。

    希望对你有所帮助。

    【讨论】:

    • AddMsalAuthentication 抛出异常,它永远不会到达对 AdditionalScopesToConsent 方法的调用。在我的项目中,我在 appsettings.json 中保存范围并遍历它们,但此迭代从未开始,因为即使没有要添加的范围,AddMsalAuthentication 也会引发异常。
    • 删除 MsalAuth 代码是否有效?希望您的Program.csbuilder.RootComponents.Add&lt;App&gt;("app"); 中没有重复此行。一个简单的最小重现项目将有助于理解根本原因。
    • 是的,没有 builder.Services.AddMsalAuthentication 行可以完美运行。仅调用一次 builder.RootComponents.Add("app") 。感谢您的帮助。该项目相当大,但在 program.cs 启动文件中很早就失败了。
    • 我想我使用了来自错误库的 AddMsalAuthentication。 Nuget 包列表和使用提供 AddMsalAuthentication 扩展方法的语句的任何机会?我尝试了一个全新的干净 WebAssembly 项目,方法未知,添加这些包和使用使其编译,但它仍然抛出相同的异常。
    • 您使用的是哪种类型的身份验证?请参考this。它已逐步解释了如何配置。我正在使用这个-"Microsoft.Authentication.WebAssembly.Msal" Version="3.2.0",它对我来说很好用。
    猜你喜欢
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多