日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

WCF安全之ASP.NET兼容模式

發布時間:2023/11/29 asp.net 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 WCF安全之ASP.NET兼容模式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文是利用ASP.NET兼容模式實現WCF安全的一個完整示例,其中用到了ASP.NET的Forms身份驗證及Membership,并啟用了角色管理。

由于整套安全方案完全利用ASP.NET相關功能實現,而未用到WCF安全策略相關的包括WCF身份驗證、WCF授權及WCF傳輸安全等元素,所以嚴格的說,這種模式不能算是WCF的安全模式,但該方案確實實現了特定應用場景下的WCF安全。

相比而言,該方案提供的安全程度比WCF的安全策要低一些(例如,未提供全過程的數據傳輸安全),因此,本方案適應對安全性要求不高的,以IIS為宿主的WCF應用。

本方案中的WCF服務需要以IIS為宿主,可以通過添加“啟用Silverlight功能的WCF服務”的方式建立WCF服務。客戶端為Silverlight,并在訪問WCF服務時使用了Visual Studio 2008自動生成的代理類。

1、建立項目

通過創建“Silverlight應用程序”建立新的項目WcfSecSample,并建立承載該Silverlight的網站WcfSecSample.Web。

2、在Web項目中建立Service目錄,并在該目錄下添加WCF服務WeatherService,服務類的完整代碼如下:

using System; using System.Linq; using System.Runtime.Serialization; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Activation; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.Security;namespace WcfSecSample.Web {[ServiceContract(Namespace = "")][AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]public class WeatherService{private static string s_weather = "Sunny";[OperationContract]public void SetWeather(string weather){if (!HttpContext.Current.User.IsInRole("Admin")) throw new ApplicationException("無權限。");s_weather = weather;}[OperationContract]public string GetWeather(){if (!HttpContext.Current.User.IsInRole("Guest")) throw new ApplicationException("無權限。");return s_weather;}} }

3、在Web項目中添加用于登錄的WCF服務LoginService,該服務類的完整代碼如下:

using System; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.Collections.Generic; using System.Text; using System.Web.Security;namespace WcfSecSample.Web {[ServiceContract(Namespace = "")][AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]public class LoginService{[OperationContract]public bool Login(string userName, string password){bool isValid = Membership.ValidateUser(userName, password);if (isValid) FormsAuthentication.SetAuthCookie(userName, false);return isValid;}[OperationContract]public void SignOut(){FormsAuthentication.SignOut();}} }

4、在Web項目中添加繼承自MembershipProvider類的CustomerMembershipProvider類,暫時只實現了本方案所需要的ValidateUser方法。ValidateUser方法的代碼如下:

public override bool ValidateUser(string username, string password){return username == "admin" && password == "123456" || username == "guest";}

5、在Web項目中添加繼承自RoleProvider類的CustomRoleProvider類,暫時只實現了本方案所需要的GetRolesForUser方法。GetRolesForUser方法的代碼如下:

public override string[] GetRolesForUser(string username){if (username == "admin") return new []{"Admin", "Guest"};return new[] { "Guest" };}

需要注意的是,雖然憑感覺HttpContext.Current.User.IsInRole方法應該最終調用RoleProvider類的IsUserInRole方法,但事實卻是最終調用了RoleProvider類的GetRolesForUser方法完成的。if (!HttpContext.Current.User.IsInRole("Admin"))還可以換成if (Roles.IsUserInRole(HttpContext.Current.User.Identity.Name, "Admin")),同樣是最終調用了RoleProvider類的GetRolesForUser方法。

6、配置Web.config文件

在system.web節內添加如下內容:

<authentication mode="Forms" ><forms name=".sec" loginUrl="LoginService.svc"></forms></authentication><membership defaultProvider="default"><providers><add name="default" type="WcfSecSample.Web.CustomerMembershipProvider, WcfSecSample.Web"/></providers></membership><roleManager defaultProvider="default" enabled="true"><providers><add name="default" type="WcfSecSample.Web.CustomRoleProvider, WcfSecSample.Web"/></providers></roleManager>

以上三節內容分別配置了身份驗證模式、MembershipProvider及RoleProvider。

然后在示例服務所在的Service目錄下添加Web.config文件,禁止對Service目錄的匿名訪問。該文件的內容如下:

<?xml version="1.0" encoding="utf-8"?> <configuration><system.web><authorization><deny users="?"/></authorization></system.web> </configuration>

至此,服務端的工作就完成了,接下來建立客戶端測試示例。

7、添加服務引用。

在Silverlight項目中添加對WeatherService的服務引用WeatherServiceRef。需注意的是進行該操作時需要暫時允許對Service目錄的匿名訪問。

8、在MainPage中添加測試代碼。完成之后的代碼如下:

MainPage.xaml文件:

<UserControl x:Class="WcfSecSample.MainPage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"><Grid x:Name="LayoutRoot" Width="200" Margin="100" ><Grid.RowDefinitions><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="*"></RowDefinition></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="Auto" ></ColumnDefinition><ColumnDefinition Width="*" ></ColumnDefinition></Grid.ColumnDefinitions><TextBlock Grid.Row="0" Grid.Column="0" Margin="5">UserName:</TextBlock><TextBox Grid.Row="0" Grid.Column="1" Margin="5" Name="txtUserName" Text="admin" ></TextBox><TextBlock Grid.Row="1" Grid.Column="0" Margin="5">Password:</TextBlock><TextBox Grid.Row="1" Grid.Column="1" Margin="5" Name="txtPassword" Text="123456"></TextBox><Button Name="btnLogin" Grid.Row="2" Grid.ColumnSpan="2" Margin="5" Content="Login" Click="Login"></Button><Button Name="btnSignOut" Grid.Row="3" Grid.ColumnSpan="2" Margin="5" Content="SignOut" Click="SignOut"></Button><Button Name="btnSetWeather" Grid.Row="4" Grid.ColumnSpan="2" Margin="5" Content="SetWeather" Click="SetWeather"></Button><Button Name="btnGetWeather" Grid.Row="5" Grid.ColumnSpan="2" Margin="5" Content="GetWeather" Click="GetWeather"></Button></Grid> </UserControl>

MainPage.xaml.cs文件:

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using WcfSecSample.LoginServiceRef; using WcfSecSample.WeatherServiceRef;namespace WcfSecSample {public partial class MainPage : UserControl{public MainPage(){InitializeComponent();this.IsLogin = false;this.client.SetWeatherCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_SetWeatherCompleted);this.client.GetWeatherCompleted += new EventHandler<GetWeatherCompletedEventArgs>(client_GetWeatherCompleted);this.loginClient.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(loginClient_LoginCompleted);this.loginClient.SignOutCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(loginClient_SignOutCompleted);}private bool isLogin;private WeatherServiceClient client = new WeatherServiceClient();private LoginServiceClient loginClient = new LoginServiceClient();private bool IsLogin{get { return isLogin; }set{isLogin = value;this.btnLogin.IsEnabled = !isLogin;this.btnSignOut.IsEnabled = isLogin;}}private void Login(object sender, RoutedEventArgs e){this.loginClient.LoginAsync(this.txtUserName.Text, this.txtPassword.Text);}private void SignOut(object sender, RoutedEventArgs e){this.loginClient.SignOutAsync();}private void GetWeather(object sender, RoutedEventArgs e){this.client.GetWeatherAsync();}private void SetWeather(object sender, RoutedEventArgs e){this.client.SetWeatherAsync("Cloudy");}void loginClient_LoginCompleted(object sender, LoginCompletedEventArgs e){if (e.Error == null){MessageBox.Show(e.Result ? "Login succeed." : "Login faild.");this.IsLogin = e.Result;}else{MessageBox.Show(e.Error.Message);}}void loginClient_SignOutCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e){if (e.Error == null){MessageBox.Show("SignOut.");this.IsLogin = false;}else{MessageBox.Show(e.Error.Message);}}void client_GetWeatherCompleted(object sender, GetWeatherCompletedEventArgs e){if (e.Error == null) MessageBox.Show(e.Result);else MessageBox.Show(e.Error.Message);}void client_SetWeatherCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e){if (e.Error == null){MessageBox.Show("Set weather succeed.");}else{MessageBox.Show(e.Error.Message);}}} }

為了測試登錄對訪問服務的影響,以上代碼并未根據登錄狀態對SetWeather、GetWeather按鈕的可用性進行控制。

運行示例,可以看到在登錄之前訪問WeatherService是不成功的,如果用Admin角色的賬號登錄之后可以SetWeather或GetWeather,如果用Guest角色的賬號登錄則只能GetWeather。登錄并調用GetWeather的效果圖如下:

示例測試環境:

操作系統:Windows7

開發環境:Visual Studio 2008 + Silverlight 3

IIS:7.5

瀏覽器:IE8

轉載于:https://www.cnblogs.com/chinadhf/archive/2010/04/29/1724388.html

總結

以上是生活随笔為你收集整理的WCF安全之ASP.NET兼容模式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。