.NET Core 3.1 Web 应用程序与 React - 如何防止基于 Active Directory 组的访问

2023-12-02

我有一个 .NET Core 3.1 Web 应用程序,其中包含使用 Windows 身份验证的 React。 当用户输入他们的 Active Directory 凭据时,我想在允许访问 React 应用程序之前验证他们属于特定的 Active Directory 组。

我尝试将默认端点设置为登录控制器来验证用户的组,但我不知道如何重定向到 React 应用程序(如果他们确实有有效的组)。

启动.cs:

app.UseEndpoints(endpoints =>
  {                
      endpoints.MapControllerRoute(
          name: "default",
          pattern: "{controller}/{action=Index}/{id?}",
          defaults: new { Controller = "Login", action = "Index" });
  });

登录控制器:

public IActionResult Index()
{
        if (HttpContext.User.Identity.IsAuthenticated)
        {
            string[] domainAndUserName = HttpContext.User.Identity.Name.Split('\\');
             //AuthenticateUser verifies if the user is in the correct Active Directory group
            if (AuthenticateUser(domainAndUserName[0], domainAndUserName[1]))
            {
                //This is where i would like to redirect to the React app
                return Ok(); //This does not go to the react app
                return LocalRedirect("http://localhost:50296/"); //This will keep coming back to this method
            }
            return BadRequest();            
        }
}

是否可以从控制器重定向到 React 应用程序? 有没有更好的方法来验证活动目录组(可能通过authorizationService.js)?


我以前遇到过这种情况,并通过 IClaimsTransformation 的自定义实现解决了它。此方法还可以与 OpenId Connect 和其他需要额外授权的身份验证系统一起使用。

通过这种方法,您可以在为您的 React 应用程序提供服务的控制器上使用授权属性

[Authorize(Roles = "HasAccessToThisApp")]

and

User.IsInRole("HasAccessToThisApp")

代码中的其他地方。

执行。请注意,每个请求都会调用 TransformAsync,如果有任何耗时的调用,建议进行一些缓存。

public class YourClaimsTransformer : IClaimsTransformation
{
    private readonly IMemoryCache _cache;

    public YourClaimsTransformer(IMemoryCache cache)
    {
        _cache = cache;
    }

    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal incomingPrincipal)
    {
        if (!incomingPrincipal.Identity.IsAuthenticated)
        {
            return Task.FromResult(incomingPrincipal);
        }

        var principal = new ClaimsPrincipal();

        if (!string.IsNullOrEmpty(incomingPrincipal.Identity.Name)
             && _cache.TryGetValue(incomingPrincipal.Identity.Name, out ClaimsIdentity claimsIdentity))
        {
            principal.AddIdentity(claimsIdentity);
            return Task.FromResult(principal);
        }

        // verifies that the user is in the correct Active Directory group
        var domainAndUserName = incomingPrincipal.Identity.Name?.Split('\\');
        if (!(domainAndUserName?.Length > 1 && AuthenticateUser(domainAndUserName[0], domainAndUserName[1])))
        {
            return Task.FromResult(incomingPrincipal);
        }

        var newClaimsIdentity = new ClaimsIdentity(
            new[]
            {
                new Claim(ClaimTypes.Role, "HasAccessToThisApp", ClaimValueTypes.String)

                // copy other claims from incoming if required

            }, "Windows");

        _cache.Set(incomingPrincipal.Identity.Name, newClaimsIdentity,
            DateTime.Now.AddHours(1));

        principal.AddIdentity(newClaimsIdentity);
        return Task.FromResult(principal);
    }
}

在启动#ConfigureServices中

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

.NET Core 3.1 Web 应用程序与 React - 如何防止基于 Active Directory 组的访问 的相关文章

随机推荐

  • 在python中绘制热图

    我有两个列表 x y 代表二维坐标 例如x 1 4 0 5 2 5 10 33 0 04 and y 2 5 44 0 33 2 14 20 0 03 x i and y i 代表二维中的一个点 现在我还有一个表示每个 x y 点的 热 值
  • 雅虎财经网络服务消失了吗? API变了?暂时下降?

    相当长一段时间以来 我一直在使用以下 REST API 来查询雅虎财经的当前价格 它在多个 Stack Overflow 帖子中都有记录 例如雅虎财经网络服务以及其他地方雅虎财经 http finance yahoo com webserv
  • 为什么使用push/pop而不是sub和mov?

    当我使用不同的编译器时https godbolt org 我注意到编译器生成这样的代码是很常见的 push rax push rbx push rcx call rdx pop rcx pop rbx pop rax 我明白每个push o
  • r - rmarkdown - 渲染数据帧列表

    是否可以将 Markdown 文档中的数据框列表呈现为单独的表格 Example 给定代码块 r listOfDf library knitr df lt data frame a rnorm 10 b rnorm 10 c c rep a
  • Php解析html dom并计算特定行数

    我正在使用 简单的 php DOM 解析器 解析 html 表并计算其行数 我解决了使用以下代码计算其中的所有行 tr 的问题 rows table gt find trClass count count rows echo count 我
  • 如何将 ruby​​ 记录器日志输出到标准输出以及文件?

    类似于记录器中的 T 恤功能 你可以写一个伪IO将写入多个的类IO对象 就像是 class MultiIO def initialize targets targets targets end def write args targets
  • 在 React 组件中从 Behance API 加载数据

    我正在尝试通过他们的 API 加载 Behance 项目数据 无论是本地主机还是产品 我都会收到以下错误 Fetch API 无法加载 XXX 对预检请求的响应未通过访问控制检查 请求的资源上不存在 Access Control Allow
  • 如何在 C# 中检查套接字是否已连接/断开?

    如果其他主机在断开连接时没有向您发送数据包 例如 因为它不正常地断开连接 如何检查网络套接字 System Net Sockets Socket 是否仍然连接 As 保罗 特纳回答了Socket Connected在这种情况下不能使用 您需
  • ExpressJS:如何使用参数重定向 POST 请求

    我需要将 Node js 服务器的所有 POST 请求重定向到远程服务器 我尝试执行以下操作 app post function req res res redirect http remoteserver com req path 重定向
  • Javascript 根据星期几隐藏/显示 div?

    我正在尝试创建一个动态页面 根据一周中的某一天更改内容 我以为我有解决方案 但我似乎无法使其发挥作用 div div
  • 重新声明 JavaScript 变量

    In this教程里写着 If you redeclare a JavaScript variable it will not lose its value 为什么要重新声明变量 在某些情况下实用吗 谢谢 这只不过是提醒您 如果您这样做 v
  • 主窗口 DataContext StackOverflowException

    我知道这可能听起来很疯狂 但为了我的理解 你会如何解释这个设置Window DataContext to MainWindow结果出现此错误 引发了 System StackOverflowException 类型的异常
  • LINQDataSource - 查询多个表?

    我有一个数据库 并且创建了一个 DBML Linq to SQL 文件来表示该数据库 我创建了一个新的 aspx 页面 并在其上放置了 linqdatasource 和 formview 控件 当我配置 linqdatasource 时 它
  • 在代码隐藏的 asp:image 中显示数据表中的图像

    我有一个数据表 它是从 1 行选择语句的结果集中填充的 通过 SQL Server 2008 中的存储过程 它包含一个Image我在其中存储图像的键入列 我有一个asp image在 aspx 页面上进行控件 我想将图像设置为该数据表的相应
  • 如何使用陀螺仪从加速度计仅获取线性加速度?

    我的房间地板上有一辆小型遥控车 为了简单起见 我们假设它沿着 x 轴移动 现在 地板看起来很平坦 但每个表面都有非常微小的凹凸不平 因此 每当汽车不完全平坦时 因为它处于起始位置 或者换句话说 每当汽车有哪怕是最轻微的倾斜时 从加速度计获得
  • 多选列表框

    我的表单上有一个列表框 它可以很好地满足我想要做的事情 我想要编辑表单上的项目 这意味着填充列表框 然后选择相关项目 我的列表框包含项目尺寸列表 我想选择属于正在编辑的项目的尺寸 请有人给我一些指点 I tried me lstItemSi
  • 拟合 RNN LSTM 模型时出错

    我正在尝试使用以下代码创建用于二元分类的 RNN LSTM 模型 alldataset np loadtxt FinalKNEEALL txt delimiter num classes 2 num of sam alldataset sh
  • Spring 捕获index.html 的所有路由

    我正在为基于react的单页应用程序开发一个spring后端 其中我使用react router进行客户端路由 除了index html页面之外 后端还提供路径上的数据 api 为了提供我的index htmlsrc main resour
  • 如何处理 UWP 按下的后退按钮

    我曾经在 Windows Phone 8 1 XAML 中使用硬件按钮 API 但是 在 UWP 中 某些设备没有后退按钮 如何适应新的应用模式 稍微解释一下答案 你可以使用系统导航管理器 of Windows UI Core名称空间 对于
  • .NET Core 3.1 Web 应用程序与 React - 如何防止基于 Active Directory 组的访问

    我有一个 NET Core 3 1 Web 应用程序 其中包含使用 Windows 身份验证的 React 当用户输入他们的 Active Directory 凭据时 我想在允许访问 React 应用程序之前验证他们属于特定的 Active