Asp.net and OAuth simple example without existing Library - asp.net

I try to get a request token from Twitter OAuth and I always received a server error 401 when I try to get the response. I don't want to used an existing library because I try to learn Oauth and maybe build my own library. This is my simple code :
WebRequest request = WebRequest.Create("https://api.twitter.com/oauth/request_token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
StringBuilder sbParams = new StringBuilder();
sbParams.Append("OAuth ");
sbParams.AppendFormat("oauth_consumer_key={0},", "[COMSUMERKEY]");
sbParams.AppendFormat("oauth_signature_method={0},", "PLAINTEXT");
sbParams.AppendFormat("oauth_signature={0},", HttpUtility.UrlEncode("[COMSUMER_SECRET]&"));
sbParams.AppendFormat("oauth_timestamp={0},", ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds).ToString());
sbParams.AppendFormat("oauth_nonce={0},", "asdfalkjpoijwpeonpoaisudfnpowieuyfpasosdfdn");
sbParams.AppendFormat("oauth_version={0},", "1.0");
sbParams.AppendFormat("oauth_callback={0}", HttpUtility.UrlEncode(Request.Url.ToString()));
request.Headers.Add("Authorization", sbParams.ToString());
// Get the response.
WebResponse response = request.GetResponse();

From http://oauth.net/core/1.0a/#http_codes You know these
HTTP 401 Unauthorized
Invalid Consumer Key
Invalid / expired Token
Invalid signature
Invalid / **used nonce
The "used nonce" thing may be a problem. You need to generate a random string. From http://oauth.net/core/1.0a/#nonce
A nonce is a random string, uniquely generated for each request
Onto the serious business. You are not supposed to transmit your consumer secret, once you ever received it! Many OAuth libraries have a
request_request_token(consumer_key,consumer_secret)
Despite appearances, the consumer_secret is never transmitted. It is used at client-side, for verification of server's response. (A similar verification occurs at server-side too)
And you dont put in any static values for signing requests. From http://oauth.net/core/1.0a/#signing_process
All Token requests and Protected Resources requests MUST be signed by the Consumer and verified by the Service Provider.
Bottomline: do read the http://oauth.net/core/1.0a/ article to see how the protocol works. And choose a hands-on OAuth library that doesnt abstract too much details (The oauth-php library I used came with SQL tables and managed data stores and session memory by itself).

Related

Encryption key retrieve on http call to the API?

Can you tell me if the following flow is good practice for retrieving encryption key?
So I have an Angular app which has custom encryption service created by me and a npm library, which now uses simple string value for key.
I also store access token inside a cookie and the value is encrypted.
Is it good practice, while executing a standard CRUD operation method against my API, first in this method to execute a separate http get request to get the encryption key from the API (from a separate endpoint), then de-crypt the cookie and THEN send it in the http request?
For example, look at this pseudo-code:
getAllProductsAsAdmin(): Observable<any>{
let encryptionKey = callApiAndGetKeyMethod(this.encryptionKeyApiUrl);
let decryptedCookie = decryptCookie(this.existingCookie, encryptionKey);
this.headers = this.headers.set('Authorization', decryptedCookie);
return this.httpClient.get<IGetProductAdminModel[]>(this.getAllProductsAsAdminUrl, {headers: this.headers})
.pipe(
tap(data => console.log('All:',JSON.stringify(data))),
catchError(this.handleError)
);

SAP .NET Connector, working with X509 certificates

We had a C# application connecting to SAP backend systemes using the SAPSSO technology. There has now been a need to replace this with X.509 certificates.
When using SAPSSO, the orginal code would make an HTTP call to the target system, and get a cookie containing the ticket to use:
response = (HttpWebResponse)request.GetResponse();
ticket = response.Cookies["MYSAPSSO2"].Value;
That ticket would then be passed to the RfcCustomDestination object to facilitate a secure connection:
prms.Add(RfcConfigParameters.SAPSSO2Ticket, ticket);
The problem is, I can change the enumerated value from SAPSSO2Ticket to X509Certificate,
prms.Add(RfcConfigParameters.X509Certificate, ticket);
but when I do this, no ticket can be returned from the response, since a MYSAPSSO2 cookie is no longer provided.
So how can I generate the needed ticket value for an X509 certificate?

How to verify a shopify webhook request in asp.net

Can someone explain how do I compute a HMAC
===============
To verify that the request came from Shopify, compute the HMAC digest according to the following algorithm and compare it to the value in the X-Shopify-Hmac-SHA256 header. If they match, you can be sure that the Webhook was sent from Shopify and the data has not been compromised.
Each Webhook request includes a X-Shopify-Hmac-SHA256 header which is generated using the app's shared secret, along with the data sent in the request.
I have the secret key... how can I combine the secret key + the data in the request to generate a HMAC
The easiest way is to use the ShopifySharp Library. You can use the Nuget package and install it in your project.
This is an example taken from the ShopifySharp website for validating webhooks:
NameValueCollection requestHeaders = Request.Headers;
Stream inputStream = Request.InputStream;
if(AuthorizationService.IsAuthenticWebhook(requestHeaders, inputStream, shopifySecretKey))
{
//Webhook is authentic.
}
else
{
//Webhook is not authentic and should not be acted on.
}
If you don't want to use ShopifySharp, you can see how they implemented it in the source code.

Not found exception when executing request in service account

I get the following error when retrieving the events of my calendar using service account.
Can anyone tell me what I'm doing wrong.
Google.Apis.Requests.RequestError Not Found [404]Errors [Message[Not Found] Location[ - ] Reason[notFound] Domain[global]]
//file path
string GoogleOAuth2CertificatePath = Server.MapPath("GoogleStore\My Project-a725fb0190fc.p12");
// #developer... e-mail address.
string GoogleOAuth2EmailAddress = "939544675132-compute#developer.gserviceaccount.com";
// certificate password ("notasecret").
string GoogleOAuth2PrivateKey = "notasecret";
X509Certificate2 certificate = new X509Certificate2(GoogleOAuth2CertificatePath, GoogleOAuth2PrivateKey, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(GoogleOAuth2EmailAddress)
{
Scopes = new[] { CalendarService.Scope.Calendar }
}.FromCertificate(certificate));
// Create the service.
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
ListRequest request = service.Events.List(calID);
request.ShowDeleted = false;
request.SingleEvents = true;
events = request.Execute();
Thank you for any answer what can help me.
Usually when encountering 404: Not found the specified resource was not found. This can happen in several cases.
when the requested resource has never existed.
when accessing a calendar that the user can not access.
Based on the Official Google Documentation, the suggested action is to implement exponential backoff.
Exponential backoff is a standard error handling strategy for network applications in which the client periodically retries a failed request over an increasing amount of time. If a high volume of requests or heavy network traffic causes the server to return errors, exponential backoff may be a good strategy for handling those errors. Conversely, it is not a relevant strategy for dealing with errors unrelated to rate-limiting, network volume or response times, such as invalid authorization credentials or file not found errors.
Used properly, exponential backoff increases the efficiency of bandwidth usage, reduces the number of requests required to get a successful response, and maximizes the throughput of requests in concurrent environments.
Take note that in every request, your application sends to the Google Calendar API must include an authorization token. The token also identifies your application to Google.
Here's a related SO ticket encountered 404 not found error: Error 404 when creating a calendar with Google Calendar Api v3 using c# .net

Android C2DM getting (401) Unauthorized

I have an Android application with an ASP.NET backend. I have the registration_id for the phone as well as an auth token from google for the application server that is performing a push.
When I make the http post request to C2DM so that the phone gets a message I keep getting the 401 Unauthorized. Here is how I'm making the request in .NET:
WebRequest myRequest = WebRequest.Create("https://android.apis.google.com/c2dm/send");
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.Method = "POST";
myRequest.Headers.Add("Authorization", "GoogleLogin auth=" + authId);
// buiold the post string
StringBuilder myPost = new StringBuilder();
myPost.AppendFormat("registration_id={0}", regId);
myPost.AppendFormat("&data.payload={0}", msg);
myPost.AppendFormat("&collapse_key={0}", colKey);
// write the post-string as a byte array
byte[] myData = ASCIIEncoding.ASCII.GetBytes(myPost.ToString());
myRequest.ContentLength = myData.Length;
Stream myStream = myRequest.GetRequestStream();
myStream.Write(myData, 0, myData.Length);
myStream.Close();
// Do the actual request and read the response stream
WebResponse myResponse = myRequest.GetResponse();
Stream myResponseStream = myResponse.GetResponseStream();
StreamReader myResponseReader = new StreamReader(myResponseStream);
string strResponse = myResponseReader.ReadToEnd();
myResponseReader.Close();
myResponseStream.Close();
Any help would be much appreciated.
Advice corner: Have some confidence in your code every once and a while! And, even Google messes up sometimes.
After spending about nine hours reading every blog post and article about Google OAuth and C2DM and trying different things in my code, I emailed Google. I'm excited to say that not only did I receive a response very quickly, but also that my account was messed up. Something went wrong while I was registering on their site and although it appeared that everything was working from the registration success email I received, it wasn't. I re-registered and everything works!
I have encountered a similar problem: error 401 "Unauthorized" while trying a google c2dm (cloud to device messaging) code sample. It looks like the example used to work as is, but now Google has changed its conditions. Before running code examples, you have to sign-up:
http://code.google.com/android/c2dm/signup.html
I signed up, and the stuff began to work in minutes.
I've got the same problem, i.e. suddenly my C2DM_ACCOUNT_EMAIL stopped working.
To solve the problem, just fill the registration again with same info and the same C2DM_ACCOUNT_EMAIL.
HTH

Resources