AuthorizeRouteView Authorizing 和 NotAuthorized 参数设置

Pep*_*ger 3 c# asp.net blazor blazor-server-side

每次非登录用户尝试访问页面时,我都想使用标签中的NotAuthorized属性<AuthorizeRouteView>重定向到登录页面。

然而,它需要一个RenderFragment<AuthentificationState>类型化的参数。我应该设置什么来设置这个参数来呈现登录页面?

编辑:代码非常简单。我使用了身份存储在应用程序中的 Blazor 服务器端项目模板,只需添加RedirectToLogin.razor如下内容:

@inject NavigationManager NavigationManager
@code { 
    protected override void OnAfterRender()
    {
        NavigationManager.NavigateTo("counter"); //for an unknown reason, the "Identity/Account/Login" redirect doesn't work.
    }
}
Run Code Online (Sandbox Code Playgroud)

并修改了App.razor

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    @if(true) { } //Used for breakpoint.
                    <RedirectToLogin />
                </NotAuthorized>
                <Authorizing>
                    @if(true) { } //Used for breakpoint.
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
Run Code Online (Sandbox Code Playgroud)

我没有碰它,Startup.cs所以它看起来像这样:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>()
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
            services.AddSingleton<WeatherForecastService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

Bri*_*ana 12

感谢MartinH,我没有花三天时间拔头发。

对于其他需要澄清“授权属性”的人,这里有一个示例......

验证Auth.razor

@page "/verifyauth"
@attribute [Authorize]    @*<--RIGHT HERE!!!*@

<div class="container">

    <h3 class="text-center">Verify Auth</h3>

</div>

@code {

}
Run Code Online (Sandbox Code Playgroud)

应用剃刀

<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" >
            <Authorizing>
                <text>Please wait, we are authorizing you...</text>
            </Authorizing>
            <NotAuthorized>
                @if (context.User.Identity.IsAuthenticated == false)
                {
                    <RedirectToLogin />
                }
                else
                {
                    <p>You are not authorized to access this resource.</p>
                }
            </NotAuthorized>
        </AuthorizeRouteView>
    </Found>
    <NotFound>
        <CascadingAuthenticationState>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there is nothing at this address.</p>
            </LayoutView>
        </CascadingAuthenticationState>
    </NotFound>
</Router>
Run Code Online (Sandbox Code Playgroud)

重定向到登录.razor

@inject NavigationManager NavManager

@code {
    protected override void OnInitialized()
    {
        NavManager.NavigateTo("/login");
    }
}
Run Code Online (Sandbox Code Playgroud)

参考: https: //learn.microsoft.com/en-us/aspnet/core/blazor/security/ ?view=aspnetcore-5.0#customize-unauthorized-content-with-the-router-component


Mar*_*inH 6

我遇到了一个类似的问题,我<NotAuthorized>在 app.razor 中的部分没有为未经授权的用户显示。在拔出我的头发 3 天后,我也在其他答案中提到的 MainLayout.razor 中寻求解决方案。一个干净的项目的最后一次尝试让我意识到我是一个多么可怜的程序员,因为我终于找到了答案。

我没有完全阅读文档,我可以在其中找到问题的原因。在以下页面上:https : //docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-5.0#customize-unauthorized-content-with- the- router-component 你会发现如何NotAuthorized 部分被调用。我完全错过了第二个要点:

Router 组件与 AuthorizeRouteView 组件结合使用,允许应用程序在以下情况下指定自定义内容:

  • 未找到内容。
  • 用户未通过应用到组件的 [授权] 条件。[Authorize] 属性包含在 [Authorize] 属性部分。
  • 正在进行异步身份验证。

这意味着<NotAuthorized>仅当路由端点具有 Authorize 标记时才会调用/显示该部件。在我的情况下,路线将进入我的索引页面,没有授权标签......


agu*_*ars 1

RenderFragment<AuthentificationState>是一段要渲染的html。您应该创建一个重定向到登录的组件:

ReditectToLogin.razor

@inject NavigationManager _navigationManager

@code {
    protected override Initialized()
    {
        _navigationManager.NavigateTo("login");
    }
}
Run Code Online (Sandbox Code Playgroud)

应用剃刀

...
<AuthorizeRouteView>
...
    <NotAuthorized>
       <ReditectToLogin />
    </NotAuthorized>
</AuthorizeRouteView>
Run Code Online (Sandbox Code Playgroud)

MainLayout.razor

<div class="sidebar bg-light">
    <NavMenu />
</div>

<div class="main bg-light mb-2">
...
    <div class="content px-4">
        <AuthorizeView>
            <Authorized>
                @Body
            </Authorized>
        </AuthorizeView>
Run Code Online (Sandbox Code Playgroud)