博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
asmx-web-service-basic-authentication
阅读量:5899 次
发布时间:2019-06-19

本文共 5203 字,大约阅读时间需要 17 分钟。

//-----------------------------------------------------

public class BasicAuthHttpModule:IHttpModule

{
   
voidIHttpModule.Init(HttpApplication context)
   
{
        context
.AuthenticateRequest+=newEventHandler(OnAuthenticateRequest);
   
}
   
voidOnAuthenticateRequest(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));
       
}
   
}
   
voidIHttpModule.Dispose()
   
{
   
}
}

staticvoidMain(string[] args)

{
   
var proxy =newService1.Service1()
                   
{
                       
Credentials=newNetworkCredential("user1","p@ssw0rd"),
                       
PreAuthenticate=true
                   
};
   
try
   
{
       
var result = proxy.HelloWorld();
       
Console.WriteLine(result);
   
}
   
catch(Exception e)
   
{
       
Console.WriteLine(e.Message);
   
}
   
Console.ReadKey();
}

The fiddler results:

POST http://www.mywebsite.com/Service1.asmx HTTP/1.1User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4927)VsDebuggerCausalityData: uIDPo+drc57U77xGu/ZaOdYvw6IAAAAA8AjKQNpkV06FEWDEs2Oja2C+h3kM7dlDvnFfE1VlIIIACQAAContent-Type: text/xml; charset=utf-8SOAPAction: "http://www.mywebsite.com/HelloWorld"Host: www.mywebsite.comContent-Length: 291Expect: 100-continueConnection: Keep-Alive
HTTP/1.1 401 UnauthorizedCache-Control: privateContent-Type: text/htmlServer: Microsoft-IIS/7.5WWW-Authenticate: Basic realm=""X-AspNet-Version: 4.0.30319WWW-Authenticate: Basic realm="www.mywebsite.com"X-Powered-By: ASP.NETDate: Sun, 03 Jun 2012 07:14:40 GMTContent-Length: 1293------------------------------------------------------------------POST http://www.mywebsite.com/Service1.asmx HTTP/1.1User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4927)VsDebuggerCausalityData: uIDPo+drc57U77xGu/ZaOdYvw6IAAAAA8AjKQNpkV06FEWDEs2Oja2C+h3kM7dlDvnFfE1VlIIIACQAAContent-Type: text/xml; charset=utf-8SOAPAction: "http://www.mywebsite.com/HelloWorld"Authorization: Basic dXNlcjE6cEBzc3cwcmQ=Host: www.mywebsite.comContent-Length: 291Expect: 100-continue
HTTP/1.1 401 UnauthorizedContent-Type: text/htmlServer: Microsoft-IIS/7.5WWW-Authenticate: Basic realm="www.mywebsite.com"X-Powered-By: ASP.NETDate: Sun, 03 Jun 2012 07:14:41 GMTContent-Length: 1293

 

 

//---------------------------------------------------------------

publicclassBasicAuthHttpModule:IHttpModule

{
   
publicvoidDispose()
   
{
   
}
   
public void Init(HttpApplication application)
   
{
application.AuthenticateRequest+=new
           
EventHandler(this.OnAuthenticateRequest);
        application
.EndRequest+=new
           
EventHandler(this.OnEndRequest);
   
}
   
public void OnAuthenticateRequest(object source,EventArgs
                        eventArgs
)
   
{
       
HttpApplication app =(HttpApplication)source;
       
string authHeader = app.Request.Headers["Authorization"];
       
if(!string.IsNullOrEmpty(authHeader))
       
{
           
string authStr = app.Request.Headers["Authorization"];
           
if(authStr ==null|| authStr.Length==0)
           
{
               
return;
           
}
            authStr
= authStr.Trim();
           
if(authStr.IndexOf("Basic",0)!=0)
           
{
               
return;
           
}
            authStr
= authStr.Trim();
           
string encodedCredentials = authStr.Substring(6);
           
byte[] decodedBytes =
           
Convert.FromBase64String(encodedCredentials);
           
string s =newASCIIEncoding().GetString(decodedBytes);
           
string[] userPass = s.Split(newchar[]{
':'});
           
string username = userPass[0];
           
string password = userPass[1];
           
if(!MyUserValidator.Validate(username, password))
           
{
               
DenyAccess(app);
               
return;
           
}
       
}
       
else
       
{
            app
.Response.StatusCode=401;
            app
.Response.End();
       
}
   
}
   
publicv oid OnEndRequest(object source,EventArgs eventArgs)
   
{
       
if(HttpContext.Current.Response.StatusCode==401)
       
{
           
HttpContext context =HttpContext.Current;
            context
.Response.StatusCode=401;
            context
.Response.AddHeader("WWW-Authenticate","Basic Realm");
       
}
   
}
   
private void DenyAccess(HttpApplication app)
   
{
        app
.Response.StatusCode=401;
        app
.Response.StatusDescription="Access Denied";
        app
.Response.Write("401 Access Denied");
        app
.CompleteRequest();
   
}
}

//--------------------------------------------------------

 string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus";

    HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
    string user = "ricks";
    string pwd = "secret";
    string domain = "www.west-wind.com";
    string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
    req.PreAuthenticate = true;
    req.Headers.Add("Authorization", auth);
    req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
    WebResponse resp = req.GetResponse();
    resp.Close();

//-----------------------------------------------------

转载地址:http://rehsx.baihongyu.com/

你可能感兴趣的文章
抓屏原理
查看>>
UNIX网络编程读书笔记:TCP输出、UDP输出和SCTP输出
查看>>
扩展 DbUtility (1)
查看>>
iOS开发UI篇—使用picker View控件完成一个简单的选餐应用
查看>>
Apple Developer Registration and DUNS Number Not Accepted
查看>>
Hadoop学习笔记系列文章导航
查看>>
不同页面之间实现参数传递的几种方式讨论
查看>>
SpringMVC中ModelAndView addObject()设置的值jsp取不到的问题
查看>>
Prometheus : 入门
查看>>
使用 PowerShell 创建和修改 ExpressRoute 线路
查看>>
PHP如何学习?
查看>>
谈教育与成长
查看>>
jni c++
查看>>
在C#中获取如PHP函数time()一样的时间戳
查看>>
Redis List数据类型
查看>>
大数据项目实践(四)——之Hive配置
查看>>
初学vue2.0-组件-文档理解笔记v1.0
查看>>
NG-ZORRO-MOBILE 0.11.9 发布,基于 Angular 7 的 UI 组件
查看>>
我就是一个救火员(DBA救援)
查看>>
Centos7安装Gitlab10.0
查看>>