Unauthorized access API - c#

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.

Related

How to call a web api that has Oauth 2.0

Hi so we have an external web api we want to call to get data out. It is using oauth 2.0. Can somebody please explain how we would go about doing this in .NET either vb.net or c#. I have in the past created api, however this one seems very complicated. Firstly you have to be signed into their oauth web page they have which generates some cookies, using these cookies by syncing them up in postman we can see the data, however we need this to be within our .net app. Can somebody please help how we go about this. Some code would be useful.
Thanks
This is how usually OAuth 2 authentication works.
You basically log in with username and password (optional second factor) and then you receive a token, the so called Json Web Token or JWT (it holds encrypted information about your user, your access roles or groups you are member of as well as some timestamp which is the expiration time of the token).
In every subsequent request you make to the server, you pass this token in the request header (or in your case as cookie).
Example code:
Login request:
HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, new Uri(_baseUrl, "token"));
string body = JsonConvert.SerializeObject(new
{
Username = _userName,
Password = _password,
secondFactor = secondFactor
});
httpRequest.Content = new StringContent(body, Encoding.UTF8, "application/json");
var response = await client.SendAsync(httpRequest);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
TokenResult r = JsonConvert.DeserializeObject<TokenResult>(responseContent);
if (!string.IsNullOrWhiteSpace(r.token))
{
_token = r.token;
_tokenValidity = r.expirationDate;
_refreshToken = r.refreshToken;
_refreshTokenValidity = r.refreshTokenExpirationDate;
return _token;
}
else
{
throw new Exception($"Failed to get token from server.\r\n{responseContent}");
}
}
Now you use the _token in subsequent requests in the request header:
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _token);
using HttpResponseMessage response = await client.GetAsync(new Uri(_baseUrl, relativePath));
if (response.IsSuccessStatusCode)
{
using var stream = await response.Content.ReadAsStreamAsync();
stream.Position = 0;
using var reader = new StreamReader(stream);
reader.ReadToEnd();
}
Please note, that usually the token has a certain lifetime after which it is basically useless. Some APIs offer a refresh token with which a new token can be requested without the user having to log in again with username and password, but that's beyond the scope of this question.
You said you have to use the token as cookie? Well there are APIs which work like this but personally I've never seen one like this, which is why I can't you help very much, but it shouldn't be much more than putting the token you got into a cookie with a certain name.
Hope this helps.
Not sure what you are asking. I have a controller code where I use web api call to authenticate user. You can use your own model to pass the data. If your web api expects token for request, then you might have to get the token first to give a call to any method. Hope this helps.
OktaUserDetailsModel Model = new OktaUserDetailsModel();
Model.username = model.UserName;
Model.password = model.Password;
using (var httpClient = new HttpClient())
{
HttpContent inputContent = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(Model), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync(ConfigurationManager.AppSettings["OktaAPIuri"], inputContent).Result;
if (response.IsSuccessStatusCode)
{
string strResponse = (new JavaScriptSerializer()).Deserialize<string>(response.Content.ReadAsStringAsync().Result);
if (strResponse.ToUpper() == "TRUE")
return OktaSingleSignOnLogin(astrReturnUrl, model.UserName);
else
return ErrorPage();
}
else
{
return ErrorPage();
}
}

OpenID Connect Authentication Successful. Now what?

I'm writing a windows service in C# that needs to authenticate with an API and make some calls. I'm able to authenticate successfully with this API I'm talking to, but I can't seem to figure out how to use the response. The response looks like this:
{"access_token":"Es-Zjs_LI0tcXyLe3aEfgKPNLHN7CwyUhTss-cTld1A","expires_in":1800,"token_type":"Bearer","scope":"example","auth_state":1,"company":"examplecompany"}
I can get the access token out of that string if I want, but no matter how I pass it to a request, I get a 401 error. This is what my current iteration looks like:
string results = "";
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",token);
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://example.ca/endpoint"),
//Headers =
//{
// { "authorization", "Bearer"},
//},
};
try
{
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
results = body;
}
}
catch (Exception ex)
{
results = "ERROR: " + ex.Message;
}
return results;
Where "token" is the string "Es-Zjs_LI0tcXyLe3aEfgKPNLHN7CwyUhTss-cTld1A" in this example. I had previously tried stitching the access_token value as a string to the "Bearer" string in the commented out section in the middle there. What am I doing wrong? Do I need to make a JwtSecurityToken out of the response?
AuthenticationResult authResult = await daemonClient.AcquireTokenForClient(new[] { MSGraphScope })
.ExecuteAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
I've used the authResult.AccessToken. Not sure if it works in your scenario. The return type in my case was Microsoft.Identity.Client.AuthenticationResult type when I retrieved the token for a Graph API that I was using.
Be aware that the token you have received ("Es-Zjs_LI0tcXyLe3aEfgKPNLHN7CwyUhTss-cTld1A") is a reference token and not a JWT-token. Make sure your API accepts that type of token.
To use the token effectively in production then I would consider using the various helper methods found in the IdentityModel library and especially the Worker application helpers.
While I understand it's largely situational depending on what API you're trying to connect to, for me the solution was to use this method to pass in the authentication token:
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);

Calling a Rest API with Bearer token

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 ...

403 error when trying to get data from Reddit API

I am using oAuth to authenticate my app. I managed to get a code, access_token and refresh_token. So the next step would be trying to get info about the current user.
public async void GetCurrentUser()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);
var response = await client.GetAsync("https://oauth.reddit.com/api/v1/me");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
}
}
}
This is the method I am using to do that. However the response is always an 403 (Forbidden) error code. Any idea what could be wrong? The access_token is what I got when I made a request to https://oauth.reddit.com/api/v1/access_token
I think the token is correct because when I create the same request with Fiddler it works.
ANSWER:
Fixed it by adding a custom user-agent
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, _endpointUri + "me");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
request.Headers.Add("User-Agent", Uri.EscapeDataString("android:com.arnvanhoutte.redder:v1.2.3 (by /u/nerdiator)"));
var response = await client.SendAsync(request);

Get access-token and authorization

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;

Categories

Resources