TeamCity - Unable to authenticate via API - c#

I've been struggling with authentication in TeamCity through the API lately. I can access the resources directly in my browser (http://usr:pw#teamcity:8111/httpAuth/app/rest/...), but doing so programmatically returns 401-Unauthorized.
WebRequest request = WebRequest.Create("http://user:pwd#teamcity:8111/httpAuth/app/rest/projects");
request.Method = WebRequestMethods.Http.Get;
try
{
request.Timeout = Timeout.Infinite;
WebResponse response = request.GetResponse(); //Returns 401:Unauthorized
I can use guestAuth(http://teamcity:8111/guestAuth/app/rest/projects) without any problem, so there should not be any problem with the WebRequest itself.
Does anyone have an idea?

Try to add your credentials and then make request.it will be get what you need.
var username = "abc";
var password = "123";
var encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);

Related

C# POST/GET Issue with Login Credentials

Pretty much a noob here, having issues here with a Post Request in C#. I am returning the server response to webBrowser Control, and no matter what I try, I just get the login page returned with no form values posted. Any help here would be greatly appreciated!
Login Page: "https://www.carrier411.com/".
URL example that I want to return:(You have to be logged in to view)
"https://www.carrier411.com/manager/companydetail.cfm?docket=MC1114638"
var username = "******"; var password = "******";
string url = "https://www.carrier411.com/manager/companydetail.cfm?docket=MC1073504";
string postData = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + passWord));
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "text/html";
httpRequest.Headers.Add("Authorization", "Basic " + postData);
httpRequest.Accept = #"text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{streamWriter.Write(postData);}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
string result = streamReader.ReadToEnd().ToString();
webBrowser1.DocumentText = result;

How to fetch classrooms from google classroom using API calls?

So I am trying to fetch my classes from my google classroom into my application:
Here is my google url:
var Googleurl = "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=" + googleplus_redirect_url + "&prompt=consent&response_type=code&client_id=" + googleplus_client_id + "&scope=https://www.googleapis.com/auth/userinfo.profile+https://www.google.com/m8/feeds/+https://www.googleapis.com/auth/drive+https://www.googleapis.com/auth/drive.appdata+https://www.googleapis.com/auth/drive.file+https://www.googleapis.com/auth/drive.metadata+https://www.googleapis.com/auth/classroom.courses+https://www.googleapis.com/auth/classroom.profile.emails+https://www.googleapis.com/auth/classroom.profile.photos+https://www.googleapis.com/auth/classroom.rosters+https://www.googleapis.com/auth/classroom.rosters.readonly&access_type=offline";
After this I request for the access codes through:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
I am able to get the access code as well as the refresh token all fine.
Now when I wish to fetch my classroom by:
string p="https://classroom.googleapis.com/v1/courses";
string auth = "Bearer "+access_token;
private bool GetClasses(string p,string auth)
{
using (var client = new WebClient())
{
var uri = new Uri(p);
//client.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer", auth);
string req="Authorization: "+ auth;
client.Headers.Add(req);
var response = client.DownloadString(uri);
}
return true;
}
This code return an error of type:System.Net.WebException: {"The remote server returned an error: (403) Forbidden."}
I have used the same access_token to get all other scopes as shown in the scopes parameter in mu Googleurl. However I am unable to access my classes even though I've added the respective scopes for it.
Apparently to use google classroom related functionalities we need to enable the google classroom Api. As silly as it may sound I was ignorant about it(As I had already enabled the google Api service). Just had to activate the classroom api and the code worked like a charm.

Basic Auth not working when trying to get raw contents from BitBucket?

I'm trying to download file contents from Bit Bucket, but I keep getting a "Log In" page as a response. I'm providing credentials with Basic Auth. Is this a C# specific issue? Everything works fine if I try it via Postman. Code Below.
var url = "https://[BITBUCKET_DOMAIN]/projects/[ID]/repos/[REPO]/raw/[PATH_TO_MY_FILE]"
var uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
string userName = "user";
string password = "pw";
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(userName, password);
request.Accept = "text/plain";
string result;
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
return result;
This top answer here worked for me.
HttpWebRequest using Basic authentication
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);

Django server returns 403 Forbidden while logging in via C#

There is a code I'm using to authenticate in django app with "/" as login url:
HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");
tokenRequest.CookieContainer = new CookieContainer();
string token = "";
using (var response = (HttpWebResponse)tokenRequest.GetResponse()) {
token = response.Cookies["csrftoken"].ToString().Split('=')[1];
}
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");
var cache = new CredentialCache();
cache.Add(new Uri("http://carkit.kg/"), "Digest", new NetworkCredential(tempEmail, tempPass));
loginRequest.Credentials = cache;
loginRequest.PreAuthenticate = true;
loginRequest.Method = "POST";
loginRequest.CookieContainer = new CookieContainer();
loginRequest.CookieContainer.Add(new Cookie("csrftoken", token) {Domain="carkit.kg"});
Debug.Log(token);
byte[] data = Encoding.UTF8.GetBytes("username=" + tempEmail + "&password=" + tempPass + "&csrfmiddlewaretoken=" + token);
loginRequest.ContentLength = data.Length;
loginRequest.Timeout = 10000;
loginRequest.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(tempEmail + ":" + tempPass)));
loginRequest.GetRequestStream().Write(data, 0, data.Length);
Debug.LogWarning(loginRequest.ToString());
//There is 403 error
HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();
Debug.Log(authResponse.ResponseUri);
Token request is ok, but post request returns 403 error. I'm guessing that the problem is in incorrect cookies or post data but I cant find it out.
You need to send a X-CSRFToken header with the csrf token.
X-CSRFToken:<csrftoken cookie value>
(I don't know how to do it with C# )

Send login details with HttpWebRequest

I'm trying to get this bit of code to pause/unpause my XBMC Player
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl+playPause);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
Debug.WriteLine(resStream);
And I need to send my login data with it, lets say its MyUsername and SuperPassword.
How would I add that data intp the request? I tried request.Headers.Add("Authorization", "MyUsername SuperPassword"); but I still get the 401 error from it.
EDIT: Nevermind, i figured it out
String username = "MyUsername";
String password = "SuperPassword";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
There is a awesome post about Send login details with HttpWebRequest and the link is post link
if You feel brother then you can also try one my Best solve this by using webClient class. example:
var url = #"...";
var mybar= new System.Collections.Specialized.NameValueCollection();
mybar.Add("username", "username");
mybar.Add("password", "password");
var client = new System.Net.WebClient();
var data = client.UploadValues(url, mybar);
var res = System.Text.Encoding.ASCII.GetString(data);
Console.WriteLine(res);
Console.ReadLine();

Categories