C# .NET 中的身份验证、授权、用户和角色管理以及一般安全性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1222974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Authentication, Authorization, User and Role Management and general Security in .NET
提问by Saajid Ismail
I need to know how to go about implementing general security for a C# application. What options do I have in this regard? I would prefer to use an existing framework if it meets my needs - I don't want to re-invent the wheel.
我需要知道如何为 C# 应用程序实现一般安全性。在这方面我有哪些选择?如果现有框架满足我的需求,我更愿意使用它——我不想重新发明轮子。
My requirements are as follows:
我的要求如下:
- the usual username/password authentication
- managing of users - assign permissions to users
- managing of roles - assign users to roles, assign permissions to roles
- authorization of users based on their username and role
- 通常的用户名/密码认证
- 用户管理 - 为用户分配权限
- 角色管理 - 为用户分配角色,为角色分配权限
- 基于用户名和角色的用户授权
I am looking for a free / open-source framework/library that has been time-tesed and used by the .Net community.
我正在寻找一个经过时间检验并被 .Net 社区使用的免费/开源框架/库。
My application takes a client/server approach, with the server running as a windows service, connecting to a SQL Server database. Communication between client and server will be through WCF.
我的应用程序采用客户端/服务器方法,服务器作为 Windows 服务运行,连接到 SQL Server 数据库。客户端和服务器之间的通信将通过 WCF。
One other thing that is important is that I need to be able to assign specific users or roles permissions to View/Update/Delete a specific entity, whether it be a Customer, or Product etc. For e.g. Hyman can view a certain 3 of 10 customers, but only update the details of customers Microsoft, Yahoo and Google, and can only delete Yahoo.
另一件重要的事情是,我需要能够分配特定用户或角色权限来查看/更新/删除特定实体,无论是客户还是产品等。例如,Hyman 可以查看 10 个中的某个 3客户,但只能更新客户微软、雅虎和谷歌的详细信息,并且只能删除雅虎。
采纳答案by Marc Gravell
For coarse-grained security, you might find the inbuilt principal code useful; the user object (and their roles) are controlled in .NET by the "principal", but usefully the runtime itself can enforce this.
对于粗粒度的安全性,您可能会发现内置的主体代码很有用;用户对象(及其角色)在 .NET 中由“主体”控制,但有用的是运行时本身可以强制执行此操作。
The implementation of a principal can be implementation-defined, and you can usually inject your own; for example in WCF.
主体的实现可以是实现定义的,您通常可以注入自己的;例如在 WCF 中。
To see the runtime enforcing coarse access (i.e. which functionalitycan be accessed, but not limited to which specific data):
要查看执行粗略访问的运行时(即可以访问哪些功能,但不限于哪些特定数据):
static class Roles {
public const string Administrator = "ADMIN";
}
static class Program {
static void Main() {
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity("Fred"), new string[] { Roles.Administrator });
DeleteDatabase(); // fine
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity("Barney"), new string[] { });
DeleteDatabase(); // boom
}
[PrincipalPermission(SecurityAction.Demand, Role = Roles.Administrator)]
public static void DeleteDatabase()
{
Console.WriteLine(
Thread.CurrentPrincipal.Identity.Name + " has deleted the database...");
}
}
However, this doesn't help with the fine-grained access (i.e. "Fred can access customer A but not customer B").
但是,这对细粒度访问没有帮助(即“Fred 可以访问客户 A 但不能访问客户 B”)。
Additional; Of course, for fine-grained, you can simply check the required roles at runtime, by checking IsInRole
on the principal:
额外的; 当然,对于细粒度,您可以通过检查IsInRole
主体在运行时简单地检查所需的角色:
static void EnforceRole(string role)
{
if (string.IsNullOrEmpty(role)) { return; } // assume anon OK
IPrincipal principal = Thread.CurrentPrincipal;
if (principal == null || !principal.IsInRole(role))
{
throw new SecurityException("Access denied to role: " + role);
}
}
public static User GetUser(string id)
{
User user = Repository.GetUser(id);
EnforceRole(user.AccessRole);
return user;
}
You can also write your own principal / identity objects that do lazy tests / caching of the roles, rather than having to know them all up-front:
您还可以编写自己的主体/身份对象来进行延迟测试/角色缓存,而不必预先了解它们:
class CustomPrincipal : IPrincipal, IIdentity
{
private string cn;
public CustomPrincipal(string cn)
{
if (string.IsNullOrEmpty(cn)) throw new ArgumentNullException("cn");
this.cn = cn;
}
// perhaps not ideal, but serves as an example
readonly Dictionary<string, bool> roleCache =
new Dictionary<string, bool>();
public override string ToString() { return cn; }
bool IIdentity.IsAuthenticated { get { return true; } }
string IIdentity.AuthenticationType { get { return "iris scan"; } }
string IIdentity.Name { get { return cn; } }
IIdentity IPrincipal.Identity { get { return this; } }
bool IPrincipal.IsInRole(string role)
{
if (string.IsNullOrEmpty(role)) return true; // assume anon OK
lock (roleCache)
{
bool value;
if (!roleCache.TryGetValue(role, out value)) {
value = RoleHasAccess(cn, role);
roleCache.Add(role, value);
}
return value;
}
}
private static bool RoleHasAccess(string cn, string role)
{
//TODO: talk to your own security store
}
}
回答by Ray
WCF have rich security related functionality provides both authorization and authentication. In details here: http://msdn.microsoft.com/en-us/library/ms735093.aspx
WCF 具有丰富的安全相关功能,提供授权和身份验证。详情请见:http: //msdn.microsoft.com/en-us/library/ms735093.aspx
回答by MyItchyChin
Look into ASP.NET's Membership Providers. I don't think the out of box SQLMembershipProvider will work in your case but it's easy enough to roll your own provider.
查看ASP.NET 的 Membership Providers。我认为开箱即用的 SQLMembershipProvider 不适用于您的情况,但推出您自己的提供程序很容易。
回答by Chris Andrews
I would take a look at something like CSLA.net: Expert C# 2008 Business Objects
我会看看像 CSLA.net: Expert C# 2008 Business Objects 这样的东西
It should provide everything you require.
它应该提供您需要的一切。
回答by Stephen Wrighton
my answer is probably dependent upon the answer to this question: Is this an Enterprise application which lives within a network with Active Directory?
我的回答可能取决于对这个问题的回答:这是一个存在于具有 Active Directory 的网络中的企业应用程序吗?
IF the answer is yes, then these are the steps I would provide:
如果答案是肯定的,那么这些是我将提供的步骤:
1) Create Global Groups for your application, in my case, I had a APPUSER group and an APPADMIN group.
1)为您的应用程序创建全局组,就我而言,我有一个 APPUSER 组和一个 APPADMIN 组。
2) Have your SQL Server be able to be accessed in MIXED AUTHENTICATION mode, and then assign your APPUSER group(s) as the SQL SERVER LOGIN to your database with the appropriate CRUD rights to your DB(s), and ensure that you access the SQL SERVER with Trusted Connection = Truein your connection string.
2) 让您的 SQL Server 能够以混合身份验证模式访问,然后将您的 APPUSER 组作为 SQL SERVER LOGIN 分配到您的数据库,并具有对您的数据库的适当 CRUD 权限,并确保您访问连接字符串中具有Trusted Connection = True的 SQL SERVER 。
At this point, your AD store will be responsible for authentication. Since, you're accessing the application via a TRUSTED CONNECTION, it will pass the identity of whatever account is running the application to the SQL Server.
此时,您的 AD 存储将负责身份验证。因为,您通过受信任的连接访问应用程序,它会将运行该应用程序的任何帐户的标识传递给 SQL Server。
Now, for AUTHORIZATION (i.e. telling your application what the logged in user is allowed to do) it's a simple matter of querying AD for a list of groups which the logged in user is a member of. Then check for the appropriate group names and build your UI based upon membership this way.
现在,对于 AUTHORIZATION(即告诉您的应用程序允许登录用户做什么),查询 AD 以获取登录用户所属的组列表是一件简单的事情。然后检查适当的组名称并以这种方式基于成员身份构建您的 UI。
The way my applications work are thus:
我的应用程序的工作方式是这样的:
- Launching the application, credentials are based upon the logged-in user, this is the primary aspect of authentication (i.e. they can log in therefore they exist)
- I Get all Groups For the Windows Identity in question
- I check for the Standard USER Group -- if this group does not exist for the Windows Identity in question, then that's an authentication FAIL
- I check for ADMIN User Group -- With this existing in the user's groups, I modify the UI to allow access to administration components
- Display the UI
- 启动应用程序,凭据基于登录用户,这是身份验证的主要方面(即他们可以登录,因此他们存在)
- 我获取了有关 Windows 标识的所有组
- 我检查了标准用户组——如果这个组不存在于有问题的 Windows 标识,那么这是一个身份验证失败
- 我检查 ADMIN 用户组 -- 在用户组中存在此用户组后,我修改了 UI 以允许访问管理组件
- 显示用户界面
I then have either a PRINCIPLE object with the determined rights/etc on it, or I utilize GLOBAL variables that I can access to determine the appropriate UI while building my forms (i.e. if my user is not a member of the ADMIN group, then I'd hide all the DELETE buttons).
然后我有一个具有确定的权限/等的 PRINCIPLE 对象,或者我在构建我的表单时使用我可以访问的 GLOBAL 变量来确定适当的 UI(即,如果我的用户不是 ADMIN 组的成员,那么我会隐藏所有 DELETE 按钮)。
Why do I suggest this?
为什么我建议这样做?
It's a matter of deployment.
这是部署的问题。
It has been my experience that most Enterprise Applications are deployed by Network Engineers rather than programmers--therefore, having Authentication/Authorization to be the responsibility of AD makes sense, as that is where the Network guys go when you discuss Authentication/Authorization.
根据我的经验,大多数企业应用程序是由网络工程师而不是程序员部署的——因此,将身份验证/授权作为 AD 的责任是有道理的,因为当您讨论身份验证/授权时,网络人员会去那里。
Additionally, during the creation of new users for the network, a Network Engineer (or whoever is responsible for creating new network users) is more apt to remember to perform group assignments while they are IN AD than the fact that they have to go into a dozen applications to parse out assignments of authorization.
此外,在为网络创建新用户期间,网络工程师(或负责创建新网络用户的任何人)更容易记住在他们在 AD 期间执行组分配,而不是他们必须进入十几个应用程序来解析授权分配。
Doing this helps with the maze of permissions and rights that new hires need to be granted or those leaving the company need to be denied and it maintains authentication and authorization in the central repository where it belongs (i.e. in AD @ the Domain Controller level).
这样做有助于解决新员工需要授予或离开公司需要拒绝的权限和权利的迷宫,并且它在其所属的中央存储库中维护身份验证和授权(即在 AD @ 域控制器级别)。
回答by Wyatt Barnett
I think you are looking at a few separate problems here--it is no accident most security systems separate authentication and authorization.
我认为您在这里查看了几个单独的问题——大多数安全系统将身份验证和授权分开并不是偶然的。
For authentication, the bigger question is logistical. Or, is there a logical place for these users to live, be it locally to the application, in Active Directory, some other LDAP store or even in some other application. Exactly where is pretty immaterial--we just need to be able to solidly identify users and preferably make that task someone else's problem. End of the day you really just need a unique identifier and the comfort that Bob from Accounting is actually Bob from Accounting.
对于身份验证,更大的问题是后勤问题。或者,这些用户是否有一个合乎逻辑的居住位置,无论是在应用程序本地、Active Directory 中、某个其他 LDAP 存储中,还是在其他某个应用程序中。确切的位置非常不重要——我们只需要能够可靠地识别用户,并最好将这项任务交给其他人。归根结底,您真的只需要一个唯一的标识符,以及会计的 Bob 实际上是会计的 Bob 的安慰。
Authorization is the more interesting part of the problem here. I think, if it is truly fine-grained, you really want to manage this wholly within your application, no matter where the users come from. Marc Gravell really hit on a good way to model at least some of this--use some custom implementation of IPrincipal and PrincipalPermission to manage things is a very clean way to get started. Beyond that you can use techniques like this oneto make more complex authorization decisions in a rather clean manner.
授权是这里问题中更有趣的部分。我认为,如果它真的是细粒度的,你真的希望在你的应用程序中完全管理它,不管用户来自哪里。Marc Gravell 确实找到了一种很好的方法来至少对其中的一些进行建模——使用 IPrincipal 和 PrincipalPermission 的一些自定义实现来管理事物是一种非常干净的入门方法。除此之外,你可以使用技术,像这样一个在一个相当干净的方式,使更多复杂的授权决定。
回答by Kunal Khatri
I would use the term - 'RBAC' (Role based Access Control system) as the Solution to all your requirements.
我会使用术语 - 'RBAC'(基于角色的访问控制系统)作为满足您所有要求的解决方案。
I would not go in much detail for explaining 'RBAC' here, rather I would briefly describe it as:
我不会在这里详细解释“RBAC”,而是将其简要描述为:
It basically contains 3 features.
它基本上包含3个功能。
1) Authentication - It confirms the user's identity. Usually it is done via user accounts and passwords or credentials.
1) 身份验证 - 它确认用户的身份。通常它是通过用户帐户和密码或凭据完成的。
2) Authorization - It defines what user can do and cannot do in an application. Ex. ‘Modifying order' is allowed but ‘creating new order' is not allowed.
2) 授权 - 它定义了用户在应用程序中可以做什么和不能做什么。前任。允许“修改订单”,但不允许“创建新订单”。
3) Auditing of user actions on applications. - It keeps track of user's actions on applications, as well as who has granted which access to which users?
3) 审计用户对应用程序的操作。- 它跟踪用户对应用程序的操作,以及谁授予了哪些用户访问权限?
you can check RBAC on wiki here.
您可以在此处查看 wiki 上的 RBAC。
https://en.wikipedia.org/wiki/Role-based_access_control
https://en.wikipedia.org/wiki/Role-based_access_control
Now, regarding answer to your requirements - one of the possible solution is to extend ASP.NET membership as per your needs.
现在,关于满足您的要求 - 一种可能的解决方案是根据您的需要扩展 ASP.NET 成员资格。
And regarding, some ready to use framework , I would recommend VisualGuardfor which I work, you should check this, It does all the things what you need very easily, and what is most important is, It manages all your users, roles, permissions, and applications via Central Administration Console, and for defining permissions, administrators do not require developer's knowledge, i.e he/she can create restrictions on activities via UI.
关于一些现成的框架,我会推荐我工作的VisualGuard,你应该检查一下,它可以很容易地完成你需要的所有事情,最重要的是,它管理你的所有用户、角色、权限,以及通过中央管理控制台的应用程序,并且对于定义权限,管理员不需要开发人员的知识,即他/她可以通过 UI 对活动创建限制。
you can also check this article to have more understanding on permission and role based system.
您还可以查看这篇文章以对基于权限和角色的系统有更多的了解。