【发布时间】:2021-02-05 07:02:27
【问题描述】:
我在 Visual Studio 2019 中创建了 Blazor WebAssembly 应用程序,并在 IdentityServer4 上使用选项 ASP.NET Core 托管和身份验证(个人用户帐户、应用程序内存储用户帐户)。从 Visual Studio 生成的程序。我没有修改任何东西。一切正常。我可以登录并查看带有 [Authorize] 属性的客户端页面。
在下一步中,我将一个新的 Razor 页面添加到服务器端(而不是客户端) - Reports.cshtml 启动程序后,我可以进入新创建的页面。它工作正常。
现在我将 [Authorize] 属性添加到服务器端 Reports.cshtml 页面。启动程序并登录后,显示 Reports.cshtml 页面的尝试以错误结束:401 Unauthorized
这有什么问题?
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseWebAssemblyDebugging();
}
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.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-BlazorAuthTest1;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"IdentityServer": {
"Clients": {
"BlazorAuth.Client": {
"Profile": "IdentityServerSPA"
}
}
},
"AllowedHosts": "*"
}
感谢您的帮助!
【问题讨论】:
-
我遇到了同样的问题,并在你的前一天问了这个问题stackoverflow.com/questions/64470056/… 我认为这与设置使用不记名令牌的事实有关(如果使用模板,你可以看到获取天气数据)。在提出建议后,我使用了 NavigateTo 功能,但对于普通的服务器页面,默认情况下它不会放入不记名令牌。如果我不能解决这个问题,我正在考虑是否追求这个或只是将我的服务器页面滚动到应用程序中。我确定这是在启动代码中配置它的问题。
-
我会说会有更多这样的事情发生,所以如果微软有人在看的话,这是一个很好的教程或指南案例?
标签: c# blazor razor-pages webassembly authorize