`
wyf
  • 浏览: 424923 次
  • 性别: 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.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 ...

    ASP.NET MVC in Action

    ASP.NET MVC in Action shows you how to test each piece of your ASP.NET application and how to introduce principles of test-driven development into your process. Because the framework is completely ...

    成员管理+MemberShip+Roles

    成员管理+MemberShip+Roles成员管理+MemberShip+Roles成员管理+MemberShip+Roles成员管理+MemberShip+Roles成员管理+MemberShip+Roles成员管理+MemberShip+Roles

    Authorization in ASP.Net MVC using XML Configuration.

    Asp.net MVC comes with built in Authorization filter attribute that you can use on your Controller and Action to define the role that can access corresponding Controller or Action. This approach will ...

    Membership和Roles类的使用

    Membership和Roles类的使用

    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 ...

    2.ASP.NET.2.0.高级编程(第4版) [1/7]

    2.ASP.NET.2.0.高级编程(第4版) [1/7] 原书名: Professional ASP.NET 2.0 原出版社: Wrox 作者:(美)Bill Evjen, Scott Hanselman, Farhan Muhammad [同作者作品] [作译者介绍] 译者: 李敏波[同译者作品] ...

    ASP.NET Core 1.1 For Beginners: How to Build a MVC Website

    If you are already familiar with MVC 5, the content in this book can get you started with ASP.NET Core 1.1 in a fast, no-fluff way. It's important to mention that this book is practical and tactical,...

    适合初学的asp.net网上书店系统eshop

    网站采用asp.net 用户角色配置(membership,UserRoles),用户角色、权限可在asp.net配置里修改,注册,登陆均采用asp.net登陆控件,网站根据用户角色自定义sitemap,基本上使用了asp.net用户角色的所有新特性。...

    《零基础学ASP.NET 2.0》第18章 ASP.NET 2.0的安全性

    18.1 ASP.NET 2.0 的潜在威胁 312 18.2 使用基于表单的身份验证 312 18.2.1 启用并配置表单身份验证 313 18.2.2 建立登录页面 314 18.2.3 创建资源提供页 316 18.3 Windows身份验证 318 18.4 成员资格和角色管理 318...

    零基础学ASP.NET 2.0电子书&源代码绝对完整版1

    示例描述:本章演示ASP.NET 2.0网站的预编译以及学习ASP.NET 2.0的前置知识。 WebSite文件夹 创建的ASP.NET 2.0 Web站点。 www文件夹 第一个用C#开发的Web应用程序。 bianyi.bat 编译网站的批处理文件。 ...

    Create-Users-Roles-Using-ASP.NET-Membership:您可以使用ASP.NET成员资格表创建用户和角色

    我们正在使用ASP.NET成员资格表来创建角色,创建用户 您可以使用ASP.NET成员资格表创建用户和角色 在您SQL数据库中创建ASP.NET成员资格表。 您将必须在计算机上运行(aspnet_regsql.exe)。 您可以在以下位置找到该...

    ASP.NET2.0高级编程(第4版)1/6

    本书全面介绍了ASP.NET各种编程技能和2.0版中的巨大变化,并详细阐述了2.0版中的每个新特性。书中提供了大量的实例,可帮助读者快速掌握如何在.NET平台下开发功能强大的ASP.NET应用程序。本书适合有一些基础的ASP...

    PortSight Secure Access v4.3.3012 Enterprise Edition

    ASP.NET 2.0 Membership provider authenticates users against a store of users, the Role provider authorizes users to perform actions based on roles they have been assigned and the Profile provider ...

    天轰穿系列教程之-75成员管理 MemberShip Roles

    天轰穿系列教程之-75成员管理 MemberShip Roles 天轰穿系列教程之-75成员管理 MemberShip Roles 天轰穿系列教程之-75成员管理 MemberShip Roles 天轰穿系列教程之-75成员管理 MemberShip Roles 天轰穿系列教程之-75...

    世界上最简单的ASP.net的Forms验证Demo

    如果只是为了完成任务,我用ASP就OK了,为什么还要用ASP.net,如果我们用.net时还用ASP的思路也得了,为什么还要研究ASP.net提供的东西。呵呵,不为什么,喜欢,我所做的正是我想做的,我不是为了完成一个任务,而是...

    NopCommerce (ASP.NET商城) v2.0.zip

    nopCommerce 是一个由ASP.NET多层模式开发的开源电子商城系统,可以自行设置模板、配置灵活、功能强大,它内含一个目录前端和一个管理工具后端。前端包括用户注册、商品购买(可以进行评论)、投票、Blog等,后端有...

    NopCommerce (ASP.NET商城) v2.0 源码包.zip

    nopCommerce 是一个由ASP.NET多层模式开发的开源电子商城系统,可以自行设置模板、配置灵活、功能强大,它内含一个目录前端和一个管理工具后端。前端包括用户注册、商品购买(可以进行评论)、投票、Blog等,后端有...

Global site tag (gtag.js) - Google Analytics