简体   繁体   English

在 C# 中使用基本身份验证调用 WEB API

[英]Calling WEB API with basic authentication in C#

I have a working WEB API that I wrote, and I added basic authentication to the API (username is "testing", password is "123456").我有一个我编写的工作 WEB API,我向 API 添加了基本身份验证(用户名是“testing”,密码是“123456”)。 However, when trying to call that API from my web form, I keep getting the "(401) Unauthorized" message.但是,当尝试从我的 Web 表单调用该 API 时,我不断收到“(401) Unauthorized”消息。 What should I change in the web code to call the API successfully?我应该在 Web 代码中更改什么才能成功调用 API?

 string url = String.Format("http://example.com"); //here I have the correct url for my API
 HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);
 requestObj.Method = "Get";
 requestObj.PreAuthenticate = true;
 requestObj.Credentials = new NetworkCredential("testing", "123456");
 HttpWebResponse responseObj = null;
 responseObj = (HttpWebResponse)requestObj.GetResponse();
 string strresult = null;
 using (Stream stream = responseObj.GetResponseStream())
 {
     StreamReader sr = new StreamReader(stream);
     strresult = sr.ReadToEnd();
     sr.Close();
 }

This is what my API searches for in terms of authentication:这是我的 API 在身份验证方面搜索的内容:

actionContext.Request.Headers.Authorization.Parameter

Should I be adding a header instead of NetworkCredential or is it the same thing?我应该添加一个标头而不是 NetworkCredential 还是同样的事情?

This should help:这应该有帮助:

    HttpMessageHandler handler = new HttpClientHandler()
    {
    };
        
    var httpClient = new HttpClient(handler)
    {
         BaseAddress = new Uri(url),
         Timeout = new TimeSpan(0, 2, 0)
    };
        
    httpClient.DefaultRequestHeaders.Add("ContentType", "application/json");
        
    //This is the key section you were missing    
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("testing:123456");
    string val = System.Convert.ToBase64String(plainTextBytes);
    httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + val);
        
    HttpResponseMessage response = httpClient.GetAsync(url).Result;
    string content = string.Empty;
        
    using (StreamReader stream = new StreamReader(response.Content.ReadAsStreamAsync().Result, System.Text.Encoding.GetEncoding(_encoding)))
    {
         content = stream.ReadToEnd();
    }

这是我需要的行:

requestObj.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));

I just found out that with .NET Core 3.1 you could do it like this:我刚刚发现使用 .NET Core 3.1 你可以这样做:

    HttpRequestMessage request = new HttpRequestMessage(
        HttpMethod.Post,
        "your-api-url-here");

    request.Headers.Authorization = new BasicAuthenticationHeaderValue(username, password);

I think your API might need a header being added to it (if you haven't done so already).我认为您的 API 可能需要添加一个标头(如果您还没有这样做的话)。 Take a look at this article: https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side看看这篇文章: https : //en.wikipedia.org/wiki/Basic_access_authentication#Client_side

But essentially, your API will need an Authorization header added to it.但本质上,您的 API 需要添加一个Authorization标头。 The Authorization key will contain the word Basic followed by a space, then the username and password encrypted using Base64 . Authorization密钥将包含单词Basic后跟一个空格,然后是使用Base64加密的用户名和密码。 So in your instance, testing:123456 would be encrypted using base64 as dGVzdGluZzoxMjM0NTY= .因此,在您的实例中, testing:123456将使用 base64 作为dGVzdGluZzoxMjM0NTY=进行加密。 So the header record will look like this:所以标题记录将如下所示:

Authorization: Basic dGVzdGluZzoxMjM0NTY=

(Basic Authentication) Here is the other solution to call Authenticated API (Basic Authentication) 这是调用Authenticated API的另一种解决方案

 class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM