我当前的WCF REST方法定义为:
[OperationContract]
[WebGet(UriTemplate = "{username}/{password}", ResponseFormat =
WebMessageFormat.Json)]
string Login(string username, string password);
一个android客户端应用程序将连接到该服务,假设它是http://service.com/login.svc/login ...
但是我不希望像在UriTemplate中指定的那样在URL中传递用户名和密码。如何从android应用接收用户名和密码到服务中,或者更好的是,如何更改登录方法以检索某些POST参数中的用户名和密码,我可以在登录功能中处理该参数并验证用户身份sql成员数据库。
最佳答案
我们通过使用“ Authorization”标头来完成此操作。客户传递一组加密的凭据,然后我们会为他们生成令牌。这是处理身份验证的HttpModule的BeginRequest方法的示例。我们使用自定义主体来处理令牌:
private void BeginRequest(Object source, EventArgs e)
{
if (null == HttpContext.Current || String.IsNullOrEmpty(HttpContext.Current.Request.Headers["Authorization"]))
{
HttpContext.Current.Response.StatusCode = (Int32)HttpStatusCode.Unauthorized;
HttpContext.Current.Response.End();
}
HttpContext context = HttpContext.Current;
Regex matcher = new Regex(WfmConfigurationManager.GetAppSetting("AuthenticationPath"));
if (!matcher.IsMatch(context.Request.Url.ToString(),0))
{
String authHeader = context.Request.Headers["Authorization"];
IIdentity tokenIdentity = new TokenIdentity(authHeader);
if (!tokenIdentity.IsAuthenticated)
{
HttpContext.Current.Response.StatusCode = (Int32)HttpStatusCode.Unauthorized;
HttpContext.Current.Response.End();
}
IPrincipal tokenPrincipal = new TokenPrincipal(tokenIdentity, TokenAuthentication.GetRolesForUser(tokenIdentity));
HttpContext.Current.User = tokenPrincipal;
}
}