簡體   English   中英

Blazor 使用 Azure AD 身份驗證允許匿名訪問

[英]Blazor using Azure AD authentication allowing anonymous access

我目前正在編寫一個(服務器端)Blazor 應用程序,其中包括默認的 AzureAD 身份驗證。

這適用於經過身份驗證的用戶 - 挑戰入口 ( _Host.cshtml ) 文件,重定向然后在經過身份驗證后返回。

我需要有幾個不需要認證的頁面-我不希望用戶受到挑戰,並重定向到微軟做。

這樣做的正確方法是什么? 我已經嘗試過AllowAnonymousAttributeAllowAnonymousToPage剃刀頁面選項,似乎沒有什么能阻止挑戰。

任何幫助將不勝感激!

以下是我的身份驗證設置(ConfigureServices):

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

    services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});

    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddTelerikBlazor();
}

然后是配置中的相應部分:

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/_Host");
});

我發現我必須做的是將以下內容添加到 _Hosts.cshtml

@using Microsoft.AspNetCore.Authorization
@attribute [AllowAnonymous]

一旦我這樣做了,默認情況下,任何頁面上都不再需要此授權,然后我可以將其添加到我想要它的頁面中。

例如,如果您想保護 Counter.razor 頁面,只需在頂部添加一個 Authorize 屬性:

@attribute [Authorize]

因此,現在如果您嘗試訪問櫃台頁面,您將收到一條未授權消息。

如果您想在用戶未登錄時刪除計數器鏈接,請修改 NavMenu.razor 並用<AuthorizeView> </AuthorizeView>包圍計數器鏈接,如下所示:

<AuthorizeView>
    <li class="nav-item px-3">
        <NavLink class="nav-link" href="counter">
            <span class="oi oi-plus" aria-hidden="true"></span> Counter
        </NavLink>
    </li>
</AuthorizeView> 

理想情況下,我只想選擇退出對索引頁面的授權,並默認保護其他所有內容,但我找不到讓它工作的方法。 如果我嘗試將@attribute [AllowAnonymous]添加到 Index.razor 頁面,它似乎忽略了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM