Blazor using Azure AD authentication allowing anonymous access

不打扰是莪最后的温柔 提交于 2021-02-16 09:27:06

问题


I'm currently writing a (Server side) Blazor application that includes the default AzureAD Authentication.

This works well for authenticated users - challenging on the entrance (_Host.cshtml) file, redirecting and then back once authenticated.

I need to have a couple of pages not requiring authentication - I don't want the user being challenged and redirected to Microsoft.

What is the correct way to do this? I have experimented with the AllowAnonymousAttribute, the AllowAnonymousToPage razor pages options, nothing seems to stop the challenge.

Any help would be greatly appreciated!

Below is my setup for Authentication (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();
    }

And then the appropriate part in Configure:

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

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

回答1:


I found what I had to do was add the following to _Hosts.cshtml

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

Once I did this authorization was no longer required on any of the pages by default and I could then add it to the pages where I wanted to require it.

For example if you wanted to secure the Counter.razor page just add an Authorize attribute to the top:

@attribute [Authorize]

So now if you tried to access the counter page you will get a Not authorized message.

If you want to remove the counter link when the user is not logged in modify the NavMenu.razor and surround the Counter link with an <AuthorizeView> </AuthorizeView> as so:

<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> 

Ideally I would have liked to just opt out of authorization for the index page and have everything else secured by default but I could not find a way to get that to work. If I tried adding the @attribute [AllowAnonymous] to the Index.razor page it seemed to ignore it.



来源:https://stackoverflow.com/questions/60768399/blazor-using-azure-ad-authentication-allowing-anonymous-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!