`
wyf
  • 浏览: 436853 次
  • 性别: Icon_minigender_1
  • 来自: 唐山
社区版块
存档分类
最新评论

ASP.NET Membership and Roles in Silverlight 3

阅读更多

Since Silverlight applications run on the client, in the browser, they do not natively have access to server-side technologies such as the ASP.NET Membership, Roles, and Profile Services.  However, it is relatively easy to provide these services through a WCF service that your Silverlight Application can consume. In this manner we can require users of our Silverlight app to authenticate, and we can even grant them specific roles, which can be stored in the Silverlight application itself once a user has authenticated.

I've seen a couple of examples where people saw somebody else's sample code that was using the default ASPNETDB.MDF SQL Server database and they actually decided to "roll their own" Membership Provider so that they would not have to use two separate databases. This is unnecessary. You can enable ANY SQL Server database for ASP.NET Membership, Roles and Profile by simply running the ASPNET_REGSQL.EXE  utility from the C:\Windows\Microsoft.NET\Framework\v2.0.50727 folder. This will prompt you to select a database, and you just "follow the wizard". You can also do this programmatically; make a "Setup.aspx" page that uses the System.Web.Management utility method. In this manner, the same SQL Server database can handle both your application's business logic persistence as well as ASP.NET Membership, Role and Profile storage. All the table names and stored procedure names will be prefixed with "aspnet" so as not to clobber your existing database schema:

Management.SqlServices.Install("server", "USERNAME", "PASSWORD", "databasename", SqlFeatures.All)

System.Web.Management -- SqlFeatures.Install Method

Here is the signature:

public static void Install (
string server,
string user,
string password,
string database,
SqlFeatures features
)

The majority of the "code" to enable a Silverlight application for Membership is actually  in the web.config, so let's go over the key areas first:

First we need to set up our connection string:

 <connectionStrings>
<remove name ="LocalSqlServer" />
<add name ="LocalSqlServer" connectionString ="server=(local);database=TEST;Integrated Security=SSPI" providerName ="SqlClient"/>
</connectionStrings >

 It is important to have a <remove...> element on these  first, otherwise you can end up using the ASP.NET default which is predefined in machine.config. Next, we need to allow unauthenticated users access to the stuff we'll use to authenticate them, otherwise they would never get to see our Silverlight Login "Page":

<
location path="SilverlightAuthenticationTestPage.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="ClientBin/SilverlightAuthentication.xap">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="WebServices/AuthenticationService.svc">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>

Finally, we'll enable the RoleManager:

<
roleManager enabled="true" />

And last, we need our Authentication and Membership blocks:

<
authentication mode="Forms">
<forms name="secure" enableCrossAppRedirects="true" loginUrl="/SilverlightAuthenticationTestPage.aspx" defaultUrl ="/SilverlightAuthenticationTestPage.aspx" protection="All">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<membership >
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="false" passwordFormat="Clear" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>

 The security features in the above sample are deliberately weak, as it is only a demo. The last ingredient is our System.ServiceModel block, which controls our service behavior:

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="SilverlightAuthentication.Web.WebServices.AuthenticationServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior> 
</serviceBehaviors>
</behaviors> 
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
<service behaviorConfiguration="SilverlightAuthentication.Web.WebServices.AuthenticationServiceBehavior"
name="SilverlightAuthentication.Web.WebServices.AuthenticationService">
<endpoint address="" binding="basicHttpBinding" contract="SilverlightAuthentication.Web.WebServices.AuthenticationService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service> 
</services>
</system.serviceModel>

 Moving into the codebehind for the actual WCF Service implementation, the code is very simple:

[ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AuthenticationService
    {
        public AuthenticationService()
        {
          // uncomment lines below to create a user and role
            //MembershipUser user = Membership.GetUser("test");
            //if(!Roles.GetAllRoles().Contains("Administrator"))
            //Roles.CreateRole("Administrator");
            //if(user==null)
            //{
            //    MembershipCreateStatus status;
            //    Membership.CreateUser("test", "test", "test@doo.com", "hello", "goodbye", true, out status);

            //    Roles.AddUsersToRole(new string[] {"test"}, "Administrator");
            //}
        }



        [OperationContract]
        public bool Authenticate(string Username, string Password)
        {
            if (Membership.ValidateUser(Username, Password))
            {
                FormsAuthentication.SetAuthCookie(Username, false);
                return true;
            }
            return false;
        }
    }

 

You can see I've got some commented "utility" code in the constructor that is only used once to facilitate programmatically creating a test user and Administrator Role. The actual work is done in the  Authenticate method, which does standard Membership authentication and sets the Forms Auth cookie. It then simply returns "true" if the user authenticated. You could, of course, modify this. Instead of simply returning a Boolean, you could instead have it return the names of the Roles for the authenticated user, which can be stored in the Silverlight app for further "permissions" use.  No Roles means they simply didn't authenticate.  Finally, notice the RequirementsMode attribute. You need to have this set.

OK! That's the service side. Now we can switch over to  the client-side in all of its Silverlight goodness.

In my default Silverlight "Page" I've got a Username and Password textbox, and a login Button. The codebehind looks like this
:

private void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            AuthenticationService.AuthenticationServiceClient authService = new AuthenticationService.AuthenticationServiceClient();
            authService.AuthenticateCompleted += new EventHandler<SilverlightAuthentication.AuthenticationService.AuthenticateCompletedEventArgs>(authService_AuthenticateCompleted);
            authService.AuthenticateAsync(TextBoxUsername.Text, TextBoxPassword.Text);
        }

        private void authService_AuthenticateCompleted(object sender, SilverlightAuthentication.AuthenticationService.AuthenticateCompletedEventArgs e)
        {
            if (e.Result)
            {
                App.CurrentUser = TextBoxUsername.Text;
                App app = (App)Application.Current;
                // Remove the displayed page
                app.root.Children.Clear();
                // Show the new page
                app.root.Children.Add(new Success());
            }
            else
            {
                TextBlockResult.Text = "Invalid username or password.";
            }
        }

 We instantiate our Service proxy, set the callback, and call it's AuthenticateAsync method. In the callback, if the result is true, we set the CurrentUser of the App, clear the Child Controls, and add in our Success Control which represents, in the demo,  "the rest of the app after you have logged in". If you didn't authenticate, we show the "Invalid" message.  If you are moving from one part of your Silverlight app to another, you can check the App.CurrentUser property to see if you're still "Logged in", and be able to control permissions appropriately. After reading and implementing the "Readme.txt" instructions, make sure that the web project is your startup project in Visual Studio.

 

分享到:
评论

相关推荐

    asp.net--membership详解

    3. **角色管理**:结合 ASP.NET Roles 功能,可以实现基于角色的权限控制。 4. **个性化设置**:利用序列化功能存储用户的个性化设置,如主题、字体大小等。 #### 四、总结 ASP.NET Membership 是一个强大的工具,...

    [ASP.NET.3.5高级程序设计(第2版)].Pro.ASP.NET.3.5.in.C#.2008.2th.edtion.pdf

    CHAPTER 1 Introducing ASP.NET 3 CHAPTER 2 Visual Studio 23 CHAPTER 3 Web Forms 71 CHAPTER 4 Server Controls 115 CHAPTER 5 ASP.NET Applications 167 CHAPTER 6 State Management219 PART 2 Data ...

    pro ASP.NET 4 in C# (part1/3)

    Introducing ASP.NET Visual Studio Web Forms Server Controls ASPNET Applications State Management ADONET Fundamentals Data Components and the DataSet Data Binding Rich Data Controls Caching ...

    asp.net4.0网站开发

    ASP.NET 4.0提供了内置的Membership、Roles和Profile系统,我们将学习如何配置和使用它们。 8. **AJAX和jQuery**:为了实现页面的异步更新和交互性,ASP.NET 4.0集成了AJAX技术和jQuery库。我们将学习如何使用...

    ASP.NET2.0数据库项目案例导航

    在ASP.NET 2.0中,可以使用预建的身份验证和授权组件,如Membership、Roles和Profile,来轻松实现用户注册、登录、密码找回和权限控制等功能。通过自定义表单身份验证,开发者可以创建符合特定业务需求的用户验证...

    Asp.net 2.0模块四

    C24 - "Asp.net 2.0 Membership and Roles" 这个部分主要讲解Asp.NET 2.0中的成员资格(Membership)和角色(Roles)管理。成员资格提供了一种安全且灵活的方式来管理用户账户,允许开发者轻松地添加注册、登录、...

    ASP.NET/C#企业库存管理系统

    此外,系统可能还会集成其他微软技术,如Windows Authentication进行身份验证,或者使用ASP.NET Membership和Roles提供用户管理和权限控制。 总之,ASP.NET/C#企业库存管理系统利用了现代Web技术和.NET框架的优势,...

    membership(access版)

    1. **配置Access数据库**:设置数据库表结构以匹配ASP.NET Membership所需的模式,如AspNet_Users, AspNet_Roles, AspNet_Membership等。 2. **创建自定义MembershipProvider**:在代码中创建一个新的类,继承自`...

    Apress - Pro ASP.NET 3.5 in C# 2008, 2nd Edition (Nov 2007)

    此外,还会介绍ASP.NET Membership、Roles和Profile,这些是用于处理用户认证和授权的内置服务,对于构建安全的Web应用至关重要。 通过对《精通ASP.NET 3.5,C# 2008版(第二版)》的学习,读者将能够熟练掌握ASP...

    Asp.Net2.0网站开发实战.iso

    4. **会员和角色管理**:为了支持网站的身份验证和授权,Asp.Net 2.0引入了 Membership 和 Roles API,可以方便地实现用户注册、登录、权限控制等功能。 5. **状态管理**:包括ViewState、Session、Cookie等机制,...

    ASP.NET管理系统

    ASP.NET管理系统是一个基于微软.NET Framework开发的Web应用程序,主要用于实现系统的后台管理功能。在这个系统中,权限管理是一个核心部分,它允许管理员精确控制用户对不同功能甚至具体到按钮级别的访问权限。这样...

    Asp.net数据访问

    5. ASP.NET Membership和Roles:这两个组件提供了用户身份验证和角色管理功能,可以方便地构建安全的Web应用程序。Membership用于用户注册、登录和权限控制,Roles则用于管理用户的角色分配和权限。 6. GridView和...

    asp.net实现小区物业内部管理网

    【ASP.NET 2.0 实现小区物业内部管理网】 ASP.NET 2.0 是微软推出的Web应用程序开发框架,用于构建高效、可扩展且易于维护的动态网站。在这个项目中,我们将探讨如何利用ASP.NET 2.0的技术特性来创建一个小区物业...

    ASP.NET 类库

    8. **System.Web.Security**: 这个命名空间提供了用户认证和授权的类,如FormsAuthentication、Membership、Roles等,用于实现网站的安全性。 9. **System.Web.UI.HtmlControls** 和 **System.Web.UI.WebControls....

    asp.net用户验证系统

    ASP.NET的SQL Server Membership Provider可以自动创建这些表。 6. **角色管理**: 除了用户验证,还可以通过角色管理控制不同用户组的权限。ASP.NET的角色框架允许创建和管理角色,并将用户分配到这些角色。 7. ...

    权限管理系统 asp.net

    3. 动态生成TREEVIEW:TREEVIEW控件是ASP.NET中的服务器控件,常用于展现层次结构的数据。在这个系统中,动态生成TREEVIEW意味着在运行时根据后台数据生成节点,这样可以根据权限动态调整显示的内容。这通常涉及到...

    ASP.net开发大全

    1. Membership和Roles:ASP.NET 2.0引入了Membership和Roles机制,方便用户管理和权限控制。书中会详细讲解这两个特性的使用。 2. Profile:ASP.NET 2.0中的Profile允许开发者存储和检索用户的个性化设置。书中会...

    ASP.NET 2.0电子商务开发实战

    ASP.NET 2.0引入了Membership和Roles API,使得用户注册、登录、角色分配变得简单。这部分内容会教授如何使用这些工具构建安全的用户管理系统。 4. **状态管理**:电子商务网站需要处理大量的用户交互和数据交换,...

    web应用开发asp.net 2.0 复习资料

    ASP.NET 2.0是微软推出的用于构建Web应用程序的框架,它是.NET Framework的一部分,提供了丰富的功能和工具,使得开发者能够高效地创建动态、交互式的Web应用程序。本复习资料旨在帮助初学者深入理解ASP.NET 2.0的...

Global site tag (gtag.js) - Google Analytics