none
Add Username and Password Json File in C# RRS feed

  • Question

  • dear friend,

    I have a little problem, when I try to run my program it show an error 401 (unauthorized)

     I need to input username: admin and password: admin into Json, but I don't how to put it

    does anyone could help me ? this is my script

    public partial class Form1 : Form
        {
                
             private static void PostJson(string uri, template postParameters)
            {
                string postData = JsonConvert.SerializeObject(postParameters);
                byte[] bytes = Encoding.UTF8.GetBytes(postData);
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentLength = bytes.Length;
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                using (Stream requestStream = httpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Count());
                }
                var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (httpWebResponse.StatusCode != HttpStatusCode.OK)
                {
                    string message = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode);
                    throw new ApplicationException(message);
                }
            }
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                PostJson("http://xxxxxxxxxxx/CustomerSalesOrder", new template{ });
                var template = new template
                {
                    CardCode = "C001",
                    PostingDate = "2017-05-17",
                    DocDueDate = "2017-05-17",
                    TaxDate = "2017-05-17",
                    SalesPersonCode = "-1",
                    DocumentNumberingPOS = "xx",
                    PrimaryNumberingPOS = "xxx",
                };
    
                template.Lines.Add(new template_item
                {
                    ItemCode = "ITEM0001",
                    WarehouseCode = "PST-000",
                    Quantity = "1",
                    Price = "50000",
                });
    
                template.Lines.Add(new template_item
                {
                    ItemCode = "ITEM0002",
                    WarehouseCode = "PST-000",
                    Quantity = "1",
                    Price = "10000"
                });
            }
        }
    
        public class template
        {
            public string CardCode { get; set; }
            public string PostingDate { get; set; }
            public string DocDueDate { get; set; }
            public string TaxDate { get; set; }
            public string SalesPersonCode { get; set; }
            public string DocumentNumberingPOS { get; set; }
            public string PrimaryNumberingPOS { get; set; }
            public static List<template_item> Lines = new List<template_item>();      
        }
    
        public class template_item
        {
            public string ItemCode { get; set; }
            public string WarehouseCode { get; set; }
            public string Quantity { get; set; }
            public string Price { get; set; }
        }

    Thanks for your help

    Regards,

    Steve Henry


    • Edited by steve_henry Wednesday, October 4, 2017 4:23 AM change url
    Wednesday, October 4, 2017 4:21 AM

All replies

  • Unfortunately that is completely dependent upon the URL you're calling. If it is a REST API then you have to use the auth scheme for the API. Most use OAuth but there are 4 different types. For the common case of client credentials you first have to call a (generally separate) URL for authentication that requires the client ID, secret and oauth scope(s). You get back a bearer token that you then add to the HTTP header for calls to the actual API.

    If the URL is an ASP.NET forms auth app then you need to first go to the URL for the login and pass the UN/PWD as the form data body. You get back a cookie with the auth information. You then need to attach the cookie to subsequent requests. You probably also need to include session information.

    Refer to the documentation for the URL you're calling to determine how they expect authentication to work. It is unlikely you would pass UN/PWD on each request. That is unsecure and inefficient.

    Michael Taylor
    http://www.michaeltaylorp3.net

    Wednesday, October 4, 2017 2:38 PM
    Moderator
  • dear CoolDadTx

    thanks for your help

    I've got the solution but I can't see it it success or not

    that's my new problem

    Regards,

    STeve Henry

    Thursday, October 5, 2017 2:24 AM
  • Hi Steve,

    Please submit detailed information about the error message, we could not guess what happen.

    I provided the following code snippet per my understanding, please try and let me know your result.

    var webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Method = "GET";
    webRequest.ContentType = "application/json";
    webRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:28.0) Gecko/20100101 Firefox/28.0";
    webRequest.ContentLength = 0; // added per comment
    string autorization = "username" + ":" + "Password";
    byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
    autorization = Convert.ToBase64String(binaryAuthorization);
    autorization = "Basic " + autorization;
    webRequest.Headers.Add("AUTHORIZATION", autorization);
    var webResponse = (HttpWebResponse)webRequest.GetResponse();
    if (webResponse.StatusCode != HttpStatusCode.OK) Console.WriteLine("{0}",webResponse.Headers);
    using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
    {
        string s = reader.ReadToEnd();
        Console.WriteLine(s);
        reader.Close();
    }

    To help you understand authorization, I pick up a documentation from MSDN, please refer to https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/membership/user-based-authorization-cs#a-look-at-the-url-authorization-workflow

    Hope it helps.

    Regards,

    Thursday, October 5, 2017 9:19 AM
    Moderator
  • Hello steven,

    Is there anything updated? If your issues has been solved, you could close the thread by marking  as answer.This can be beneficial to other community members reading this thread.

    Sincerely,
    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Sunday, October 29, 2017 9:31 AM
    Moderator
  • If it is a REST API, take a look at my blog posts. It may help:

    https://geek-goddess-bonnie.blogspot.com/2017/10/rest-with-ssl.html


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Proposed as answer by Fei HuModerator Wednesday, November 1, 2017 8:36 AM
    Sunday, October 29, 2017 2:28 PM
    Moderator