public ActionResult getJiraTickets(string username, string password, string jiraUrl)
{
string queryString = jiraUrl + "/rest/api/2/search";
var client = new HttpClient { BaseAddress = new Uri(queryString) };
var credentials = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(queryString).Result;
if (response.IsSuccessStatusCode)
{
// use response
}
}
I get StatusCode: 401, ReasonPhrase: 'Unauthorized' in the response.
The queryString is correct because if I hit that URI using the browser I get a JSON response back.
Username and password are correct as well.
What am I doing wrong in the code?
Thanks
I apologise for not posting this as a comment, I don't have enough rep yet to post a comment.
I know you say your username and password are correct but I would double check them because I have taken your code and run it with my login details and Jira Url and it worked as expected.
Related
I have a web server on which I'm hosting my own api for one of my projects.
This is the php-code of the api-website:
$user = $_POST['username'];
$password = $_POST['password'];
if(strcmp($user, "username") == 0 && strcmp($password, "password") == 0) {
...
} else {
die("No Permissions");
}
I want to send the two variables username and password with a HttpClient and the postAsync-method to this website and if the right log in data is detected, it returns the data I want.
For this I have the following code in C#:
Task<HttpResponseMessage> response;
var url = "www.url.de"; //not the url I'm actually calling!
var vars = "[{\"username\":\"username\", \"password\":\"password\"}]";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
response = client.PostAsync(url, new StringContent(vars, Encoding.UTF8));
Console.WriteLine(response.Result.Content.ReadAsStringAsync().Result);
if (response.IsCompleted)
{
Console.WriteLine(response.Result.Content.ReadAsStringAsync().Result);
}
}
But the problem is that no matter what I have tried the output from this code is, that i have no permissions. And I have changed the php-code, so that I can see which data is stored in $username and $password, but they are empty and I don't know why. I hope somebody can help me with this.
Your PHP code is expecting the data sent as application/x-www-form-urlencoded, but your C# code is sending it as JSON.
As mentioned in the comment by M. Eriksson, you either need to change your PHP to accept JSON, or change your C# to send as form data.
This answer shows how to use HTTPClient to send data like that.
Here's my modification of your code based on the above code (I did test it):
public static async Task DoSomething()
{
string url = "http://httpbin.org/post"; //not the url I'm actually calling!
Dictionary<string, string> postData = new();
postData["username"] = "username";
postData["password"] = "password";
using HttpClient client = new();
client.DefaultRequestHeaders.Accept.Add(new("application/json"));
HttpRequestMessage request = new(HttpMethod.Post, url);
request.Content = new FormUrlEncodedContent(postData);
HttpResponseMessage response = await client.SendAsync(request);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
I have tried to get access token for PowerBI API with the following method and proper inputs for clientId, clientSecret, username and password but I get Bad Request saying required parameter 'grant_type' is missing.
public static async Task<string> GetToken()
{
var client = new RestClient();
var url = "https://login.microsoftonline.com/common/oauth2/token"
var request = new RestRequest(url, Method.POST, DataFormat.Json);
var body = new
{
grant_type = "password",
client_id = "clientId",
client_secret = "clientSecret",
username = "user",
password = "password",
resource = "https://analysis.windows.net/powerbi/api"
};
request.AddJsonBody(body);
var response = await client.ExecutePostAsync(request);
return response.Content;
}
Something wrong with by JSON body or something completely different?
Your request body needs to be form url encoded - not json
If you're using C# I'd recommend using the Identity model library to reduce mistakes.
Here is some sample code
I am trying to use HttpClient to GET information from Jira, but I am unable to see any of the information. I want to be able to get all the bugs that match certain filters so that I can add them to a table in my program.
I have tried to access Jira with the rest api, but every time I do it says that the issue or project doesn't exist. The thing is that if I enter the URI into the bar at the top of my browser I can see the JSON text that I want. This leads me to believe that the reason my code is not returning these values is because of an authorization issue. I am using basic auth to send my credentials. I also want to add that I used cURL in cmd to test my credentials with basic auth and it worked.
public async Task<JiraModel> GetBugs()
{
using (var client = new HttpClient())
{
string url = "https://myurl.atlassian.net/rest/api/3/project/VCMF";
String username = "username";
String password = "apikey";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Basic " + encoded);
client.BaseAddress = new Uri("https://myurl.atlassian.net/rest/api/3/project/VCMF");
var response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<JiraModel>(content);
}
}
I should be getting the json results in string form by the end of this length of code, but I keep getting a 404 error instead that for this code specifically says "No project could be found with key 'VCMF'".
The issue here is that you're creating the authorization header incorrectly.
The constructor you're using for AuthenticationHeaderValue class takes two arguments: scheme and parameter:
public AuthenticationHeaderValue(string scheme, string parameter)
{
}
The first argument should be the scheme (Basic in this case) and the second, the base64-encoded credentials:
So instead of:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Basic " + encoded);
It should be:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);
Hope this helps!
I am trying to make a httprequest to a web that is authenticated with ADFS of a private company.
I am able to login and get the token of my App. I am sure I am doing it correct due to I can get the contacts of my O365.After getting the token I try to make a request to the web. As I already have the token, I try to include it in the header of the request. The answer that I receive from the web is always the html with the login web not the result that I am requesting. As additional information I have added a "Connected Service" O365 API from VisualStudio.
This is my code:
public static async Task<string> GetAnswer(string wwweb)
{
var token = await GetAccessToken();
using (var client = new HttpClient())
{
var url = wwweb;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//client.DefaultRequestHeaders.ProxyAuthorization= new AuthenticationHeaderValue("Bearer", token);
// client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var response = await client.GetStringAsync(url);
return response;
}
}
I have tried with the 3 lines ( 2 commented and one not) without success, always giving back company's login web. Am I doing something wrong?
Thanks
So basically, I am trying to connect to a REST API online. Easy enough right?
However I am getting a 401 (Unauthorized) error whenever I try to connect. I am using a C# console app to test this, and I have also tried using PUTMAN (Google Chrome App to view HTTP Requests).
Here is the link to the API I am using: https://community.dynatrace.com/community/display/APMSAASDOC/Login+-+REST+API
I follow all the steps listed. I know my username and password is correct (have logged into the Dynatrace Portal). Does anyone have any ideas what could be wrong? Here is my code below (I have removed the actual username and password for obvious reasons):
static async Task RunAsync()
{
string _user;
string _password;
string _authorizationType;
string _contentType;
string _CredentialsToBase64;
string _url = "https://datafeed-api.dynatrace.com";
_user = "MYUSERNAME";
_password = "MYPASSWORD";
_authorizationType = "basic";
_contentType = "application/json";
_CredentialsToBase64 = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(_user + ":" + _password));
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_contentType));
client.DefaultRequestHeaders.Add("Authorization", _authorizationType + " " + _CredentialsToBase64);
using (HttpResponseMessage httpResponse = await client.GetAsync("publicapi/rest/v1.0/login?user=MYUSERNAME&password=MYPASSWORD HTTP/1.1"))
{
if (httpResponse.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine(string.Format("Service request failed ({0})", httpResponse.StatusCode));
}
}
}
The HTTP/1.1 string at the end of the client.GetAsync method call is probably being translated into password=MYPASSWORD%20HTTP/1.1 (or similar) which results in the error. Try removing that, and see if it works.
Note: %20 is a urlencoded space
Another Option The answer to this post might be related. To summarize, it appears that formatting a request requires the BaseAddress to have a trailing slash and the GetAsync string to not start with a slash.
Sorry for the headache everyone. The problem was an account issue with the company itself. I contacted them and they noticed the problem was with a migration of accounts from a old to new portal. So there was nothing wrong with our end. Thanks for your help everyone!
Remove " HTTP/1.1" from the end of your GET url, its being added to the end of your password, hence the 401