我正在创建一个 Blazor 应用程序(.NET Core、C#),但对如何集成 .NET Core 的内置身份验证和授权服务(.NET Core Identity)感到困惑。
您可以参考这篇关于“Scaffold Identity into a Blazor Server project without existing authorization”的文档,将 ASP.NET Core Identity 集成到您的 Blazor 项目中,这将有助于添加所需的库并为您配置 Identity。
那么你应该在你的 Blazor 项目中做一些修改:
在Shared文件夹下添加LoginDisplay.razor
<AuthorizeView>
<Authorized>
<a href="Identity/Account/Manager">Hello, @context.User.Identity.Name!</a>
<form method="post" action="Identity/Account/LogOut">
<button type="submit" class="nav-link btn btn-link">Log out</button>
</form>
</Authorized>
<NotAuthorized>
<a href="Identity/Account/Register">Register</a>
<a href="Identity/Account/Login">Login</a>
</NotAuthorized>
</AuthorizeView>
在MainLayout.razor中引用LoginDisplay
@inherits LayoutComponentBase
<div class="sidebar">
<NavMenu />
</div>
<div class="main">
<div class="top-row px-4">
<LoginDisplay></LoginDisplay>
<a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
</div>
<div class="content px-4">
@Body
</div>
</div>
如下更新 App.razor
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
@*<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>*@
<CascadingAuthenticationState>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</CascadingAuthenticationState>
</NotFound>
</Router>
Startup 类中的配置
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//...
//other configurations here
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();
services.AddSingleton<WeatherForecastService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
//other configurations here
app.UseAuthentication();
app.UseAuthorization();
//...
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
当我也在构建数据访问的API时,我觉得认证等也应该在Web API部分实现
如果您在 Web API 项目中分离数据访问部分,保护 Web API 部分(通过 JWT 身份验证等)将有助于防止意外使用者调用您的 API。
测试结果