REST客户端对REST API的基本授权

时间:2018-03-27 19:59:31

标签: c# rest api web-services rest-client

我有一个问题。我有一个Base64Encoded的基本授权值看起来像这样的“aHZjYnN4NXJ4bXV6OmplWHN1Wl ....”,我只是想知道我可以将这个值放在代码中的哪个位置?它是必需的,所以我可以收到承载访问令牌。我让它在Postman中工作,但不在此代码中。此代码用于从其他API获取JSON字符串,这些API不需要额外的授权。但是当我在另一个需要Basic Authorization字符串的API上尝试它时,我收到此错误:{“errorMessage”:[“远程服务器返回错误:(405)Method Not Allowed。”],“errors”:{} }。无法找到关于这个主题的大量文档,任何帮助将不胜感激。

以下是表单类中的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AuthtRestClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region UI Event Handlers
        private void CmdGO_Click(object sender, EventArgs e)
        {
            RestClient rClient = new RestClient();
            rClient.Endpoint = txtRequestURI.Text;

            rClient.UserName = txtUserName.Text;
            rClient.UserPassword = txtPassword.Text;

            DebugOutput("REst Client Created");

            string strResponse = string.Empty;

            strResponse = rClient.MakeRequest();

            DebugOutput(strResponse);
        }

        #endregion

        private void DebugOutput (string strDebugText)
        {
            try
            {
                System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
                txtResponse.Text = txtResponse.Text + strDebugText + Environment.NewLine;
                txtResponse.SelectionStart = txtResponse.TextLength;
                txtResponse.ScrollToCaret();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
            }
        }
    }
}

以下是RestClient类中的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace AuthtRestClient
{
    public enum HttpVerb
    {
        GET,
        POST,
        PUT,
        DELETE
    }

    public enum AuthenticationType
    {
        Basic,
        NTLM
    }

    public enum AuthenticationTechnique
    {
        RollYourOwn,
        NetworkCredential
    }

    class RestClient
    {
        public string Endpoint { get; set;  }
        public string EndPoint { get; }
        public HttpVerb HttpMethod { get; set;  }
        public AuthenticationType AuthType { get; set; }
        public AuthenticationTechnique AuthTech { get; set; }
        public string UserName { get; set; }
        public string UserPassword { get; set; }

        public RestClient()
        {
            EndPoint = string.Empty;
            HttpMethod = HttpVerb.GET;
        }

        public string MakeRequest()
        {
            string strResponseValue = string.Empty;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Endpoint);

            request.Method = HttpMethod.ToString();

            string authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(UserName + ":" + UserPassword));
            request.Headers.Add("Authorization", "Basic " + authHeader);

            HttpWebResponse response = null;

            try 
            {
                response = (HttpWebResponse)request.GetResponse();

                // Process the response stream... (could be JSON, XML, HTML, etc...)

                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            strResponseValue = reader.ReadToEnd();
                        }// End of StreamReader
                    }
                }// End of using ResponseStream

            }
            catch(Exception ex)
            {
                strResponseValue = "{\"errorMessage\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
            }
            finally
            {
                if (response != null)
                {
                    ((IDisposable)response).Dispose();
                }
            }

                return strResponseValue;
        }
    }
}

我试图通过几种不同的方式传递它,其中一种看起来像这样,但是无法让它工作:

string authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("U4OXU5aHZjYnN4NXJ4bXV6ORIWUp==" + 
                ":" +UserName + ":" + UserPassword));
request.Headers.Add("Authorization", "Basic " + authHeader);

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

我用RestSharp来解决它。

// RestSharp code:
        var client = new RestClient("https://auth.example.com/oauthserver/oauth2/token/");
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        //request.AddHeader("Postman-Token", "1defca09-ab68-43cd-91a0-a78709a2fb41"); //this line not needed
        request.AddHeader("Cache-Control", "no-cache");
        request.AddHeader("Authorization", "Basic U5aHZjYnN4NXJlWHN1WlhwZDZIbn==");
        request.AddParameter("undefined", "grant_type=client_credentials", ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string