AzureAD 使用自定义按钮单击

AzureAD using custom button click

您好,我正在尝试使用 Azure 活动目录(Blazor 服务器应用程序)开发演示。

我的要求:

-> 单击按钮时它应该重定向到 https://login.microsoftonline.com/ 并且它应该对用户进行身份验证然后它应该再次重定向到我当前的 blazor 应用程序索引 url.

但在 运行 blazor 应用程序之后它直接重定向到 https://login.microsoftonline.com/ 并且在身份验证页面重定向到我的应用程序之后。

我的代码如下所示:

appSettings.json

{
   "AzureAd": {
   "Instance": "https://login.microsoftonline.com/",
   "Domain": "jpda.onmicrosoft.com",
   "TenantId": "aacd4f65-xxxx",
   "ClientId": "93134054-xxxx",
   "CallbackPath": "/signin-oidc",
   "ClientSecret": "I~Uoq5yxxxx"
},
  "Logging": {
  "LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
 }
  },
 "AllowedHosts": "*"
}

LoginDisplay.razor

<AuthorizeView>
<Authorized>
    Hello, @context.User.Identity.Name!
    <a href="MicrosoftIdentity/Account/SignOut">Log out</a>
</Authorized>
<NotAuthorized>
    <a href="MicrosoftIdentity/Account/SignIn">Log in</a>
</NotAuthorized>

Index.razor

@page "/"

<div class="top-row px-4 auth">
 @if (IsButtonClicked == true)
 {
    <LoginDisplay />
 }
 <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
 </div>
<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<button class="btn btn-primary" @onclick="(() => IsButtonClicked = true)">Login</button>

@code{ 
     [Parameter]
     public EventCallback<bool> OnButtonClicked { get; set; }
     public bool IsButtonClicked { get; set; }
  }

我正在从 index.razor 组件有条件地调用 组件,如果单击按钮然后它应该在身份验证页面上调用和重定向。

如果有人有想法请帮助我!! 提前致谢!

  1. 去的时候蔚蓝

    App registrations->new app registration

    提供一些有效名称并选择有效租户选项后, 您可以看到重定向 URI 选项。把 uri 放在那里很重要, 因为一旦注册,你就必须回到 应用。 url 取决于您的应用程序和位置 它位于本地。

    • 之后,当您进行身份验证时,您可以看到您提供的 url,您可以添加更多。

2. 打开 startup.cs 。必须有类似下面的内容(下面显示的注释行)

  • 将以下代码替换为以下代码 services.AddControllersWithViews(...),以便在单击登录按钮时重定向到 login.microsoftonline.com。

public void ConfigureServices(IServiceCollection services)
{
   //
   
   //
   services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

    services.AddControllersWithViews()
        .AddMicrosoftIdentityUI();

    services.AddRazorPages();
    
    
    
    //

    
}

3. 在blazor中,可以打开index.razor,打开terminal window 并添加以下库 =>Microsoft.AspNetCore.Authorization
代码:

    > dotnet add package Microsoft.AspNetCore.Authorization

4. 您可以打开index.razor并添加如下引用。 (你 可以在需要身份验证的地方为您喜欢的视图执行此操作 发生)

(如果您的应用有控制器,您也可以将 [Authorize] 属性添加到控制器中的索引操作,而不是在视图中授权)

参考文献:

  1. Redirect URI (reply URL) restrictions and limitations.
  2. Application configuration options.
  3. 使用 Azure Active Directory 身份验证构建 Blazor Web 应用程序 和 Microsoft Graph。