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