将凭据传递到Web服务

时间:2019-12-20 14:51:37

标签: web-services networkcredentials


我有一个Web服务(asmx),我需要在其上实现安全性,并确保只有一个用户可以使用此方法。
这是我的WebService:

  public SoapHeader myHeader;
    [WebMethod]
    [SoapHeader("myHeader", Direction = SoapHeaderDirection.InOut)]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public string List_Person()
    {
        System.Data.Common.DbConnection C = new SqlConnection();
        C.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString.ToString();

        LabDatabase.dbLAB db = new LabDatabase.dbLAB(C);


            var res = (from P in db.d_person select P).OrderBy(e => e.pe_surname).Take(2);//togliere limite
          return JsonConvert.SerializeObject(res );
}

和我的web.config安全设置:

<system.web>

<authorization>
  <allow users="Kim"/>
  <allow roles="Admins"/>
  <!-- <deny users="?"/>-->     
</authorization>
<authentication mode="Forms" />
<!--mode="Windows" 
 <identity impersonate="true" />-->
<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

我试图从客户那里打电话给

  public string CitySave(string city)
    {
        string URL = "http://localhost:50256/LABService.asmx/List_Person";
        System.Uri MyUrl = new System.Uri(URL);

        string result = "";
        try
        {
            using (System.Net.WebClient webClient = new System.Net.WebClient())
            {
                webClient.UseDefaultCredentials = true;
                System.Net.NetworkCredential cred = new System.Net.NetworkCredential();
                cred.UserName = "username";
                cred.Password = "password";
                webClient.Credentials = cred;// myCredentialCache;

                System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
                credentialCache.Add(MyUrl, "Basic", cred);

                webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                webClient.Headers.Add("Content-type", "application/json");
                //string data = JsonConvert.SerializeObject(city);
                // var response = webClient.UploadString(URL, data);
                var response = webClient.DownloadString(URL);
            //    result = JsonConvert.DeserializeObject<string>(response);
                return result;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

当我在webServer上设置断点并尝试查看: Environment.UserName 是否有效,或者   User.Identity.Name ,它不会返回我在客户端中设置的用户,而是Windows用户。
我该怎么做才能发送正确的凭据并在我的Web服务器上对其进行检查?

0 个答案:

没有答案