简体   繁体   English

使用用户名和密码调用 rest api - 如何

[英]Calling a rest api with username and password - how to

I am new to rest api's and calling them via .NET我是休息 api 的新手并通过 .NET 调用它们

I have an api: https://sub.domain.com/api/operations?param=value&param2=value我有一个 api: https : //sub.domain.com/api/operations? param = value & param2 =value

The notes for the api say that to authorize I need to use the basic access authentication - how do I do that? api 的注释说要授权我需要使用基本访问身份验证 - 我该怎么做?

I currently have this code:我目前有这个代码:

        WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
        req.Method = "GET";
        //req.Credentials = new NetworkCredential("username", "password");
        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

However I get a 401 unauthorized error.但是我收到 401 未经授权的错误。

What am I missing, how do I form api calls using the basic access auth?我错过了什么,如何使用基本访问身份验证形成 api 调用?

If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request.如果 API 说要使用 HTTP 基本身份验证,那么您需要向您的请求添加一个 Authorization 标头。 I'd alter your code to look like this:我会改变你的代码看起来像这样:

    WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
    req.Method = "GET";
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
    //req.Credentials = new NetworkCredential("username", "password");
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

Replacing "username" and "password" with the correct values, of course.当然,用正确的值替换"username""password"

You can also use the RestSharp library for example例如,您还可以使用 RestSharp 库

var userName = "myuser";
var password = "mypassword";
var host = "170.170.170.170:333";
var client = new RestClient("https://" + host + "/method1");            
client.Authenticator = new HttpBasicAuthenticator(userName, password);            
var request = new RestRequest(Method.POST); 
request.AddHeader("Accept", "application/json");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");            
request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Here is the solution for Rest API这是 Rest 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.

相关问题 在C#中使用标头,用户名和密码调用Api - Calling Api with header, username and password in C# 如何使用multipart / formdata编码和POST方法使用带有用户名和密码的rest API - How to consume rest API with username and password using multipart/formdata encoding and using POST method 如何在没有用户名和密码的情况下访问 REST API 方法 - 但只能使用令牌? - Howto access REST API methods without username and Password - but only with a token? Xamarin Forms - Wordpress REST API - 查看用户名和密码 - Xamarin Forms - Wordpress REST API - See Username and Password 在标头(REST API)中使用具有用户名和密码的GetAsync - Use GetAsync with username+password in header (REST API) 从.Net C#调用需要身份验证的Java Web服务“ REST”和用户名,密码和证书 - calling java web service “REST” that require auth with username & password and certificate from .Net C# 如何在 Wordpress JWT Auth API 的正文中传递用户名和密码 - How To Pass Username and Password in the Body for Wordpress JWT Auth API 未指定用户名/密码致电Amazon S3 - Username / password not specified Calling Amazon S3 调用基本REST API - Calling Base REST API REST API不调用导航 - REST api not calling on the navigation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM