E成网络

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

(五):安全应用程序块——入门篇

一.     安全应用程序块概述:

安全应用程序块通过一个或多个安全机制,帮助开发人员在应用程序中实现通用的安全相关任务。

需要提高扩展性,以便在不改变应用程序代码的情况下更改认证或授权方式。

提供了以下几个方面的功能:

1.认证

2.授权

3.角色管理

4Profile管理

二.     几个重要的概念:

1.          Credential(令牌)

2.          Identity(身份)

3.          Principal(主体特征)

三.     使用三部曲:

在进行使用前请确保项目中有App.configWeb.config文件,并且需要数据库中有相关的表和存储过程,具体可参见数据库EntLibQuickStartsEnterprise Library的示例库)。

1.定义配置文件:

1)运行Enterprise Library Configuration 配置工具,打开项目中的配置文件;

2)右击Application,选择New | Security Application Block,创建一个安全应用程序块;

3)在Security Application Block | Authentication 节点上右击,选择 New | Database Authentication Provider,创建一个数据库认证Provider

4)根据在数据访问应用程序块中所讲的,设置数据库的连接字符串;

5)右击Cryptography Application Block | Hash Providers,选择New | Hash Algorithm Provider,创建一个加密Provider,并设置SaltEnabledTrue

6)选择Security Application Block | Authentication | Database Provider设置 Database 属性为 Database Instance, 并且设置 HashProvider 属性为SHA1Managed

7)选择Security Application Block,设置它的DefaultAuthenticationInstanceDatabase Provider



8)选择File | Save All保存全部。

至此,关于认证部分的配置已经做完。仅仅有这些还不够,我们还要进行设置角色。

9)选择Security Application Block,右击Roles,选择New | Role Database Provider创建一个角色的数据库Provider

10)设置Database属性为Database Instance

11)选择Security Application Block节点,设置DefaultRolesInstance,为RolesDatabase Provider


12)保存全部File | Save All

至此,所有的配置文件的工作已经做完。最后别忘了,做拷贝目录

1copy "$(ProjectDir)\*.config" "$(TargetDir)"

2.创建Security Provider实例:

1IAuthenticationProvider authprovider;
2            authprovider = AuthenticationFactory.GetAuthenticationProvider();

3.执行Security Provider命令:

 1 public static bool Authenticate(string username, string password)
 2        {
 3            bool authenticated = false;
 4
 5            
 6            NamePasswordCredential credentials;
 7            credentials = new NamePasswordCredential(username, password);
 8 
 9            IAuthenticationProvider authprovider;
10            authprovider = AuthenticationFactory.GetAuthenticationProvider();
11 
12            IIdentity identity;
13            authenticated = authprovider.Authenticate(credentials, out identity);
14 
15            if (!authenticated)
16            {
17                throw new SecurityException("Invalid username or password.");
18            }

19            
20          
21            
22            IRolesProvider rolesprovider;
23            rolesprovider = RolesFactory.GetRolesProvider();
24 
25            IPrincipal principal;
26            principal = rolesprovider.GetRoles(identity);
27 
28            // Place user's principal on the thread
29            Thread.CurrentPrincipal = principal;
30            
31            return authenticated;
32        }
posted on 2006-08-15 23:39  玉成  阅读(162)  评论(0)    收藏  举报