C# clr udf for Active Directory group membership

≯℡__Kan透↙ 提交于 2019-12-08 18:48:27

Most likely all of those Assemblies will need to be set to UNSAFE, especially the three System.DirectoryServices* .NET Framework libraries that you imported. Also, since you are importing unsupported .NET Framework libraries, you will need to set the database to TRUSTWORTHY ON in order to get them to work. Setting a Database to TRUSTWORTHY ON is typically something you want to avoid as it is a security risk, but in this case I do not believe that it can be avoided.

That said, I am not sure that you even need to create this function yourself in SQLCLR. If you are just wanting to know if a Login (Windows Logins only, obviously) belongs to a particular Active Directory group, there is a built-in function that should do that for you. The IS_MEMBER function will indicate if the current Login is a member of the specified Windows group (specified as Domain\Group). The difference in how this function works as opposed to the one that you are creating is that it only works for the current Login; you cannot pass any arbitrary Login into it. BUT, it also doesn't require any of the extra effort and security risks that are a part of this SQLCLR solution. So, something to consider :-).

Comment from O.P. on this answer:

Actually, I need to check an arbitrary Login if it's member of a particular group. I even tried to use a stored proc and `OPENQUERY' with a linked server to ADSI, but this only works as Dynamic SQL since I need to inject group and user.

In that case, just make the Dynamic SQL two layers deep instead of the usual one layer. Something along the lines of:

DECLARE @SQL NVARCHAR(MAX);
SET @SQL = N'
  SELECT *
  FROM   OPENQUERY([LinkedServer], N''
             SELECT *
             FROM   someResource
             WHERE  GroupName=N''''' + @Group + N'''''
             AND    ObjectName=N''''' + @Login + N''''';
                   '');
';

PRINT @SQL; -- DEBUG
EXEC (@SQL);

In this approach, the query executing OPENQUERY is Dynamic SQL, but the query given to OPENQUERY to execute is a string literal.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!