HTTP BASIC 应用(2)

本文介绍了一种使用HTTP Basic认证机制实现用户验证的方法。通过解析HTTP请求头中的Authorization字段,提取并解码Base64格式的用户名及密码,进而验证用户身份。文章提供了不同语言环境下实现Basic认证的具体代码示例。
publicclassUserAuthenticator:IHttpModule
{
   
publicvoidDispose()
   
{
   
}

   
publicvoidInit(HttpApplication application)
   
{
        application
.AuthenticateRequest+=newEventHandler(this.OnAuthenticateRequest);
        application
.EndRequest+=newEventHandler(this.OnEndRequest);
   
}

   
publicvoidOnAuthenticateRequest(object source,EventArgs eventArgs)
   
{
       
HttpApplication app =(HttpApplication)source;

       
// Get the request stream
       
Stream httpStream = app.Request.InputStream;

       
// I converted the stream to string so I can search for a known substring
       
byte[] byteStream =newbyte[httpStream.Length];
        httpStream
.Read(byteStream,0,(int)httpStream.Length);
       
string strRequest =Encoding.ASCII.GetString(byteStream);

       
// This is the end of the initial SOAP envelope
       
// Not sure if the fastest way to do this but works fine
       
int idx = strRequest.IndexOf("</t:RequestSecurityToken></s:Body></s:Envelope>",0);
        httpStream
.Seek(0,SeekOrigin.Begin);
       
if(idx !=-1)
       
{
           
// Initial packet found, do nothing (HTTP status code is set to 200)
           
return;
       
}

       
//the Authorization header is checked if present
       
string authHeader = app.Request.Headers["Authorization"];
       
if(!string.IsNullOrEmpty(authHeader))
       
{
           
if(authHeader ==null|| authHeader.Length==0)
           
{
               
// No credentials; anonymous request
               
return;
           
}

            authHeader
= authHeader.Trim();
           
if(authHeader.IndexOf("Basic",0)!=0)
           
{
               
// the header doesn't contain basic authorization token
               
// we will pass it along and
               
// assume someone else will handle it
               
return;
           
}

           
string encodedCredentials = authHeader.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];
           
// the user is validated against the SqlMemberShipProvider
           
// If it is validated then the roles are retrieved from
           
// the role provider and a generic principal is created
           
// the generic principal is assigned to the user context
           
// of the application

           
if(Membership.ValidateUser(username, password))
           
{
               
string[] roles =Roles.GetRolesForUser(username);
                app
.Context.User=newGenericPrincipal(new
               
GenericIdentity(username,"Membership Provider"), roles);
           
}
           
else
           
{
               
DenyAccess(app);
               
return;
           
}
       
}
       
else
       
{
            app
.Response.StatusCode=401;
            app
.Response.End();
       
}
   
}

   
publicvoidOnEndRequest(object source,EventArgs eventArgs)
   
{
       
// The authorization header is not present.
       
// The status of response is set to 401 Access Denied.
       
// We will now add the expected authorization method
       
// to the response header, so the client knows
       
// it needs to send credentials to authenticate
       
if(HttpContext.Current.Response.StatusCode==401)
       
{
           
HttpContext context =HttpContext.Current;
            context
.Response.AddHeader("WWW-Authenticate","Basic Realm");
       
}
   
}

   
privatevoidDenyAccess(HttpApplication app)
   
{
        app
.Response.StatusCode=403;
        app
.Response.StatusDescription="Forbidden";

       
// Write to response stream as well, to give the user
       
// visual indication of error
        app
.Response.Write("403 Forbidden");

        app
.CompleteRequest();
   
}
} 
 
//----------------------------------------------------------------------
// 进行 HTTP 验证 (Basic Authorization) jsp
String auth_user = "", auth_pass = "";
String auth = request.getHeader("Authorization");
if (auth != null && auth.toUpperCase().startsWith("BASIC")) {
  String encoded = auth.substring(6);
  sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
  String decoded = new String(dec.decodeBuffer(encoded));
  String[] userAndPass = decoded.split(":", 2);
  auth_user = userAndPass[0];
  auth_pass = userAndPass[1];
}  //end if
if (!auth_user.equals("admin") || !auth_pass.equals("password")) {
  // 帐号或密码不正确,无法通过验证!
  response.setStatus(401);
  response.setHeader("WWW-Authenticate", "Basic realm="My Realm"");
} else {
  // 验证通过,可以进行其他业务操作了 
}  //end if

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

string authorization =Request.Headers["Authorization"];
string userInfo;
string username ="";
string password ="";
if(authorization !=null)
{
    
byte[] tempConverted =Convert.FromBase64String(authorization.Replace("Basic ","").Trim());
     userInfo
=System.Text.Encoding.UTF8.GetString(tempConverted);
    
string[] usernamePassword = userInfo.Split(newstring[]{":"},StringSplitOptions.RemoveEmptyEntries);
     username
= usernamePassword[0];
     password
= usernamePassword[1];
}

if(username =="yourusername"&& password =="yourpassword")
{
}
else
{
    
Response.AddHeader("WWW-Authenticate","Basic realm=\"Test\"");
    
Response.StatusCode=401;
    
Response.End();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值