用户授权失败:(空)

2024-02-07

我正在为 ASP.NET MVC Core 使用自定义身份验证,但它不使用Identity。这是Startup.cs:

public class Startup
{
    public IConfiguration Configuration { get; set; }

    // Configure IoC container
    // https://docs.asp.net/en/latest/fundamentals/dependency-injection.html
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<AppSettings>(options => Configuration.GetSection(nameof(AppSettings)).Bind(options));

        // https://docs.asp.net/en/latest/security/anti-request-forgery.html
        services.AddAntiforgery(options => options.CookieName = options.HeaderName = "X-XSRF-TOKEN");

        services.AddDbContext<DbSesamContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("SesamConnection"));
        });

        services.AddDbContext<TerminalDbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("TerminalConnection"));
        });

        services.AddMvcCore()
            .AddAuthorization()
            .AddViews()
            .AddRazorViewEngine()
            .AddJsonFormatters();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
    {
        // Configure logging
        // https://docs.asp.net/en/latest/fundamentals/logging.html
        factory.AddConsole(Configuration.GetSection("Logging"));
        factory.AddDebug();

        // Serve static files
        // https://docs.asp.net/en/latest/fundamentals/static-files.html
        app.UseStaticFiles();

        // Enable external authentication provider(s)
        // https://docs.asp.net/en/latest/security/authentication/sociallogins.html
        //app.UseIdentity();

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = "ResWebAuth",
            LoginPath = new PathString("/login"),
            AccessDeniedPath = new PathString("/unauthorized/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
        });

        // Configure ASP.NET MVC
        // https://docs.asp.net/en/latest/mvc/index.html
        app.UseMvc(routes =>
        {
            routes.MapRoute("default", "{*url}", new { controller = "Home", action = "Index" });
        });
    }

    public static void Main()
    {
        var cwd = Directory.GetCurrentDirectory();
        var web = Path.GetFileName(cwd) == "server" ? "../public" : "public";

        var host = new WebHostBuilder()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseWebRoot(web)
            .UseKestrel()
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

在我的控制器中:

[Authorize]
public class HomeController : Controller
{
    public async Task<IActionResult> Index()
    {
        ...

        return View();
    }

    [HttpGet("login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login(string ReturnUrl)
    {
        ...

        return View();
    }

    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginInfo loginInfo)
    {
        if (LoginUser(loginInfo.Username, loginInfo.Password))
        {
            var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, loginInfo.Username),
                    new Claim("DbVersion", loginInfo.Terminal.SesamDbVersion),
                    new Claim("DbUrl", loginInfo.Terminal.SesamDbUrl),
                    new Claim("DbName", loginInfo.Terminal.SesamDbName),
                    new Claim("DbUsername", loginInfo.Terminal.SesamDbUserName),
                    new Claim("DbPasswordHash", loginInfo.Terminal.SesamDbPasswordHash),
                };

            var userIdentity = new ClaimsIdentity(claims, "login");

            ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
            await HttpContext.Authentication.SignInAsync("ResWebAuth", principal);

            //Just redirect to our index after logging in. 
            return Redirect("/");
        }
        return View();
    }

    [HttpGet("getchartdata")]
    //[AllowAnonymous]
    public JsonResult GetChartData()
    {
        ...
    }

The log:

info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
      HttpContext.User merged via AutomaticAuthentication from authenticationScheme: ResWebAuth.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
      Authorization was successful for user: admin.

...

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/getchartdata/
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
      AuthenticationScheme: ResWebAuth was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action Server.Controllers.HomeController.GetChartData (server) in 5.2905ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 10.1037ms 302 

所以基本上它成功授权了用户Index()控制器的方法,但未能在GetChartData()同一控制器的方法。

之间似乎有区别Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1] and Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]我不明白它是什么以及如何解决它。


对于 ASP.Net Core 2.0,我添加了:app.UseAuthentication(); in Startup.Configure() https://learn.microsoft.com/en-us/aspnet/core/fundamentals/startup#the-configure-method这为我解决了这个错误。

参考:Oauth 2.0 迁移公告 https://github.com/aspnet/Security/issues/1310

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });
}

Note:请务必致电UseAuthentication()打电话之前UseMvc() in Startup.Configure() https://learn.microsoft.com/en-us/aspnet/core/fundamentals/startup#the-configure-method正如评论中所指出的。

中间件组件在Configure 方法中添加的顺序定义了它们在请求中调用的顺序,以及响应的相反顺序。此顺序对于安全性、性能和功能至关重要。

Source ASP.NET Core 文档 https://learn.microsoft.com/en-us/aspnet/core/ -> 中间件 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?tabs=aspnetcore2x -> Ordering https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?tabs=aspnetcore2x#ordering

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用户授权失败:(空) 的相关文章

随机推荐

  • 埃拉托斯特尼素数筛法到一百万 C++

    所以我需要有关我的代码的帮助 由于某种原因 当我输入超过 500 000 的数字时 它不断崩溃 这是确切的分配 实现埃拉托色尼筛法并用它来查找所有素数 数量小于或等于一百万 使用结果 证明哥德巴赫猜想对于 4 到 4 之间的所有偶数 100
  • 基于单选按钮选择的 jQuery DatePicker 更新选项

    我试图让 jquery 日期选择器在选择不同的单选按钮时进行更新 div style padding bottom 50px div
  • 使用 WebDriver 处理不受信任的 SSL 证书

    我在使用 Java 中的 webdriver 处理不受信任的 SSL 证书时遇到了困难 我创建了 Firefox 配置文件 如下所示 FirefoxProfile profile new FirefoxProfile profile set
  • InstallShield - 相对文件路径

    如何将文件添加到 InstallShield 组件并指定 InstallShield 项目的相对路径 以便轻松在不同计算机上编译项目 使用免费的 VS 限量版 InstallShield 设置自定义路径看起来不太可能 因此 在只有几个预定义
  • Drupal:在网络表单中的提交按钮上方添加免责声明文本

    有没有一种简单的方法来修改 webform form tpl php 模板以在 Drupal Web 表单中的提交按钮上方显示免责声明文本 我可以在按钮下方添加文本 但不知道如何将按钮与其他元素分开以在它们之间添加文本 即 form ele
  • 使用 @Named 和未命名参数从 Javascript 客户端库进行调用是没有意义的

    我有一个Cloud Endpoints方法看起来像这样 HTTP POST ApiMethod name hylyts insert public Hylyt insertHylyt Named url String url Hylyt h
  • 将bind1st 用于通过引用获取参数的方法

    我有一个这样的结构 struct A void i int i void s string const s 现在当我尝试这个时 bind1st mem fun A i a 0 bind1st mem fun A s a 第一行编译正常 但第
  • 检查 SQL 中的日期是否重叠

    我有一个表 tblBranchTimingEntry BranchEntryID fromDate toDate SundayIn 24 2015 01 01 00 00 00 000 2015 01 31 00 00 00
  • Airflow k8s 运营商 xcom - 握手状态 403 禁止

    当我使用运行 docker 镜像时KubernetesPodOperator在气流版本 1 10 中 一旦 pod 成功完成任务 airflow 就会尝试通过 k8s 流客户端连接到 pod 来获取 xcom 值 以下是我遇到的错误 201
  • 如何设置 RStudio 服务器以在 AWS 上使用 SSL 运行?

    我有兴趣在 AWS 实例上运行 RStudio 服务器并通过 SSL 加密连接访问服务器 我该如何设置 启动一个使用 Ubuntu 作为操作系统的 AWS 实例 以及一个安全组 除了通过端口 22 的 SSH 连接之外 该安全组还具有端口
  • BLE获取广告包中编码的uuid

    我正在尝试获取 ble 设备的 UUID 我遵循 Android 开发人员指南 到目前为止我只能获取设备名称和 RSSI 我试图获取扫描方法中设备的 Uuid 如下所示 public void onLeScan final Bluetoot
  • 关于glTexImage3D

    对于 3D 纹理 对于三维纹理 z 索引指的是第三维 这究竟意味着什么 对于二维数组纹理 z 索引指的是切片索引 如果我们有 4 层 2D 纹理 那么如果 z 2 它将引用第二个 2D 纹理切片 那么 当我们有目标 GL TEXTURE 3
  • 实体框架 6 重用数据注释

    我已经寻找了一段时间的明确解决方案 但尚未得出结论 我想在数据模型类上仅指定一次数据注释 并让 UI 从视图模型类中看到这些注释 而无需再次指定它们 为了说明我的观点 假设我有一个 UserAccount 类 public class Us
  • iOS7风格的mapview标注segue在标注中(calloutAccessoryControlTapped,UIButtonTypeDetailDisclosure)

    我在 iPad 上有带有注释和标注的地图视图 每个标注还有 rightCalloutAccessoryView 和详细信息披露按钮 我看到库存地图应用程序对标注对象内的标注详细信息执行segue 它首先像推送转场一样执行视图从右到左的转换
  • Three.js - 合并多个几何体/网格,删除公共区域

    我正在尝试将两个几何图形 网格 红色和蓝色 合并为一个独特的几何图形 网格 但是在创建新的几何体并应用 Geometry merge 之后 我发现所有内部顶点和面仍然存在 绿色区域 我想删除所有这些额外的信息 因为它会在渲染的面上产生视觉故
  • CSS @font-face 在 ie 中不起作用

    我有以下 CSS 可以在 Firefox 中运行 但不能在 IE 中运行 显然 字体在目录中 有什么建议么 font face font family Futura src url fonts Futura Medium BT eot IE
  • 如何在使用 NSwag 生成的客户端方法名称中包含 Http 请求方法名称

    当我使用 NSwag 为 API 生成 C 客户端时 其中 API 包含可与多种 Http 请求类型 例如 POST GET 一起使用的端点 客户端为每个请求生成一个具有相同基本名称和数字的方法 例如 使用此 API https api p
  • 反向 Swift 字典查找

    我有一本看起来像这样的字典 let ints Int String 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 A 11 B etc 我可以查找一个整数ints 5 to get 5 如何从字符串中
  • Python中有B树数据库或框架吗?

    我听说 B Tree 数据库比哈希表更快 所以我想到在我的项目中使用 B Tree 数据库 python中是否有任何现有的框架允许我们使用这样的数据结构 或者我必须从头开始编码 无论是在内存中还是在块存储中 如在数据库中 选择 B 树而不是
  • 用户授权失败:(空)

    我正在为 ASP NET MVC Core 使用自定义身份验证 但它不使用Identity 这是Startup cs public class Startup public IConfiguration Configuration get