如何在WCF服务中使用角色管理器?
在我的.NET应用程序中,我可以使用[Authorize(Roles=)]
标记限制类或方法。如何为我的WCF服务启用此功能?
我目前为每个端点设置了以下绑定:
<webHttpBinding>
<binding name="TransportSecurity" maxReceivedMessageSize="5242880">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</webHttpBinding>
由于我希望用户登录并接收带主体的cookie,我是否需要将其更改为另一种clientCredentialType
?
修改1:
这是使用REST,而不是SOAP。还需要注意的是,它适用于移动设备(Android,iPhone)并且可以使用cookie来维护会话。到目前为止,我无法使用以下代码/配置来实现此功能:
配置文件:
<roleManager enabled="true" defaultProvider="ActiveDirectoryRoleProvider" cacheRolesInCookie="true" cookieName="RoleCookie" cookiePath="/" cookieTimeout="30" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieProtection="All">
<providers>
<clear />
<add name="ActiveDirectoryRoleProvider" connectionStringName="ADServices" connectionUsername="" connectionPassword="" attributeMapUsername="sAMAccountName" type="" />
</providers>
</roleManager>
<membership defaultProvider="MembershipADProvider">
<providers>
<add name="MembershipADProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" applicationName="" connectionStringName="ADServices" connectionUsername="" connectionPassword="" attributeMapUsername="sAMAccountName" />
</providers>
</membership>
<bindings>
<webHttpBinding> <!-- webHttpBinding is for REST -->
<binding name="TransportSecurity" maxReceivedMessageSize="5242880">
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
<serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="ActiveDirectoryRoleProvider" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="MembershipADProvider" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
代码
public void SignIn2(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
// put the attributes in a string for userdata
string userData = "";
// create the ticket
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(240),
createPersistentCookie,
userData);
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
// add the cookie
HttpContext.Current.Response.Cookies.Add(authCookie);
}
现在使用Principal Permission ,我得到SecurityException
(我知道该角色在服务器上有效)
[PrincipalPermission(SecurityAction.Demand, Role = Constants.RoleUser)]
public Message TestRoles()
{
var context = NetworkHelper.GetWebOperationContext();
return context.CreateTextResponse("You have successfully activated the endpoint.");
}
我错过了关键的一步吗?
答案 0 :(得分:9)
我写了关于如何在WCF中使用ASP.NET身份验证的a blog post;它的要点是你想使用以下绑定:
<basicHttpBinding>
<binding>
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
您还必须应用以下serviceBehavior
<behavior>
<!-- no need for http get;
but https get exposes endpoint over SSL/TLS-->
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
<!-- the authorization and credentials elements tie
this behavior (defined as the default behavior) to
the ASP.NET membership framework-->
<serviceAuthorization
principalPermissionMode="UseAspNetRoles"
roleProviderName="AspNetRoleProvider" />
<serviceCredentials>
<userNameAuthentication
userNamePasswordValidationMode="MembershipProvider"
membershipProviderName="AspNetMembershipProvider" />
</serviceCredentials>
</behavior>
需要注意的一点是,如果要使用名称和密码保护WCF,则必须使用SSL,这就是指定传输安全性的原因。
完成此操作后,您应该可以使用PrincipalPermission
属性来保护您的服务方法。
答案 1 :(得分:3)
我。你必须添加2个辅助类:
using System.Web;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
namespace TicketingCore
{
public class HttpContextPrincipalPolicy : IAuthorizationPolicy
{
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
HttpContext context = HttpContext.Current;
if (context != null)
{
evaluationContext.Properties["Principal"] = context.User;
}
return true;
}
public System.IdentityModel.Claims.ClaimSet Issuer
{
get { return ClaimSet.System; }
}
public string Id
{
get { return "TicketingCore HttpContextPrincipalPolicy"; }
}
}
}
using System;
using System.Collections.Generic;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Text;
using System.Web;
using System.Security.Principal;
namespace TicketingCore
{
// syncs ServiceSecurityContext.PrimaryIdentity in WCF with whatever is set
// by the HTTP pipeline on Context.User.Identity (optional)
public class HttpContextIdentityPolicy : IAuthorizationPolicy
{
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
HttpContext context = HttpContext.Current;
if (context != null)
{
// set the identity (for PrimaryIdentity)
evaluationContext.Properties["Identities"] =
new List<IIdentity>() { context.User.Identity };
// add a claim set containing the client name
Claim name = Claim.CreateNameClaim(context.User.Identity.Name);
ClaimSet set = new DefaultClaimSet(name);
evaluationContext.AddClaimSet(this, set);
}
return true;
}
public System.IdentityModel.Claims.ClaimSet Issuer
{
get { return ClaimSet.System; }
}
public string Id
{
get { return "TicketingCore HttpContextIdentityPolicy"; }
}
}
}
II。更改webconfig以添加这两个策略,这是我的配置(格式:add policyType =“namespace.class,assembly”)
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="SQLMembershipProvider"/>
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="TicketingCore.HttpContextIdentityPolicy, TicketingCore"/>
<add policyType="TicketingCore.HttpContextPrincipalPolicy, TicketingCore"/>
</authorizationPolicies>
</serviceAuthorization>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
III。确保cookie和角色正常运行
注意:我也不记得解决方案的来源,你可能需要谷歌的类名来查找,希望对你有所帮助,祝你好运!
答案 2 :(得分:2)
我认为这样的事情会提供你想要的东西:
// Only members of the SpecialClients group can call this method.
[PrincipalPermission(SecurityAction.Demand, Role = "SpecialClients")]
public void DoSomething()
{
}
您可以在此处找到有关设置服务的不同选项的好文章:MSDN Article。您可能希望使用以下内容更新配置:
<security mode="TransportWithMessageCredential" >
<transport clientCredentialType="Windows" />
</security>
答案 3 :(得分:2)
两年前,我在博客上发表了与表单身份验证和主要权限属性的wcf集成。我相信你会觉得这很有用:
http://netpl.blogspot.com/2010/04/aspnet-forms-authentication-sharing-for.html
答案 4 :(得分:1)
查看此问题Passing FormsAuthentication cookie to a WCF service。重点是由于cookie域/ asp设置/ auth加密密钥,无法发送或接收验证cookie。我建议您为了调试目的而转储该cookie值Request.Cookies [“。ASPXAUTH”]。