通過SOAPHeader增強WebService的安全性

來源:互聯網
上載者:User

  閱讀目錄

  一:前言

  二:SOAPHeader實現身分識別驗證步驟

  三:通過SOAPHeader實現身分識別驗證步驟執行個體

  一:前言
  在互連網上,調用WebService往往需要進行身分識別驗證,我們的WebService不可以讓任何人都能夠調用的,一般能調用我們的WebService的不是我們的客戶,就是我們的合作方,調用WebService時我們需要身分識別驗證,只有通過身分識別驗證的使用者才能調用相應的WebService資源,我們可以通過SOAPHeader自訂的身分識別驗證方式實現驗證

  二:SOAPHeader實現身分識別驗證步驟

  1:自訂一個類比如CustomSOAPHeader,該類繼承自SOAPHeader

  2:在CustomSOAPHeader類裡面寫我們自訂驗證的邏輯

  3:在WebService中聲明CustomSOAPHeader類型的公用成員header,並在暴露給用戶端調用的方法中調用header的自訂驗證方法實現身分識別驗證功能

  4:在用戶端首先建立CustomSOAPHeader類型的執行個體對象header,然後將使用者名稱和密碼傳入header,最後調用WebService執行個體對象的CustomSOAPHeaderValue屬性將header傳入WebService

  三:通過SOAPHeader實現身分識別驗證步驟執行個體

  1:Service.cs

   public class CustomSOAPHeader : SoapHeader
  {
      public CustomSOAPHeader()
      {
          //
          //TODO: 在此處添加建構函式邏輯
          //
      }
      public string name;
      public string password;
      public bool IsValid(string strUserName, string strPassword)
      {
          if (strUserName == "三星電子" && strPassword == "abc")
              return true;
          else
              return false;
      }
  }

  public class Service : System.Web.Services.WebService
  {
      public Service ()

    {

          //如果使用設計的組件,請取消注釋以下行 
          //InitializeComponent(); 
      }
      public CustomSOAPHeader header;
      [WebMethod]
      [SoapHeader("header")]
      public string HelloWorld() 
      {
          if (header.IsValid(header.name, header.password))
              return "SOAP標題驗證成功,返回HelloWorld";
          return "SOAP標題驗證失敗";
      }
  }

  2:Program.cs

   static void Main(string[] args)
        {
            localhost.Service service = new localhost.Service();
            localhost.CustomSOAPHeader header = new localhost.CustomSOAPHeader();
            header.name = "三星電子";
            header.password = "abc";
            service.CustomSOAPHeaderValue = header;
            Console.WriteLine(service.HelloWorld());
            Console.ReadLine();
        }

  

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.