简体   繁体   中英

Authorizing in azure devops rest API

I have a use a azure devops api for statistics but i cant authenticate in c# when sending header.

i use webrequests.

after a bunch of testing i went and used the postman to test it out and i could get in using username and password so i coppied that authorization headear which 100% works since i did get information back from server.

var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = "GET";

            httpWebRequest.Headers.Add("Authorization:Basic base64Username:password");
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
                Console.WriteLine(result);
            }

in c# all im getting in response is whole bunch of html type code what i guess is part of authentication website

The fact that you're getting a bunch of HTML back suggests that you're not forming the basic auth header in the correct way, or that the username you're providing is not recognised. It's not clear from your code sample which it is, but if you were supplying a correctly formed auth header, with invalid credentials, you would receive a 401 Unauthorized response, which the HttpWebRequest class would throw as an exception.

Two things to check:

  • Ensure you're forming the auth header correctly (this is almost certainly it, it's not clear from your question how you copied it from postman or tried generating it in C#)

  • Ensure your credentials are valid.

I've adjusted your code snippet to be explicit about correctly forming the header:

var base64Creds = Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password"));

var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";

httpWebRequest.Headers.Add($"Authorization: Basic {base64Creds}");

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();

    Console.WriteLine(result);
}

If the above code snippet doesn't work with your main username and password, as a last resort you can try setting an alternate credential: ( https://dev.azure.com/ {organisation}/_usersSettings/altcreds) with a known username and password combination and see if that works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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