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

    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.NET2.0数据库项目案例导航

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

    ASP.NET课程大纲

    此外,会员认证(Membership)和角色管理(Roles)让开发者可以实现用户身份验证和权限控制。 课程还涉及到Web服务(WebService)的相关技能,让学生理解服务接口的创建和调用,以及如何利用Ajax技术实现客户端的无...

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

    Asp 3.5 与 Vs2008 新手入门

    - **Login & Security**:登录控件(Login)、身份验证(Membership)、角色管理(Roles)和用户配置文件(Profile)为网站提供了安全性和个性化设置。 - **Navigation**:Menu和TreeView控件用于构建网站的导航...

    微软vs2005和vs2008技术教程下载工具

    5. **ASP.NET 2.0**:Web应用程序开发得到极大提升,引入了母版页、控件生命周期改进和 membership/roles/profiles 等新特性。 6. **ADO.NET Entity Framework**:初步引入,为数据访问提供了一种面向对象的方式,...

Global site tag (gtag.js) - Google Analytics