繁体   English   中英

使用 Azure Active Directory 验证 Blazor WebAssembly 应用程序

[英]Authenticating a Blazor WebAssembly app with Azure Active Directory

我已经有一个现有的 Blazor WebAssembly 应用程序,我正在尝试使用 Azure Active Directory 添加身份验证。

我添加了Microsoft.Authentication.WebAssembly.Msal nuget。

在我服务器的Program.cs中,我添加了以下代码:

builder.Services.AddMsalAuthentication(options =>
        {
            builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
            options.ProviderOptions.LoginMode = "redirect";
        });

我已经将以下内容添加到我的 appsettings.json

  "AzureAd": {
    "Instance": "xxxxxxxxxxx",
    "Domain": "xxxxxxxxxxx",
    "TenantId": "xxxxxxxxxxx",
    "ClientId": "xxxxxxxxxxx",
    "CallbackPath": "xxxxxxxxxxx"
  },

我很难理解我还需要添加什么,以便在运行该应用程序时,我会看到 Microsoft 登录屏幕。

您需要对部分应用程序或整个应用程序进行授权。 默认情况下,应用程序内的所有路由都向公众开放。 如果你想屏蔽这些路由中的任何一条,你需要明确地请求授权。
此处记录了如何执行此操作: Secure ASP.NET Core Blazor WebAssembly

在 Blazor WebAssembly 应用程序中,可以绕过授权检查,因为用户可以修改所有客户端代码。 这同样适用于所有客户端应用程序技术,包括 JavaScript SPA 框架或适用于任何操作系统的本机应用程序。

始终在您的客户端应用程序访问的任何 API 端点内的服务器上执行授权检查。

如果您在托管选项上托管应用程序,例如 Static Web 应用程序,您可以让 Azure 平台强制执行授权,而无需手动执行任何操作。

验证和授权 Static Web Apps

您可以新建一个 blazor web 组合应用程序并选择Microsoft identity platform ,然后修改appsettings.json文件。

在此处输入图像描述

您需要添加 3 个部分, Program.cs中的身份验证注入, appsettings.json中的配置,以及sign view模块,其中 2 个您已经拥有,左侧是顶部导航栏中的sign in/out按钮,这样您就可以单击它重定向到 Microsoft 登录页面。 您可以创建模板项目并将 razor 组件复制到您的项目中。

LoginDisplay.razor

@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication

@inject NavigationManager Navigation
@inject SignOutSessionStateManager SignOutManager

<AuthorizeView>
    <Authorized>
        Hello, @context.User.Identity?.Name!
        <button class="nav-link btn btn-link" @onclick="BeginLogout">Log out</button>
    </Authorized>
    <NotAuthorized>
        <a href="authentication/login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

@code{
    private async Task BeginLogout(MouseEventArgs args)
    {
        await SignOutManager.SetSignOutState();
        Navigation.NavigateTo("authentication/logout");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM