Get access-token and authorization - c#

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;

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();
}
}

Unauthorized access API

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.

How to add bearertoken to post/get restsharp automation testing

maybe anyone could help me with RestSharp api automation testing.
I'll try to be as clear as possible.
Basically the scheme is:
I'm sending my username/password credentials & I get BearerToken in return.
I parse the bearer token into a json file.
After I get the bearer token I need to "Authenticate" in order to get the information that I need.
For example i need full company credit report which I get after I input companyName ="Whatever"; companyCode = "Whatever";
{
var client = new RestClient("https://www.myapitesting.com/api/Auth/Authenticate");
var request = new RestRequest(Method.GET);
var body = new AuthenticatePostCredentials { Username = "myUserName", Password = "myPassword" };
request.AddJsonBody(body);
var response = client.Post(request);
HttpStatusCode statusCode = response.StatusCode;
int numericStatusCode = (int)statusCode;
request.AddHeader("content-type", "application/json");
var queryResult = client.Execute<object>(request).Data;
string jsonToken = JsonConvert.SerializeObject(queryResult);
var JSON1 = JToken.Parse(jsonToken);
var pureToken = JSON1.Value<string>("token");
File.WriteAllText(#"C:\Users\....\TestAPI\TestAPI\token.json", pureToken);
Console.WriteLine(pureToken);
Console.WriteLine(numericStatusCode)
The output I get is: token, status code 200 (correct credentials to get the bearertoken)
//////////At this point I get the token and it is writed into my json file/////////////// (the token works)
Now im trying to authenticate with my token and get the company information that I need
var client = new RestClient("https://www.myapitesting.com/api/GetCompanyReport");
var myRequest = new RestRequest(Method.POST);
myRequest.AddHeader("Accept", "application/json");
myRequest.AddHeader("Authorization", $"Bearer{pureToken}");
myRequest.AddHeader("content-type", "application/json");
var companyInfoInput = new AuthenticatePostCredentials { companyName = "MyCompanyName", companyCode = "MyCompanyCode" };
requestas.AddJsonBody(companyInfoInput);
var response = myRequest.Execute(request);
Console.WriteLine(response.Content);
The output I get is error code that says I havent authenticated, even though I pass the bearer token with my addHeader command.
{"ErrorId":401,"ErrorName":"Unauthorized","ErrorDescription":"User is not logged in"}
What am I doing wrong? Any kind of help would be greatly appreciated!
In this case, you could load the "Authenticator" you want to use, in the case of JWT you may instantiate something like this:
var authenticator = new JwtAuthenticator(pureToken);
and then set your client authenticator like this:
client.Authenticator = authenticator;
Mainly, you should not need to set headers by hand for the most commons ones using Restsharp.
You can for example fix this statement:
var myRequest = new RestRequest(url, DataFormat.Json);
var response = client.Post(request);
I also made this gist for you to check an example
If you want to see something more complete I also have this another gist

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);

Withings API and C#

I try to connect my home automation in c# with Withings but I don't achieve to do this.
I try this library but it doesn't work, the URL doesn't contain key or secret.
I try to use RestSharp :
RestClient client = new RestClient(baseUrl)
{
Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
};
RestRequest request = new RestRequest("account/request_token", Method.POST);
IRestResponse response = client.Execute(request);
NameValueCollection qs = HttpUtility.ParseQueryString(response.Content);
string oauthToken = qs["oauth_token"];
string oauthTokenSecret = qs["oauth_token_secret"];
PackageHost.WriteInfo("{0}", response.Content);
const string verifier = "5179055";
request = new RestRequest("account/access_token");
client.Authenticator = OAuth1Authenticator.ForAccessToken(
consumerKey, consumerSecret, oauthToken,
oauthTokenSecret, verifier);
response = client.Execute(request);
Assert.NotNull(response);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
qs = HttpUtility.ParseQueryString(response.Content);
oauthToken = qs["oauth_token"];
oauthTokenSecret = qs["oauth_token_secret"];
I succeed to authorize my application but I don't get the access token or secret. It says "Invalid verifier" but I get this verifier from authorization page, in url.
Anyone succeed to connect Withings with .net ?
Thank for your help.
I've been having the same issue. I decided on using Quantfabric. You can see my post on Medium, for instructions on how to use.

Categories

Resources