I'm trying to consume a REST api with bearer token authentication. I'm getting this error:
Media type is unsupported
Code:
using System;
using RestSharp;
using System.Configuration;
using Newtonsoft.Json.Linq;
string Authtoken = "My OAuth token";
var client = new RestClient(DataserviceURL);
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + Authtoken);
try
{
IRestResponse response = client.Execute(request);
var obj = JObject.Parse(response.Content);
Console.WriteLine("Data_" + response.Content);
Console.ReadLine();
}
catch (Exception ex) { string ex1 = ex.ToString(); }
You most likely just need to add a HTTP header like this:
var request = new RestRequest(Method.POST);
request.Headers.Add("Content-Type", "application/json");
to clarify what type of content you're sending in your POST body (that is assuming you are sending JSON in your POST body - otherwise adapt as needed).
This has nothing to do with your bearer token authentication ...
Related
I'm trying to access an API via C# but it's giving an UNAUTHORIZED error, I've tried it with the CURL command in CMD it's working, but in C# code it doesn't work, what's wrong:
try
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://services.efatura.cv/v1/dfe/pdf/CV1220223253095794000010100000000184794720477"))
{
request.Headers.TryAddWithoutValidation("accept", "application/xml");
request.Headers.TryAddWithoutValidation("cv-ef-repository-code", "1");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer //BearerToken here//");
var response = await httpClient.SendAsync(request);
var contents = await response.Content.ReadAsStringAsync();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I'm guessing that your code is exactly the same as your snippet here. In that case you need to actually add a bearer token in the Authorisation header.
Usually you can get the bearer token through another GET endpoint with a username and password.
Alternatively you can try to use another form of API authorisation if possible.
I am trying too make a rest call with C# for the first time.
I think im very close but i get an error message : Error: 400 - Bad Request.
Here is my Code:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.test123.com/oauth2/token"))
{
string webstring = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id=${2}&client_secret={3}", access_code_string, RedirectURI,ClientId, ClientSecret);
Console.WriteLine(webstring);
request.Content = new StringContent(webstring);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
Console.WriteLine("Access token: " + response);
}
}
Here is an sample code from Curl
curl -X POST \
--header "Content-Type: application/x-www-form-urlencoded" \
--data "grant_type=authorization_code&code=dlZE0KFxhM&redirect_uri=http%3A%2F%2Fclient%2eexample%2Ecom&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET"
"https://api.test123.com/oauth2/token"
This is the description:
Obtain an access token
After you have received the authorization code you can request an access token.
Method
POST
URL
https://api.test123.com/oauth2/token
Request format
application/x-www-form-urlencoded
Request parameters
Name Type Description
grant_type String Value must be set to authorization_code
code String The authorization code
client_id String
client_secret String
redirect_uri String The URL where the response is sent. Must match the registered redirect URI.
Response format
application/json
I took an different approach
public void call()
{
string access_code_string = Read_Json_Values("accsess_code");
string webstring = String.Format("https://api.test123.com/oauth2/token?grant_type=authorization_code&code={0}&client_id=${1}&client_secret={2}&redirect_uri={3}", access_code_string, ClientId, ClientSecret, RedirectURI);
var client = new RestClient(webstring);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", "Bearer xxxx");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.WriteLine(response.Content);
}
Getting StatusCode: UnsupportedMediaType for file upload. I am using RestClient with bearer token
I got the bearer token successfully, but when sending the JSON to the API I'm getting the exception unsupported media type
var client = new RestClient(requestAPIURL);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", string.Format("Bearer " +
token.AccessToken));
request.AddParameter("application/json",
JsonConvert.SerializeObject(jsonData), ParameterType.RequestBody);
var response = client.Execute(request);
POST the JSON in the request body:
request.AddBody(JsonConvert.SerializeObject(jsonData));
I am trying to POST a JSON with HhttpClient using a permanent token authorization, but I always get an error 401 Unauthorized code:
public static async Task<Uri> CrearitemAsync(Item item)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("OAuth", AuthToken);
HttpResponseMessage response = await client.PostAsJsonAsync(
"items/" + IdProvider, JsonConvert.SerializeObject(item));
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
}
I also tried this:
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthToken);
The token seems to be fine. It is an alphanumeric string all lower case. Is this the correct way to use a permanent token?
update The key i have to use for the header is: IDENTITY_KEY
but still failing
finally it worked with Add.. had to use this 'key' value rather than authorization in the header:
client.DefaultRequestHeaders.Add("IDENTITY_KEY", AuthToken);
I have to upload files to box.com for that i need authorize and get accesstoken and refresh token. I am not finding any code in c# asp.net.i want code for authentication using c# and asp.net and code for getting accesstoken and refresh token. I tried below code am getting error as page is Expired request again.
Here is the code in c# asp.net.I am trying using Restsharp
public void GetAccessToken(string code, string ClientId, string ClientSecret)
{
RestClient rs = new RestClient();
string grant_type = "authorization_code";
RestRequest request = new RestRequest(Method.POST);
IRestRequest reuest = request;
string strHeaders = null;
RestResponse response = default(RestResponse);
IRestResponse resp = response;
string strResponse = null;
try
{
rs.BaseUrl = "https://www.box.com/api/oauth2/token";
request.Resource = "oauth2/token";
strHeaders = string.Format("grant_type={0}&code={1}&client_id={2}&client_secret={3}", grant_type, code, clientId, Clientsecret);
request.AddHeader("Authorization", strHeaders);
resp = rs.Execute(reuest);
strResponse = resp.Content;
Label1.Text = strResponse;
}
catch (Exception ex)
{
throw ex;
}
}
From the documentation:
https://developers.box.com/oauth/
(See "Getting the Access Token")
When exchanging an auth code for a set of access tokens and refresh tokens, you need to make a POST request to the https://www.box.com/api/oauth2/token endpoint.
Try taking what you're adding in the "Authorization" part of your header, and putting it in a URL encoded POST body.
Or even better, try the available .NET SDK which will handle this very part of the OAuth workflow for you:
https://github.com/box/box-windows-sdk-v2
You also need to set the encoding with:
request.RequestFormat = DataFormat.Xml;