Autenticación básica del servicio web Asmx.
Quiero implementar la autenticación básica mediante la validación de nombre de usuario y contraseña en miasmx servicio web.
No quiero usar WCF y sé que esta no es una forma segura, pero necesito usar la autenticación básica sin usar https.
Mi servicio web es así:
[WebService(Namespace = "http://www.mywebsite.com/")]
public class Service1
{
[WebMethod]
public string HelloWorld()
{
return "Hello world";
}
}
Y utilizo este HttpModule personalizado:
public class BasicAuthHttpModule : IHttpModule
{
void IHttpModule.Init(HttpApplication context)
{
context.AuthenticateRequest += new EventHandler(OnAuthenticateRequest);
}
void OnAuthenticateRequest(object sender, EventArgs e)
{
string header = HttpContext.Current.Request.Headers["Authorization"];
if (header != null && header.StartsWith("Basic")) //if has header
{
string encodedUserPass = header.Substring(6).Trim(); //remove the "Basic"
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass));
string[] credentials = userPass.Split(':');
string username = credentials[0];
string password = credentials[1];
if(!MyUserValidator.Validate(username, password))
{
HttpContext.Current.Response.StatusCode = 401;
HttpContext.Current.Response.End();
}
}
else
{
//send request header for the 1st round
HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", string.Empty));
}
}
void IHttpModule.Dispose()
{
}
}
Y en la web.config utilizo esto:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="None"/>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="BasicAuthHttpModule"
type="AuthService.BasicAuthHttpModule, AuthService" />
</modules>
</system.webServer>
</configuration>
El código de llamada es:
static void Main(string[] args)
{
var proxy = new Service1.Service1()
{
Credentials = new NetworkCredential("user1", "p@ssw0rd"),
PreAuthenticate = true
};
try
{
var result = proxy.HelloWorld();
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
Cuando uso este servicio web, el servicio solicita una autenticación básica, peroheader
variable en elOnAuthenticateRequest
El método siempre es nulo yMyUserValidator.Validate()
nunca corras.
EDITAR
Los resultados del violinista:
POST http://www.mywebsite.com/Service1.asmx HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4927)
VsDebuggerCausalityData: uIDPo+drc57U77xGu/ZaOdYvw6IAAAAA8AjKQNpkV06FEWDEs2Oja2C+h3kM7dlDvnFfE1VlIIIACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://www.mywebsite.com/HelloWorld"
Host: www.mywebsite.com
Content-Length: 291
Expect: 100-continue
Connection: Keep-Alive
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorld xmlns="http://www.mywebsite.com/" /></soap:Body></soap:Envelope>
HTTP/1.1 401 Unauthorized
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
WWW-Authenticate: Basic realm=""
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Basic realm="www.mywebsite.com"
X-Powered-By: ASP.NET
Date: Sun, 03 Jun 2012 07:14:40 GMT
Content-Length: 1293
------------------------------------------------------------------
POST http://www.mywebsite.com/Service1.asmx HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4927)
VsDebuggerCausalityData: uIDPo+drc57U77xGu/ZaOdYvw6IAAAAA8AjKQNpkV06FEWDEs2Oja2C+h3kM7dlDvnFfE1VlIIIACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://www.mywebsite.com/HelloWorld"
Authorization: Basic dXNlcjE6cEBzc3cwcmQ=
Host: www.mywebsite.com
Content-Length: 291
Expect: 100-continue
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorld xmlns="http://www.mywebsite.com/" /></soap:Body></soap:Envelope>
HTTP/1.1 401 Unauthorized
Content-Type: text/html
Server: Microsoft-IIS/7.5
WWW-Authenticate: Basic realm="www.mywebsite.com"
X-Powered-By: ASP.NET
Date: Sun, 03 Jun 2012 07:14:41 GMT
Content-Length: 1293
------------------------------------------------------------------