zoukankan      html  css  js  c++  java
  • HTTP BASIC 应用(2)

    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();
    }

  • 相关阅读:
    python 爬虫应用——校园网搜索引擎(crawler application——Campus web search engine part-two)(下)
    python 列表寻找满足某个条件的开始索引和结束索引(python find the starting and ending indices of values that satisfy a certain condition in a list)
    python 爬虫应用——校园网搜索引擎(crawler application——Campus web search engine part-one)(上)
    python 根据空格切割英文单词(python split string according to space)
    vscode 配置 typeScript+nodejs 和 react+typeScript 开发环境
    vscode electron error (Refused to execute inline event handler because it violates the following Content Security Policy directive ... 和 Uncaught ReferenceError: process is not defined)
    vscode 运行和调试 javascript 代码 (vscode run and debug javascript code)
    Matplotlib:绘图和可视化
    Pandas
    Numpy
  • 原文地址:https://www.cnblogs.com/fx2008/p/2819684.html
Copyright © 2011-2022 走看看