我从Visual Studio模板开始,这是一个新的Blazor WebAssembly,具有身份验证和Web API作为服务器端。
现在,我想保护我的Pages和服务器API。我执行以下操作:
Page:
<AuthorizeView Roles="Administrator">
<Authorized>
<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>
}
</Authorized>
<NotAuthorized>
...
</NotAuthorized>
</AuthorizeView>
@code {
private WeatherForecast[] forecasts;
protected override async Task OnInitializedAsync()
{
var response = await Http.GetAsync("Api/WeatherForecast/Get");
//var resp = await Http.GetFromJsonAsync<WeatherForecast[]>("Api/WeatherForecast/Get");
if (response.IsSuccessStatusCode)
{
var s = await response.Content.ReadAsStringAsync();
forecasts = await response.Content.ReadFromJsonAsync<WeatherForecast[]>();
}
}
}
API
[Authorize]
[ApiController]
[Route("api/[controller]/[action]")]
public class WeatherForecastController : Controller
{
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”的用户未登录,并且无法显示站点。 但是仍会调用OnInitializedAsync。该API被阻止是因为[授权]。
但是现在问题来了。 使用var response = await Http.GetAsync(“ Api / WeatherForecast / Get”);我得到了HttpCode 200。但是从未调用过API?它来自哪里?
这里有问题吗?如何使我的Page和API安全?
我不想像这样在每个页面中使用AuthenticationStateProvider:
@code {
private WeatherForecast[] forecasts;
[CascadingParameter]
Task<AuthenticationState> authenticationStateTask { get; set; }
protected override async Task OnInitializedAsync()
{
if(authenticationStateTask.Result.User.IsInRole("Administrator"))
{
var response = await Http.GetAsync("Api/WeatherForecast/Get");
//var resp = await Http.GetFromJsonAsync<WeatherForecast[]>("Api/WeatherForecast/Get");
if (response.IsSuccessStatusCode)
{
var s = await response.Content.ReadAsStringAsync();
forecasts = await response.Content.ReadFromJsonAsync<WeatherForecast[]>();
}
}
}
}
答案 0 :(得分:0)
你不必! :) 但问题是,您是希望整个应用都安全,还是只是几个页面?
就我个人而言,我更喜欢注入 @inject AuthenticationStateProvider AuthenticationStateProvider
,然后使用 GetAuthenticationStateAsync();
内的 OnInitializedAsync()
获取身份验证状态。示例:
protected override async Task OnInitializedAsync()
{
try
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
if(authState.User.Identity.IsAuthenticated)
UserName = $"Hi, {authState.User.Claims.FirstOrDefault(x => x.Type == "display_name")?.Value}!";
}
catch (Exception ex)
{
Logger.LogError($"Failed to initialize menu. Error: {ex}");
}
}
您可以使用 <AuthorizeView />
组件为经过身份验证/授权的用户处理呈现内容。来自我自己的应用的示例:
<AuthorizeView>
<Authorized>
<CascadingValue Name="DeviceType" IsFixed="true" Value="DeviceType">
<NavMenu />
</CascadingValue>
</Authorized>
</AuthorizeView>
如果当前用户登录,我只使用它来呈现我的导航。如果没有,则没有菜单。