为什么 blazor webassembly 需要授权显示数据?

why blazor webassembly need to authorize for show data?

我使用 aspcore 托管(默认模板)和个人用户帐户身份验证创建了默认的 Blazor Web 程序集。但我有一个问题,我想为 Anonymous 用户显示数据 FetchData.razor 组件。默认情况下,用户必须登录网站才能查看 FetchData.razor 组件内容。

我将所有 [Authorize] 属性更改为 [AllowAnonymous] 组件和 Web api 甚至删除所有 [Authorize] 属性(在组件和 Web api 上)。但是,还是去重定向到登录页面。

组件:

using blazorAuten.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace blazorAuten.Server.Controllers
{
   // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            this.logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

fetchdata api 控制器:

@page "/fetchdata"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using blazorAuten.Shared
@*@attribute [Authorize]*@
@inject HttpClient Http

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
    }

}

如您所见,所有 [Authorize] 属性都是注释。即使使用 [AllowAnonymous] 检查也是相同的结果。

即使在App.Razor组件中,我也评论了<RedirectToLogin />组件。但是当我转到 fetchdata 组件时仍然重定向到登录页面:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    @if (!context.User.Identity.IsAuthenticated)
                    {
                        @*<RedirectToLogin />*@
                    }
                    else
                    {
                        <p>You are not authorized to access this resource.</p>
                    }
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

所以如果我想向匿名用户(第一次访问网站的来宾用户)显示来自 api 的数据,我应该怎么做?所有网站访问者都必须登录?来自 api(服务器)的所有数据都需要用户授权吗?

我有这个App.razor,它对我有用:

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                <RedirectToLogin />
            </NotAuthorized>
            <Authorizing>
                <PageLoading Information="Authentication in progress" />
            </Authorizing>
        </AuthorizeRouteView>
    </Found>
    <NotFound>
        <CascadingAuthenticationState>
            <LayoutView Layout="@typeof(MainLayout)">
                <PageNotFound />
            </LayoutView>
        </CascadingAuthenticationState>
    </NotFound>
</Router>

HttpClient一定没有AuthorizationMessageHandler.

我遇到了同样的问题,只需在 https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-3.1#unauthenticated-or-unauthorized-web-api-requests-in-an-app-with-a-secure-default-client 中寻找“具有安全默认客户端的应用程序中未经身份验证或未经授权的 Web API 请求”部分的解决方案,问候。