【问题标题】:why blazor webassembly need to authorize for show data?为什么 blazor webassembly 需要授权显示数据?
【发布时间】:2020-08-13 08:34:51
【问题描述】:

我创建了一个带有 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();
        }
    }
}

fetchdataapi 控制器:

@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 组件中,我也会评论&lt;RedirectToLogin /&gt; 组件。但是当我转到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(服务器)的所有数据都需要用户授权吗?

【问题讨论】:

    标签: c# blazor blazor-webassembly


    【解决方案1】:

    我有这个 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

    【讨论】:

    • 我把App.razor改成这个,但仍然重定向到登录页面(结果相同)。
    • 你删除了授权属性吗?
    • 你需要一个没有BaseAddressAuthorizationMessageHandlerHttpClient
    • 否,此处理程序用于从会话存储中检索访问令牌并填充授权标头。如果用户未通过身份验证,则尝试登录。
    • 如果您需要 2 个HttpClient,一个用于匿名端点,一个用于授权端点,然后考虑使用名为 HttpClient 的 HttpClientFactory
    【解决方案2】:

    我遇到了同样的问题,请在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 请求”部分的解决方案,问候。

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2021-11-03
      • 2023-03-20
      • 1970-01-01
      • 2013-02-19
      • 2020-08-27
      • 2021-11-05
      • 2021-03-08
      • 1970-01-01
      相关资源
      最近更新 更多