详细答案示例
经过一般讨论后,这是一个详细的示例建立传输安全+简单密码(在 IIS、本地或 Azure 中我刚刚测试过)
这是非常simple.
- 没有角色,没有基于身份的声明性或程序性控制。
- 身份是硬编码的。
- 没有使用更强的消息安全性(中间人)。
- 传输安全性是最低的,因为基本身份验证不安全。
该安全场景实施起来很困难
1. 创建具有传输安全性的 Web 服务
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicBindingConfiguration">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="HelloServiceLibrary.HelloService" behaviorConfiguration="customIdentificationBehavior">
<endpoint address=""
binding="basicHttpBinding"
contract ="HelloServiceLibrary.IHelloService"
name="basicEndpoint"
bindingConfiguration="BasicBindingConfiguration">
</endpoint>
2. 声明一个模块来查找Basic-Auth
<system.webServer>
<modules>
<add name="BasicAuthenticationModule"
type="Security.UserNameModuleAuthenticator,App_Code/Security" />
</modules>
</system.webServer>
3. 模块的实现:
public class UserNameModuleAuthenticator : IHttpModule{
...
public void OnAuthenticateRequest(object source, EventArgs eventArgs){
HttpApplication app = (HttpApplication)source;
string authStr = app.Request.Headers["Authorization"];
string username = ...; // from header
string password = ...; // from header
if (username == "gooduser" && password == "password")
{
app.Context.User = new GenericPrincipal(new GenericIdentity(username, "Custom Provider"), null);
}
else
{
DenyAccess(app);
return;
}
4 配置客户端通过基本身份验证
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicEndpoint">
<security mode="Transport" >
<transport clientCredentialType="Basic"
proxyCredentialType="None"
realm="" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://localhost/TransportUsernameService/HelloService.svc"
binding="basicHttpBinding" bindingConfiguration="basicEndpoint"
contract="SecureServiceReference.IHelloService" name="basicEndpoint" />
</client>
</system.serviceModel>
5. 客户端传递**凭证到服务器**
HelloServiceClient client = new HelloServiceClient("basicEndpoint",
new EndpointAddress("https://testsecurewebservice.azurewebsites.net/HelloService.svc"));
client.ClientCredentials.UserName.UserName = userName;
client.ClientCredentials.UserName.Password = password;
String msg = client.SayHello(userName);
可能的扩展
- 创建/管理一些用户(使用 ASP.Net Provider 或自定义库)
- 担任一些角色
- 对方法添加一些声明性权限,例如:
[PrincipalPermission(SecurityAction.Demand, Role = "Manager")]
完整的解决方案在这里:http://1drv.ms/1Q5j9w0 http://1drv.ms/1Q5j9w0
Regards