如何保护带有Azure AD B2C的Blazor Wasm应用程序访问的Azure功能? [英] How to secure an Azure Function accessed by a Blazor Wasm app with Azure AD B2C?

查看:20
本文介绍了如何保护带有Azure AD B2C的Blazor Wasm应用程序访问的Azure功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:我有一个用B2C身份验证保护的Blazor wasm应用程序,它需要调用一个HTTP触发的Azure函数。保护该Azure函数的最佳方法是什么,以便只有Blazor应用程序和/或经过身份验证的用户可以调用该函数?

到目前为止,我知道如何用B2C保护Blazor应用程序(显然很愚蠢!)我还能够将B2C身份验证添加到Azure函数中,并通过验证JWT令牌来保护调用。但我不清楚这两部分应该如何结合在一起。

我是否应该在B2C租户的Azure函数的应用注册中公开API?如果是,Blazor应用程序将如何对Azure函数进行身份验证调用?

还是只需通过Azure函数调用的http请求标头从Blazor应用程序发送JWT令牌,然后在函数内部手动验证该令牌?

我最近阅读了很多关于这个主题的不同帖子,但我仍然想不出实现这一目标的最佳解决方案是什么。

如有任何帮助/提示,我们将不胜感激。

谢谢!

PS:我对使用Azure API管理不感兴趣,因为对于一个非常简单的应用程序解决方案来说,它有点太贵了。

推荐答案

如果要调用Azure AD B2C投影的Azure函数,请参考以下步骤

  • 为Azure功能配置Azure AD B2C

    1. 创建Azure B2C应用。

      Web App/API:是

      允许隐式流动:是

    2. 在B2C APP中设置回复URL:https://{function app url}/.auth/login/aad/callback

    3. 在B2C App中设置App ID URL:https://{tennat}/{prefix}

    4. 记下B2C应用程序应用程序ID。

    5. 定义接口范围。转到B2C APP=>;发布的作用域

    6. 获取您的B2C用户流/策略的元数据URL。记下此URL。

      可从运行用户流页面获取。

      格式如https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/v2.0/.well-known/openid-configuration?p={policy}

    7. 转到您的功能=>;身份验证/授权

    8. 设置后

      • 应用服务身份验证:启用
      • 未通过身份验证时采取的操作:使用Azure AD登录
      • 身份验证提供程序:Azure AAD
      • 管理模式:高级
      • 客户端ID:{步骤4中的应用程序ID}
      • 颁发者URL:{步骤6中的URL}
      • 允许的受众:{第3步中的应用程序ID URL}
  • 创建客户端应用程序有关详细信息,请参阅here

  • 在Azure函数中配置CORS策略

  • 配置应用程序

  1. 创建
     dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "{AAD B2C INSTANCE}" --client-id "{CLIENT ID}" --domain "{TENANT DOMAIN}" -o {APP NAME} -ssp "{SIGN UP OR SIGN IN POLICY}"
    
  2. 代码
  • 创建自定义AuthorizationMessageHandler

    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
    
    public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
    {
        public CustomAuthorizationMessageHandler(IAccessTokenProvider provider, 
            NavigationManager navigationManager)
            : base(provider, navigationManager)
        {
            ConfigureHandler(
                authorizedUrls: new[] { "<your function app url>" },
                scopes: new[] { "<the function app  API scope your define>" });
        }
    }
  • Program.cs中添加以下代码。
public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");
             // register CustomAuthorizationMessageHandler 
            builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
            // configure httpclient
            // call the following code please add packageMicrosoft.Extensions.Http 3.1.0
            builder.Services.AddHttpClient("ServerAPI", client =>
              client.BaseAddress = new Uri("<your function app url>"))
                    .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
            // register the httpclient
            builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
             .CreateClient("ServerAPI"));
            // configure Azure AD auth
            builder.Services.AddMsalAuthentication(options =>
            {
                builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
                options.ProviderOptions.DefaultAccessTokenScopes.Add("<the function app  API scope your define>");


            });

            await builder.Build().RunAsync();
        }
  • 调用接口
 @page "/fetchdata"
        @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
        @inject HttpClient Http

        <h1>Call Azure Function</h1>

         <p>This component demonstrates fetching data from the server.</p>

         <p>Result: @forecasts</p>

          <button class="btn btn-primary" @onclick="CallFun">Call Function</button>

          @code {
              private string forecasts;

              protected async Task CallFun()
              {
                forecasts = await Http.GetStringAsync("api/http");
              }


           }

这篇关于如何保护带有Azure AD B2C的Blazor Wasm应用程序访问的Azure功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆