摘要:WCF使用ASP.NET Form驗證要點
- Service端需要設定 aspNetCompatibilityEnabled="true"
- Service需要加上attribute [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
- 每個operation加上適當的PrincipalPermissionAttribute
- 在Service加上一個Login的operation以回傳FormsAuthenticationTicket 字串
- 準備一個自訂義的IAuthorizationPolicy 類別
-
在ServiceBehaviors中加入
<serviceAuthorization principalPermissionMode="Custom"> <authorizationPolicies> <add policyType="{IAuthorizationPolicy的TypeName}" /> </authorizationPolicies> </serviceAuthorization>
-
使用Proxy時以類似以下的程式碼來呼叫
var serviceClient = new ServiceClient(); string cookie = serviceClient.Login("{帳號}", "{密碼}"); HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie, cookie); using (OperationContextScope scope = new OperationContextScope(serviceClient.InnerChannel)) { OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; serviceClient.DoSomething(); }
注意:cookie字串的格式需要是{key=value}的形式。