在 .Net Core 3.0 项目中正确设置 ASP.Net 核心授权和身份验证
Setup ASP.Net Core Authorize and Authentication Properly in a .Net Core 3.0 project
我目前正在使用 VSCode 进行 .net 核心 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。
我目前正在使用 VSCode 进行 .net 核心 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。