如何在ASP.NET Core中将角色添加到Windows身份验证 [英] How to add Roles to Windows Authentication in ASP.NET Core
问题描述
我在Visual Studio 2015中使用Windows身份验证创建了一个asp.net核心项目.我不知道如何向身份添加角色.
I created an asp.net core project in visual studio 2015 with windows authentication. I can't figure out how to add roles to the Identity.
我有一个带有Windows帐户用户名的表.当用户打开网站时,会将用户添加到身份(我想就是这样,因为我可以通过User.Identity.Name显示用户名),并且我想从另一个表中提取角色"并将其分配给用户, 这可能吗?还是有更好的方法呢? (为什么?如何?)
I have a table with usernames for the windows account. And when the user opens the website the user is added to the Identity (I assume that's what happens, because I can display the username by User.Identity.Name) and I want to pull out Roles from another table and assign them to the user, is this possible? Or perhaps is there a better way to do it? (Why?, How?)
我找不到与Windows身份验证相关的特定示例的示例,但我已阅读文档并经过此指南.而且我仍然被困住.
I couldn't find any examples specific examples related to windows authentication, but I have read the documentation and went through this guide. And I'm still stuck.
推荐答案
这是我用来检查用户是否在角色\组中的有效代码,请随时使用
this is working code that I use to check is a user is in a role \ group, please use it at your leisure
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Security.Principal;
namespace Santander.IsUserInGroupOrRole_cs
{
public class IsUserInRole
{
public static bool IsInGroup(string groupName)
{
var myIdentity = GetUserIdWithDomain();
var myPrincipal = new WindowsPrincipal(myIdentity);
return myPrincipal.IsInRole(groupName);
}
public bool IsInGroup(List<string> groupNames)
{
var myIdentity = GetUserIdWithDomain();
var myPrincipal = new WindowsPrincipal(myIdentity);
return groupNames.Any(group => myPrincipal.IsInRole(group));
}
public static WindowsIdentity GetUserIdWithDomain()
{
var myIdentity = WindowsIdentity.GetCurrent();
return myIdentity;
}
public static string GetUserId()
{
var id = GetUserIdWithDomain().Name.Split('\\');
return id[1];
}
public static string GetUserDisplayName()
{
var id = GetUserIdWithDomain().Name.Split('\\');
var dc = new PrincipalContext(ContextType.Domain, id[0]);
var adUser = UserPrincipal.FindByIdentity(dc, id[1]);
return adUser.DisplayName;
}
}
}
这篇关于如何在ASP.NET Core中将角色添加到Windows身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!