在 .Net Core 3.0 项目中正确设置 ASP.Net 核心授权和身份验证



我目前使用 VSCode 开发一个 .net core api 项目,我想将 ASP.NET 核心身份验证和授权与 cookie 集成。

我试图在Startup.cs中添加services.AddAuthentication();services.AddAuthorization();.我还在我的UsersController.cs中添加了[Authorize]属性。

[Authorize]
[Route("api/Users")]
[ApiController]
public class UsersController : ControllerBase

问题是,当我启动我的应用程序时,即使我没有创建用户或角色,我仍然可以访问我的 API。(https://localhost:5001/api/Users(

我尝试像下面这样设置我的launchSettings.json

"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:49086",
"sslPort": 44343
}

但我仍然可以访问我的 API。如果没有用户或角色,如何拒绝访问?

我肯定错过了一些东西,但我不知道是什么。

提前感谢您的帮助!

好吧,我有点愚蠢,我从ASP Mvc 5的相关问题中找到了这个解决方案,Startup.cs我在ConfigurationServices中添加了以下行:

services.AddMvcCore(option => option.EnableEndpointRouting = false).AddAuthorization();

Configure

app.UseMvc();

现在,我的控制器[Authorize]工作正常,如果我未经身份验证,我就无法访问我的 API。

最新更新