【问题标题】:REST Client Basic Authorization to a REST APIREST API 的 REST 客户端基本授权
【发布时间】:2018-09-06 08:52:26
【问题描述】:

我有一个问题。我有一个 Base64Encoded 的基本授权值,看起来像这样“aHZjYnN4NXJ4bXV6OmplWHN1Wl ....”,我只是想知道我可以在哪里将此值放入代码中?它是必需的,以便我可以接收承载访问令牌。我让它在邮递员中工作,但不是在这段代码中。此代码用于从不需要额外授权的其他 API 获取 JSON 字符串。但是当我在另一个需要基本授权字符串的 API 上尝试它时,我收到此错误:{“errorMessage”:[“远程服务器返回错误:(405)方法不允许。”],“错误”:{} }。找不到关于该主题的太多文档,任何帮助将不胜感激。

这是表单类中的代码:

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

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • (405) Method Not Allowed 表示您在请求中使用了错误的动词(GET、POST 等)。

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


【解决方案1】:

我使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    相关资源
    最近更新 更多