asp.net-core - Blazor 身份验证 - Http 调用确实适用于匿名
问题描述
我一直在使用 .net 5.0 玩 blazor。我遇到了一个简单但烦人的问题:我正在尝试从 API 加载数据,但每次调用服务器 blazor 都希望用户登录。
我理解如果我们从 API 控制器中取出 [Authorize] 标签并且@attribute [Authorize]
在剃须刀页面中没有,那就是这样。但是我很难理解为什么我的 API 调用仍然期望 AccessToken 在protected override async Task OnInitializedAsync()
错误消息中并没有说明原因。
Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessTokenNotAvailableException: ''
at Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
我没有碰过应用程序。Web程序集的cs文件..
任何人都可以帮忙吗?
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<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>
<Authorizing>
<h4>Authentication in progress...</h4>
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
解决方案
我认为这是因为您已经CascadingAuthenticationState
封装了Found
上下文,并且NotFound
因为它所做的是将授权信息传递给其他组件。因此,将它包裹在所有组件周围可以防止未经授权的用户访问。试试这个
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<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>
<Authorizing>
<h4>Authentication in progress...</h4>
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<CascadingAuthenticationState>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
<CascadingAuthenticationState>
</NotFound>
</Router>
推荐阅读
- matlab - MATLAB 对象属性可见但不可修改
- html - 为弹性列中的滑动效果转换哪个属性
- c# - Xceed 标记化文本框搜索“开始于”
- c# - 只能在 IEnumerable 上调用 Cast 和 OfType
- swift - Swift Pong(No SpriteKit):检测球击中的桨侧
- php - "Controller ..CategoryController 具有必需的构造函数参数,并且在容器中不存在。您是否忘记定义这样的服务?",
- angular - 在 Angular 应用程序上传递动态数据
- filter - 根据 RangeTool 中的日期时间散景过滤 CDSView
- bash - 按列对重复项进行排序
- apache-spark - 读取带有前导时间戳的 json