Access Nexmo C# API using OAuth - c#

I am accessing Nexmo API by passing API Key and API Secret. Nexmo uses OAuth 1.0a and I have managed to retrieve the Access Token and Token Secret using DotNetOpenAuth. I have no previous experience with Nexmo. I want to know that how to use Access Token and Token Secret instead of API Key and API Secret. On nexmo website there is not lot of help about this. There is a line written on the bottom of following URl (https://labs.nexmo.com/#oauth) which says "replace "api_key" and "api_secret" by OAuth parameters". I don't know how to do that. Does anyone know?
Hi, I have seen the PHP example but didn't understand much from it. May be I am not getting the idea of OAuth completely. I am using DotNetOpenAuth for signing with Nexmo website. Following is the code I have used so far,
Dim consumer3 As New DesktopConsumer(NexmoDescriptionService.Description, NexmoDescriptionService.TokenManager)
Dim requestToken As String = ""
consumer3.RequestUserAuthorization(Nothing, Nothing, requestToken)
Dim extraParameters = New Dictionary(Of String, String) From {{"request_token", requestToken}}
consumer3 = New DesktopConsumer(NexmoDescriptionService.Description.UserAuthorizationEndpoint, NexmoDescriptionService.TokenManager)
Dim test = consumer3.RequestUserAuthorization(extraParameters, Nothing, requestToken)
Dim request As System.Net.HttpWebRequest = consumer3.PrepareAuthorizedRequest(NexmoDescriptionService.Description.RequestTokenEndpoint, requestToken)
I have used Desktop consumer class because was not able to work with WebConsumer.

There's a screencast here, using PHP, it should be roughly the same for C#. You really don't want to manage the OAuth signing yourself, find a good C# library that does it for you, then just make the request through that.
This example and library may be helpful. At the end of the example, it shows making a call to google after the session has been setup to use the access token. You'll just go through a similar process with Nexmo:
// make a request for a protected resource
string responseText = session.Request().Get().ForUrl("http://www.google.com/m8/feeds/contacts/default/base").ToString();
As to OAuth in genral, the flow is essentially:
Get a Request Token from the Service (in this case Nexmo). That request token is matched to the application credentials you'll already have (you can create these from the Nexmo dashboard).
Redirect to user to authorize that request token. At this point you just wait for the user to be redirected back with an authorized token.
When the user is redirected back with an authorized token, trade that for a long use token, and store the credentials (you'll use those credentials any time you need to make requests on behalf of the user's account).
For the most part, OAuth Client libraries handle all the details, and your application only needs to be concerned with the high level flow.
You can find more information on the OAuth flow at the OAuth site.

Related

DocuSign JWT Impersonation Issues

I'm working through the JWT impersonation flows documented here and here. I'm using C#, and though I have worked through a few of the quick start applications, I'm still having some issues.
Existing Flow
The flow I have so far, which seems to be functional in DS sandbox/dev/demo, is:
Send user to DocuSign (oauth/auth). scope is "signature impersonation". (I've tried it with a bunch more permissions thrown in as well.)
After DS auth and impersonation grant, user shows back up on my web app with an authorization code
Take that authorization code and post it to oauth/token to get an access token for my target user
Take that access token and call oauth/userinfo to get the target user's IDs and URL
Create a JWT, sign using shared key pair between my web app and DS, and post it to oauth/token. Receive a 200 response with a seemingly-good-looking token.
This all seems to work correctly so far: all DS calls come back with 200s and data which is shaped as I expect.
Problems
The issue is that I can't actually successfully use that token from the final step to perform further action as the user who my app is impersonating. (I am being sure to use the base_url for the associated user.) When I request a GET from the suggested endpoint (brands), I receive this back:
{
"errorCode": "AUTHORIZATION_INVALID_TOKEN",
"message": "The access token provided is expired, revoked or malformed. Authentication for System Application failed."
}
The response which provided the authorization token includes an expires_in value in the thousands of seconds, and I'm performing all of these requests in serial in my web application. So, expiration or revocation should not be possible at this point. I also haven't touched the token at all, so I would expect it to be well formed.
Here's the code I'm using to post to that endpoint, if it's useful:
private async Task<IgnoreMe> GetBrands(UserInfoAccount account, AccessTokenResponse accessToken)
{
var client = _clientFactory.CreateClient("docusign");
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{account.BaseUri}/restapi/v2.1/accounts/{account.Id}/brands"),
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.AccessToken!);
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
return IgnoreMe.Fail;
}
return IgnoreMe.Succeed;
}
The args to this method are the values which came back from previous API calls: the AccessTokenResponse is from the impersonation call.
I've also tried sending similar requests to several other top-level user/account endpoints, and have received the same or similar errors for all of them.
What am I missing here?
Your flow is a mix if Auth Code Grant and JWT. You are using both.
The token from step 3 should work (But you can omit "impersonation" as it's not required for Auth Code Grant).
The token expires after 8 hours. That may be the reason for your error. You'll need to obtain a new one.
In this particular case, the problem was that I had used the wrong ID for the sub value when constructing the JWT.
Results from the oauth/userinfo endpoint I'm using come back structured as a top-level user ID which is associated with a bucket of accounts. I had used an account ID from one of those buckets rather than the top-level user ID.

Use MSAL in .NET C# to execute a custom policy flow in Azure AD B2C

I am currently using OpenIdConnect to execute HTTP GET requests for my Azure B2C custom policies. For example here is the Unified SignInSignUp:
public static void Unified(HttpRequest Request, HttpResponse Response)
{
string nonce = "defaultNonce";
string clientID = ConfigurationManager.AppSettings["aad.clientid"];
string authUrl = ConfigurationManager.AppSettings["aad.authUrl"];
string redirectUri = ConfigurationManager.AppSettings["aad.redirecturi"];
string unifiedPolicy = ConfigurationManager.AppSettings["aad.unifiedPolicy"];
// build url for AAD auth and redirect to ourself
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}?", authUrl);
sb.AppendFormat("p={0}", unifiedPolicy);
sb.AppendFormat("&client_id={0}", clientID);
sb.AppendFormat("&redirect_uri={0}", redirectUri);
sb.AppendFormat("&nonce={0}", nonce);
sb.AppendFormat("&scope=openid");
sb.AppendFormat("&response_type=id_token");
sb.AppendFormat("&prompt=login");
sb.AppendFormat("&response_mode=form_post");
// redirect to auth via AAD (and then redirect back to ourself)
Response.Redirect(sb.ToString(), true);
}
I would like to use MSAL instead but am having trouble finding a C# .NET sample that executes an HTTP GET request like I am doing with OpenIdConnect. My current technique returns the id_token just fine, but I would like to take advantage of MSAL's capabilities like caching etc.
Is such a sample around?
I wanted to add this as a comment, but the system indicated it was too long. So I would like to answer my question, since I did find some sample code (mentioned in my comment to self above) that helped me get started ~using~ MSAL.net. However I am having a number of issues (e.g. when I call my edit profile custom policy the set of claims I get is are very incomplete, using OpenIdConnect I get all my claims) and questions and will probably post another questions that is more specific, laying out my requirements. I really just need the id_token (and the OpenId Connect code I posted above was great for that), not the access or refresh tokens, and all I really need to do is validate that id_token and implement a KMSI (keep me signed in) strategy. I have added the B2C KMSI in my custom sign-in policy, but can't see how to query it in my web (asp.net web forms) web project. Currently (without using Azure) I have a "remember me" checkbox on my website and I write a persistent cookie with a rolling 30-day expiry with encrypted data in it and everything works as required; I am trying to move to Azure B2C and keep that all working.Also for validating the token I am currently using some code I found in a post here that uses low-level code (System.Security.Cryptography namespace) and it validates well, but I don't see how to validate the few claims that are recommended in documentation I have seen. So I will create a new post that inquires about all that. Thanks.

Authenticating App with OAuth from C#

I am writing an app that will talk with Salesforce. Salesforce provides access to APIs via OAuth. I've been attempting to go through the OAuth authentication process described here. Currently, I'm attempting to authorize my app. I have the following code.
// Ask Salesforce for a request token
var request = (HttpWebRequest)(WebRequest.Create(String.Format("https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id={0}&redirect_uri=http://localhost:5004/home/AuthCallback", CONSUMER_KEY)));
request.Method = "POST";
request.ContentType = "application/json";
// Retrieve the request token from the response
var response = (HttpWebResponse)(request.GetResponse());
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string accessCodeData = accessCodeReader.ReadToEnd();
}
This code is triggered when a user clicks a button in my ASP.NET MVC view. When executed, this code calls to Salesforce. I see a request in fiddler. The request header looks like this:
POST /services/oauth2/authorize?response_type=code&client_id={consumerKey}&redirect_uri=http://localhost:5004/home/AuthCallback HTTP/1.1
I am in fact passing my consumer key, I'm just removing it from the example. Regardless, this request returns a 302, with a body size of 0. I might be misunderstanding something. However, I was expecting to get a request token. I was then going to use the request token to get the access token.
What am I doing wrong?
You are misusing the API.
Take a closer look at the sequence diagram at their page (under Obtaining an Access Token): in the auhorization_code flow you are supposed to redirect the browser to their page so that the user sees the login page, provides his/her credentials and you get the token back. Instead, you are trying to POST there using a web request from your server.
This particular flow belongs then to the passive flows group, this group is intended to be used in browser apps, your server redirects the browser to their server and you basically get the response to the uri passed in the redirect_uri parameter and this should point back to your application at your server.
There are other flows, of them one is suited for non-browser apps, it is called resource owner password flow. In this flow it is your application that hosts the login UI and you send the username/password to the authorization server and you get the token back. It is to be read in their docs however whether this flow is supported.
Read more here: http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified
Take a look how I handle the OAuth2 flow to Google, using the DotNetOpenAuth library. This is a direct solution, applying it to any other provider should be straightforward.
http://www.wiktorzychla.com/2014/11/simple-oauth2-federated-authentication.html

How to use OAuth accesstoken to acquire profile images from various providers using DotNetOpenAuth.AspNet and Microsoft.AspNet.Membership.OpenAuth?

I've created a web application that uses the OAuth authentication and universal connectors as explained in this tutorial, and started to fiddle around a little to add support for other providers like Yahoo and LinkedIn. So the authentication part works and users are created in the asp.net Membership provider. Also, all the providers return the accesstoken which I supposedly can use to retrieve more information regarding the user.
I'd really like to acquire the profile image, but it seems every provider has a different way of requesting this information. Twitter even describes a way to authorise every request by changing the HTTP header information.
Whilst reading this information on the websites of the various providers I was wondering whether this functionality isn't also already included somewhere in DotNetOpenAuth.AspNet or Microsoft.AspNet.Membership.OpenAuth implementation.
How can I use DotNetOpenAuth.AspNet and/or Microsoft.AspNet.Membership.OpenAuth to request the profile image of the loggedin user using the just acquired accesstoken?
UPDATE in response to Leo's answer
I use the following code to make a call on LinkedIn's API.
string accessToken = extraData["accesstoken"]; // Extra Data received from OAuth containing the accesstoken.
WebRequest request = WebRequest.Create("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,date-of-birth,email-address,picture-url)?oauth2_access_token=" + accessToken);
using (WebResponse response = request.GetResponse())
{
// do something with response here.
}
Error message is "The remote server returned an error: (401) Unauthorized.".
What am I doing wrong?
The answer is simple...you can't use any of these. These are wrappers of OAuth and OAuth only specifies how you can authenticate a user. Now, to request the user's profile photo you will need to use the external provider's own API and you will need most likely a valid access token. So, you will need to use one of these implementations of OAuth to authenticate a user and the recieve an access token, store the access token somewhere (usually a cookie) and then use the access token to make sub-sequent calls to the provider's APIs. Examples and links....
Facebook's Graph API allows you to retrieve users profiles
https://developers.facebook.com/docs/graph-api/quickstart/
notice that all examples in the link above will require you to include the access token in a parameter named access_token, for example
https://graph.facebook.com/me?method=GET&format=json&suppress_http_code=1&access_token={your-access-token}
Google...
https://www.googleapis.com/oauth2/v3/userinfo?access_token={your-access-token}
LinkedIn...
https://api.linkedin.com/v1/people/~:(id,first-name,last-name,date-of-birth,email-address,picture-url)?oauth2_access_token={your-access-token}
You can get more specific information from these providers' websites
Let me know if you have any other doubts I might be able to help you since I have implemented stuff like these before.
Cheers, Leo

Is it possible to retrieve a list of Facebook friends via Server Side?

I have no idea how to start to retrieve my Facebook friends using the Facebook API. I have read the Graph API docs.
Secondly, I'm doing TDD so I want to start with my test cases.
At first, these will be integration tests because I have to integrate the real life Facebook api. After that works, I'll mock out these tests to make them unit tests.
So this is why I'm stuck. Please assume that I have a Facebook account (eg. email + password) so I can authenticate and then use the access token to get my friends.
UPDATE:
I also do have an FB App already setup (eg. app id / app secret).
The first thing that you need to do to get the list of friends, or any other api request on the behalf of the user, is to authenticate the user and get a user access token.
There are two authentication flows:
Client-Side: will result with a short lived access token (expires within a few hours) which you can then extend (on the server side) for a long lived using the new endpoint.
Server-Side: results with a long lived access token for about 60 days.
It will probably be hard to do that with TDD (at least at first), and so you might want to use one of the following facebook tools which will generate the access token for you:
Access Token Tool: gives you a list of `access tokens for all your apps bound to your own user'. Per application you get both a user token and an app token.
Graph API Explorer: Select your application at the top right corner and then click the "Get Access Token" button, then select the permissions you need and approve it, when the dialog closes you'll see the access token in the field.
With the access token that you get you can start querying the api.
To get the list of friends simply issue a request to me/fiends as explained in the Friends connection of the User object documentation.
I'm not a C# developer, but I'm aware of this C# SDK for Facebook, it should (like all other facebook SDKs) have implemented most of the work for you for sending the api requests and parsing the returned data.
From a quick look at their getting started documentation it should look something like:
var accessToken = "THE ACCESS TOKEN YOU HAVE";
var client = new FacebookClient(accessToken);
dynamic me = client.Get("me/friends");
...

Categories

Resources