获取用户在字符串变量中的角色

use*_*084 5 c# asp.net role

有没有办法可以使用以下命令在字符串变量中获取角色....

 System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
  System.Security.Principal.WindowsPrincipal wp = new System.Security.Principal.WindowsPrincipal(wi);
Run Code Online (Sandbox Code Playgroud)

我需要这个

 FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,                          // version
                                                   UserName.Text,           // user name
                                                   DateTime.Now,               // creation
                                                   DateTime.Now.AddMinutes(60),// Expiration
                                                   false,                      // Persistent 
                                                   role);         // User data
Run Code Online (Sandbox Code Playgroud)

as string role = wp.IsInRole();
但这不对

与此类似的东西......

Jas*_*ris 6

您可以从WindowsIdentity.Groups属性中获取用户所属的组/角色列表.WindowsIdentity.Groups集合仅包含用户所在组/角色的SID(IdentityReference集合),但不包含组/角色的实际名称.我将向您展示如何获取用户所在的所有组/角色的实际名称.

首先,获取WindowsIdentity对象.

WindowsIdentity identity = WindowsIdentity.GetCurrent();
Run Code Online (Sandbox Code Playgroud)

其次,使用LINQ将SID(IdentityReference)转换为NTAccount.

var groups = from sid in identity.Groups select sid.Translate(typeof(NTAccount)).Value;
Run Code Online (Sandbox Code Playgroud)

然后,您可以遍历组并将它们存储在可以在FormsAuthenticationTicket中使用的字符串数组中.这将为您提供BUILTIN(本地计算机)组/角色以及用户所在的DOMAIN组/角色.


Mar*_*ell 1

像这样吗?

public static string FormsAuthUserData
{
    get
    {
        IPrincipal principal = Thread.CurrentPrincipal;
        if (principal == null) return null;
        FormsIdentity identity = principal.Identity as FormsIdentity;
        if (identity == null) return null;
        FormsAuthenticationTicket ticket = identity.Ticket;
        return ticket == null ? null : ticket.UserData;
    }
}
Run Code Online (Sandbox Code Playgroud)