我目前使用 VSCode 开发一个 .net core api 项目,我想将 ASP.NET Core 身份验证和授权与 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();
并在配置
中:
app.UseMvc();
现在,我的 Controller 中的 [Authorize]
可以正常工作,如果我未经身份验证,我将无法访问我的 API。
关于c# - 在 .Net Core 3.0 项目中正确设置 ASP.Net Core 授权和身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59286207/