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

标签 c# asp.net-core .net-core .net-core-3.0

我目前使用 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/

相关文章:

asp.net-core - 修改中间件响应

c# - Quartz.Net 依赖注入(inject) .Net Core

c# - 各种 Microsoft.CodeQuality.* 分析器之间有什么区别?

c# - 使用Docker在Linux中运行dotnet应用程序

c# - 删除 Application Insights 后应用程序将无法启动

c# - 无法将类型字符串转换为 Bool

c# - 如何使用 CORS 启用自定义 header ?

c# - 在编译时不知道目标类型的情况下使用 Expression 获取属性值

c# - 如何在不知道构建配置的情况下将 EXE 从 .net 核心应用程序的 bin 目录复制到 wwwroot?

c# - .NET Microsoft.AspNetCore.Http.Extensions UriHelper.GetDisplayUrl 返回无效的 URI