Где разместить токен доступа JWT в URL-адресе

#c# #json #ssis #jwt

#c# #json #ssis #jwt

Вопрос:

Я хочу просмотреть набор данных JSON в своем браузере Chrome, но я получаю следующее сообщение:

введите описание изображения здесь

Из моих исследований похоже, что мне нужно отправить токен доступа к серверной части, чтобы получить доступ к URL-адресу и прочитать данные. Как мне отправить токен доступа JWT с помощью SSIS C #?

Вот код, который у меня есть до сих пор:

 #region Namespaces

using System;

using System.Data;

using Microsoft.SqlServer.Dts.Pipeline.Wrapper;

using Microsoft.SqlServer.Dts.Runtime.Wrapper;

using System.Net;

using Microsoft.SqlServer.Dts.Runtime;

using System.IO;

using System.Runtime.Serialization.Json;

using System.Runtime.Serialization;

using System.Collections.Generic;

using System.Text;

using System.Linq;

using System.Net.Http;
using System.Net.Http.Headers;



#endregion


#region Class



[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]

public class ScriptMain : UserComponent

{


    #region Methods



    /// <summary>Outputs records to the output buffer</summary>

    public override void CreateNewOutputRows()

    {


        //Set Webservice URL
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        string wUrl = Variables.URL;

        try

        {



            //Call getWebServiceResult to return our Article attributes

            List<Payment> outPutResponse = GetWebServiceResult(wUrl);


            if (outPutResponse != null)

            {


              

                foreach (Payment py in outPutResponse) 

                {

                    //Output main attributes of Article

                    Output0Buffer.AddRow();



                    Output0Buffer.column = DateTime.Parse(py.column);
                   


                }

            }

        }

        catch (Exception e)

        {

            FailComponent(e.ToString());

        }


    }


    /// <summary>

    /// Method to return our list articles

    /// </summary>

    /// <param name="wUrl">The web service URL to call</param>

    /// <returns>An object that contains a list of Articles</returns>



    private List<Payment> GetWebServiceResult(string wUrl)

    {

        //var client = new RestClient(wUrl);
        //var request = new RestRequest(Method.GET);
        //request.AddHeader("content-type", "application/json");
        //request.AddHeader("authorization", "Bearer ACCESS_TOKEN");
        //IRestResponse response = client.Execute(request);


        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);

        // Add an Accept header for JSON format.    

        httpWReq.Headers.Add(HttpRequestHeader.Authorization, "Bearer "  
            "Authorization Code Here");




        httpWReq.Method = "GET";

        httpWReq.ContentType = "application/json";

        HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();



        List<Payment> jsonResponse = null;


        try

        {
            Stream responseStream = httpWResp.GetResponseStream();

            /*  //Get the stream of JSON
              Stream dataStream = null;
              StreamReader reader = null;

              string responseFromServer = null;

              // Get the stream containing content returned by the server.
              dataStream = httpWResp.GetResponseStream();
              // Open the stream using a StreamReader for easy access.
              reader = new StreamReader(dataStream);
              // Read the content.
              responseFromServer = reader.ReadToEnd();
              */


            //Deserialize the JSON stream

            using (StreamReader reader = new StreamReader(responseStream))

            {
                //Deserialize our JSON

                DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<Payment>));

                jsonResponse = (List<Payment>)sr.ReadObject(responseStream);

            }

        }

        //Output JSON parsing error

        catch (Exception e)

        {

            FailComponent(e.ToString());

        }

        return jsonResponse;


    }


    /// <summary>

    /// Outputs error message

    /// </summary>

    /// <param name="errorMsg">Full error text</param>

    private void FailComponent(string errorMsg)

    {

        bool fail = false;

        IDTSComponentMetaData100 compMetadata = this.ComponentMetaData;

        compMetadata.FireError(1, "Error Getting Data From Webservice!", errorMsg, "", 0, out fail);


    }

    #endregion

}

#endregion
  

Мы будем очень признательны за вашу помощь!

Пух пух Пух пух

Ответ №1:

Спасибо всем за помощь в решении этого вопроса.

Вот ответ:

  private List<FacultyList> GetWebServiceResultJWT(string wUrl)
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    string serverBaseAddress = wUrl.Substring(0, 42);
    var accessToken = "your token";

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Clear();
        client.BaseAddress = new Uri(serverBaseAddress);

        var contentType = new MediaTypeWithQualityHeaderValue("application/json");
        client.DefaultRequestHeaders.Accept.Add(contentType);

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);



        HttpResponseMessage message = client.GetAsync(wUrl.Substring(wUrl.Length - 48, 48)).Resu<

        if (message.IsSuccessStatusCode)
        {
            string inter = message.Content.ReadAsStringAsync().Result.ToString();

            Payment result = JsonConvert.DeserializeObject<Payment>(inter);
            List<FacultyList> facultyList = result.facultyList.Cast<FacultyList>().ToList();
            return facultyList; // return type should be List<facultyList>


        }



        return null;
    }

    /* string accessToken = "yourtoken"; // or your JWT Token

     var request = new HttpRequestMessage(HttpMethod.Get, wUrl);
     request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); 

     HttpClient client = new HttpClient();
     HttpResponseMessage response = client.SendAsync(request).Resu< 
     return null;
}





private void FailComponent(string errorMsg)

{

    bool fail = false;

    IDTSComponentMetaData100 compMetadata = this.ComponentMetaData;

    compMetadata.FireError(1, "Error Getting Data From Webservice!", errorMsg, "", 0, out fail);


}