首先,在 web api 控制器中使用 [Authorize] 标记以确保只有授权用户才能访问方法。然后,确保客户端与服务器正确进行身份验证。如果使用的是 cookie 认证方式,则需要设置 CookieAuthenticationOptions 的属性。例如:
在 Startup.cs 中:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "MyApp.AuthenticationCookie";
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.LoginPath = "/Login";
options.LogoutPath = "/Logout";
options.AccessDeniedPath = "/AccessDenied";
});
在 Blazor 应用的 App.razor 文件中,使用 AuthorizeView 组件进行身份验证。例如:
You are logged in.
You are not logged in.
其中,上面的代码在页面中显示“你已经登陆”的消息,以及一个“退出”按钮。如果用户未登录,则显示“你未登录”的消息,以及一个“登录”按钮。
最后,在 web api 控制器中实现对授权用户的访问,例如:
[Route("api/[controller]")]
public class MyController : Controller
{
[Authorize]
[HttpGet]
public async Task>> Get()
{
// your code to return data here
return new string[] { "value1", "value2" };
}
}