在restful C#中使用身份验证令牌

时间:2017-06-14 01:49:42

标签: c# rest authentication

我厌倦了不同的资源,但找不到我的问题的答案,如果这个问题已在其他地方得到解答,那么请将链接发给我答案。

我有消费的宁静服务,为此我必须首先使用身份验证。 好吧,这工作正常,我管理了身份验证,我获得了身份验证令牌。

现在,当我想使用我想要的服务时 远程服务器返回错误:(401)未经授权。

服务中没有地方可以使用令牌。

我创建了一个简单的C#程序来做到这一点 它包含2个按钮 按钮1:将验证用户(工作正常,我得到令牌) 按钮2:将使用主服务(不起作用并获得未授权)

这是我的代码 请告知我应该如何使用身份验证令牌。

private void button1_Click(object sender, EventArgs e)
{
      var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://apps.ramm.co.nz:443/RammApi6.1/v1/authenticate/login");
      httpWebRequest.ContentType = "application/json";
      httpWebRequest.Method = "POST";

      using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
      {
                string json = "{\"database\":\"RAMM API Demo\"," +
                              " \"userName\":\"api_demo\"," +
                              "\"password\":\"thursday\"}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
       }

       var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
       using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
       {
          var result = streamReader.ReadToEnd();
       }
 }

.............

private void button2_Click(object sender, EventArgs e)
{
     var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://apps.ramm.co.nz:443/RammApi6.1/v1/data/table");
     httpWebRequest.ContentType = "application/json";
     httpWebRequest.Method = "POST";

     using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
     {
                string json = "{ \"tableName\": \"carr_way\" " +
                                ", \"expandLookups\": \"False\" " +
                                ", \"getGeometry\": \"True\" " +
                                ", \"loadType\": \"Specified\" " +
                                ", \"columns\": [\"carr_way_no\", \"road_id\", \"carrway_start_m\", \"carrway_end_m\", \"start_name\", \"end_name\", \"added_on\", \"chgd_on\"] " +
                                ", \"filters\": [[{\"columnName\": \"added_on\", \"operator\": \"GreaterThan\", \"value\": \"2015-01-01\"}] " +
                                ", [{\"columnName\": \"chgd_on\", \"operator\": \"GreaterThan\", \"value\": \"2015-01-01\"}]]}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
      }

      var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
      using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
      {
         var result = streamReader.ReadToEnd();
      }

   }

1 个答案:

答案 0 :(得分:1)

您通常会将授权放在授权标头中,但这可能取决于您使用的授权类型。这可能对你有所帮助:

Setting Authorization Header of HttpClient