Juo*_*nis 5 authentication wcf
我有使用UserNamePasswordValidator进行自定义授权的WCF Web服务
public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
try
{
MySession session = new MySession(userName, password);
}
catch (UnauthorizedAccessException e)
{
throw new System.IdentityModel.Tokens.SecurityTokenException("Incorrect username or password");
}
}
}
Run Code Online (Sandbox Code Playgroud)
身份验证工作正常,但我不知道如何将CustomUserNameValidator中创建的会话转移到服务.
如果您想知道,MySession来自第三方API.
在对我的网络服务进行了多次迭代之后,我对我的问题得出了可接受的答案。如果有人把这个答案打出来,我会立即接受。
不要使用用户名密码验证器。将您的服务配置为使用传输安全性,并将 clientCredentialType 设置为“None”。在 Web 服务方法中,要做的第一件事是使用从 WebOperationContext.Current 中提取的凭据创建一个会话,例如如下所示:
WebOperationContext operationContext = WebOperationContext.Current;
string encoded = operationContext.IncomingRequest.Headers[HttpRequestHeader.Authorization];
if (encoded != null)
{
var decoded = Convert.FromBase64String(encoded.Substring(encoded.LastIndexOf("Basic ") + 6));
var headerValue = Encoding.UTF8.GetString(decoded);
string userName = headerValue.Substring(0, headerValue.IndexOf(":"));
string password = headerValue.Substring(headerValue.IndexOf(":") + 1, headerValue.Length - userName.Length - 1);
if (ValidCredentials(userName, password)
return new MySession(userName, password);
}
operationContext.OutgoingResponse.Headers.Add(HttpResponseHeader.WwwAuthenticate,
String.Format("Basic realm =\"MyRealm\"", Settings.EBCommunity));
throw new WebFaultException(HttpStatusCode.Unauthorized);
Run Code Online (Sandbox Code Playgroud)
这样,Web 服务可以轻松地自托管或托管在 IIS 上,并且避免了UserNamePasswordValidator http 协议问题。
| 归档时间: |
|
| 查看次数: |
906 次 |
| 最近记录: |