How to write method in ASP.net to get the token from OAuthAPI - asp.net

Getting Access token from OAuth and passing it in the header for each of the request.
I have api at: https://login.microsoftonline.com/48b0431c-82f6-4ad2-a023-ac96dbf5614e/oauth2/token
And in Postman can see the access token getting returned.
I am trying to call this APIM api in my existing 4.5 .NET application. And wrote the following:
Dim client = InitializeTokenClient()
Using content As New StringContent(String.Empty)
Dim response = client.PostAsync($"48b0431c-82f6-4ad2-a023-ac96dbf5614e/oauth2/token", content).Result
If (response.StatusCode = HttpStatusCode.OK) Then
response.
End If
Return response
End Using
I am not sure how to access the access_token from the response object and also how would I be passing the access token to make subsequent APIM api calls?

You can take the access_token from the response by deserializing the response:
Add a reference to System.Web.Extensions and add Imports System.Web.Script.Serialization to the top of your file. Then the following code will get the access_token:
Dim j As Object = New JavaScriptSerializer().Deserialize(Of Object)(response)
Dim accessToken = j("access_token")
You can then use the token when calling the API by adding an Authorization header with the value Bearer <token>.

Related

WooCommerce rest api access failing with httpWebRequest

I am trying to get WooCommerce data using WooCommerce v3 API from c#.
When I use below url in browser I get the products data as json;
https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890
When I use url
https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products
and
consumer_key = ck_12345678901234567890 and consumer_secret = cs_12345678901234567890
as Params in Postman then I get the products data as well. So the credentials and url are valid.
However when I try to do this using HttpWebRequest it fails with "The remote server returned an error: (401) Unauthorized" exception. My code is below and the exception appears on the last line of code.
The vales in HttpWebRequest before the GetResponseAsync call can be seen here.
What am I doing wrong?
Thanks
Regards
string wc_url = "https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890";
HttpWebRequest httpWebRequest = null;
httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url);
httpWebRequest.AllowReadStreamBuffering = false;
WebResponse wr = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);

bad http authentication header format auth0 asp.net

I am using auth0 with ASP.NET for roles and permission implementation. I want to fetch all users details by using auth0 api. Below is my code,
Code 1:
var apiClient = new ManagementApiClient("Bearer <<Token>>", new Uri("<<URL>>"));
var allClients = await apiClient.Clients.GetAllAsync();
Code 2:
var client = new ManagementApiClient("Authorization: Bearer <<Token>>", new Uri("<<URL>>"));
IPagedList<User> users = await client.Users.GetAllAsync();
Above both code giving me error:
"bad http authentication header format auth0 asp.net"
tried same token and url in postman, And it's returning result,
Where I need to change to make it work?
According to the usage documentation for the ManagementApiClient class, the constructor receives just the token, so you should be calling it like:
new ManagementApiClient("<<Token>>", new Uri("<<URL>>"));
It will then automatically include that token in an HTTP Authorization header using the Bearer scheme.

Azure AD Graph API 400 Bad Request and 401 Unauthorized Error

I get a 400 Bad Request with this code:
Dim client As New WebClient()
client.Headers.Add("content-type", "application/x-www-form-urlencoded")
client.Headers.Add("Authorization", "Bearer **my-access-token-here**")
Dim groupsResponse As String = client.UploadString("https://graph.windows.net/myorganization/groups", "api-version=1.6")
I get a 401 Unauthorized with this code:
Dim client As New WebClient()
client.Headers.Add("content-type", "application/x-www-form-urlencoded")
client.Headers.Add("Authorization", "Bearer **my-access-token-here**")
Dim groupsResponse As String = client.DownloadString("https://graph.windows.net/myorganization/groups?api-version=1.6")
I'm getting my accesstoken from this OAuth2 endpoint:
https://login.microsoftonline.com/**my-tentant-id-here**/oauth2/token
Where it says "myorganization" I also tried it with my tenant id in place of "myorganization". With the same results.
What am I doing wrong?
The 400 error is because you were trying to post the incorrect data format(string) to the wrong REST API endpoint.
If you want to request the groups, you can refer the REST below(refer here):
get: https://graph.windows.net/{tenant_id}/groups?api-version=1.6
For the 401 error, you may show the detail error message so that we can identity the root reason. And you can also parse the token from here to verify whether the aud claim is https://graph.windows.net and is there enough permission to call the Group REST like Group.Read.All, Group.ReadWrite.All, Directory.Read.All and Directory.ReadWrite.All.

QuickBooks OAuth API (401) Unauthorized

Here is the OAuth library I'm using: https://github.com/danielcrenna/oauth
I'm getting the token, secret and realmId (company id) just fine and storing them, but when I go to do a simple request, I get (401) Unauthorized.
Here's the code I'm using:
var rq = new OAuthRequest
{
Method = "GET",
Type = OAuthRequestType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Token = requestToken,
TokenSecret = requestTokenSecret,
RequestUrl = "https://quickbooks.api.intuit.com/v3/company/" + realmId + "/query?query=select%20%2A%20from%20CompanyInfo&minorversion=4",
Version = "1.0",
};
And the Auth header:
OAuth oauth_consumer_key="****",oauth_nonce="6su4ljd2is5bxns4",oauth_signature="0taFXiouzOkpK258tz%2Fc%2F2fVQ0c%3D",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1461339515",oauth_token="****",oauth_version="1.0"
I can't find any other details in the error, I'm just getting "401 Unauthorized." How do I get this request to go through?
Oauth is pretty strict in how the header is written. Why not use one of the Libraries already provided by Intuit? or use the API Explorer to view the header and compare to your request header?
The order of the oauth header parameters matter, and version is not the last one. See this guide.
https://developer.intuit.com/docs/0050_quickbooks_api/0010_your_first_request/rest_essentials_for_the_quickbooks_api

ASP.Net Web API - Authorization header blank

I am having to re-write an existing REST API using .NET (originally written with Ruby). From the client's perspective, it has to work exactly the same way as the old API - i.e. the client code mustn't need to change. The current API requires Basic Authentication. So to call the old API, the following works perfectly:-
var wc = new System.Net.WebClient();
var myCache = new CredentialCache();
myCache.Add(new Uri(url), "Basic", new NetworkCredential("XXX", "XXX"));
wc.Credentials = myCache;
var returnBytes = wc.DownloadData("http://xxxx");
(I have had to ommit the real URL / username / password etc for security reasons).
Now I am writing the new API using ASP.Net Web API with MVC4. I have a weird problem and cannot find anybody else with exactly the same problem. In order to support Basic Authentication, I have followed the guidelines here:
http://sixgun.wordpress.com/2012/02/29/asp-net-web-api-basic-authentication/
One thing, I put the code to "hook in the handler" in the Global.asax.cs file in the Application_Start() event (that wasn't explained so I guessed).
Anyway, if I call my API (which I have deployed in IIS) using the above code, the Authorization header is always null, and the above fails with 401 Unauthorized. However, if I manually set the header using this code, it works fine - i.e. the Authorization header now exists and I am able to Authenticate the user.
private void SetBasicAuthHeader(WebClient request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
.......
var wc = new System.Net.WebClient();
SetBasicAuthHeader(request, "XXXX", "XXXX");
var returnBytes = wc.DownloadData("http://xxxx");
Although that works, it's no good to me because existing users of the existing API are not going to be manually setting the header.
Reading up on how Basic Authentication works, the initial request is meant to be anonymous, then the client is returned 401, then the client is meant to try again. However if I put a break point in my code, it will never hit the code again in Antony's example. I was expecting my breakpoint to be hit twice.
Any ideas how I can get this to work?
You're expecting the right behavior. System.Net.WebClient does not automatically include the Authorization headers upon initial request. It only sends them when properly challenged by a response, which to my knowledge is a 401 status code and a proper WWW-Authenticate header. See here and here for further info.
I'm assuming your basic authentication handler is not returning the WWW-Authenticate header and as such WebClient never even attempts to send the credentials on a second request. You should be able to watch this in Fiddler or a similar tool.
If your handler did something like this, you should witness the WebClient approach working:
//if is not authenticated or Authorization header is null
return base.SendAsync(request, cancellationToken).ContinueWith(task =>
{
var response = task.Result;
response.StatusCode = HttpStatusCode.Unauthorized;
response.Headers.Add("WWW-Authenticate", "Basic realm=\"www.whatever.com\"");
return response;
});
//else (is authenticated)
return base.SendAsync(request, cancellationToken);
As you noticed, if you include the Authorization headers on every request (like you did in your alternative approach) then your handler already works as is. So it may be sufficient - it just isn't for WebClient and other clients that operate in the same way.

Resources