Using OAuth2 eBay authentication with .NET SDK - c#

I have been searching throughout the internet for a solution to use OAuth2 user token with eBay's .NET SDK and could find ANY SINGLE solution. The code I have is like following:
var ctx = new ApiContext();
ctx.Version = "897";
ctx.ApiCredential.ApiAccount.Application = "//something here";
ctx.ApiCredential.ApiAccount.Developer = "//something here";
ctx.ApiCredential.ApiAccount.Certificate = "//something here";
ctx.ApiCredential.eBayToken = "v^1.1... // this is OAuth2 token";
var getUser = new GetUserCall();
getUser.OutputSelector = new string[] { "UserID","Site" };
getUser.GetUser();
What I find really irritating is the fact that there is a possibility to use the new OAuth2 token with trading API, and I know this for a fact, because if you add an HTTP header to any Trading API call like:
X-EBAY-API-IAF-TOKEN:q2eq2eq2eq2q2eq2e
It will work, but I haven't found anywhere in the documentation to pass the IAF-TOKEN (OAuth2) token via .NET SDK calls...
Has anyone else been trying this? Is there nay way to pass the OAuth2 token via .NET SDK and then fetch the results ?
Because if I try to pass the OAuth2 token like this:
ctx.ApiCredential.eBayToken = "v^1.1... // this is OAuth2 token";
In place where the traditional Auth'n'Auth token went, I'm getting the following error:
validation of the authentication token in api request failed.
Can someone help me out please ?!

Related

MSAL Error message AADSTS65005 when trying to get token for accessing custom api

I downloaded the example below to get an access token from MS Graph and it worked fine. Now I changed the code to get a token from a custom web API. On apps.dev.microsoft.com I registered a client application and an the API.
Client and server registration in AD
private static async Task<AuthenticationResult> GetToken()
{
const string clientId = "185adc28-7e72-4f07-a052-651755513825";
var clientApp = new PublicClientApplication(clientId);
AuthenticationResult result = null;
string[] scopes = new string[] { "api://f69953b0-2d7f-4523-a8df-01f216b55200/Test" };
try
{
result = await clientApp.AcquireTokenAsync(scopes, "", UIBehavior.SelectAccount, string.Empty);
}
catch (Exception x)
{
if (x.Message == "User canceled authentication")
{
}
return null;
}
return result;
}
When I run the code I login to AD via the dialog en get the following exception in the debugger:
Error: Invalid client Message = "AADSTS65005: The application
'CoreWebAPIAzureADClient' asked for scope 'offline_access' that
doesn't exist on the resource. Contact the app vendor.\r\nTrace ID:
56a4b5ad-8ca1-4c41-b961-c74d84911300\r\nCorrelation ID:
a4350378-b802-4364-8464-c6fdf105cbf1\r...
Error message
Help appreciated trying for days...
For anyone still striking this problem, please read this:
https://www.andrew-best.com/posts/please-sir-can-i-have-some-auth/
You'll feel better after this guy reflects all of your frustrations, except that he works it out...
If using adal.js, for your scope you need to use
const tokenRequest = {
scopes: ["https://management.azure.com/user_impersonation"]
};
I spent a week using
const tokenRequest = {
scopes: ["user_impersonation"]
};
.. since that is the format that the graph API scopes took
As of today, the V2 Endpoint does not support API access other than the Microsoft Graph. See the limitations of the V2 app model here.
Standalone Web APIs
You can use the v2.0 endpoint to build a Web API that is secured with
OAuth 2.0. However, that Web API can receive tokens only from an
application that has the same Application ID. You cannot access a Web
API from a client that has a different Application ID. The client
won't be able to request or obtain permissions to your Web API.
For the specific scenario that you are trying to accomplish, you need to use the V1 App Model (register apps on https://portal.azure.com).
In the very near future, V2 apps will be enabled to call other APIs other than Microsoft Graph, so your scenario will be supported, but that is just not the case today. You should keep an eye out on our documentation for this update.
In your (server) application registration in AAD, you need to specify your scopes in the oauth2Permissions element.
You may already have a user_impersonation scope set. Copy that as a baseline, give it a unique GUID and value, and then AAD will let your client request an access token with your new scope.

How to issue and consume JWT using ServiceStack's JwtAuthProvider

Looking at the JwtAuthProvider documentation for ServiceStack, it seems that a lot of JWT functionality is given out-of-the-box. However I really need to look at some working example. I could not find any in the example directory for ServiceStack.
What I'd like to see, is an example code that shows:
How to issue a token with some claims.
How to decode the token and inspect the claims.
Just using some "Hello world" service. Does anyone have some code that shows this or know where to look?
Ideally, the signing would use RSA, but right now this is not that important...
Thanks.
The JWT AuthProvider is what Issues the JWT token which it populates based on the User Session. You can add your own metadata in the tokens and inspect it with the CreatePayloadFilter and PopulateSessionFilter.
JWT is enabled in both the AngularJS http://techstacks.io Example by just making a call to /session-to-token after the user successfully authenticates with their OAuth Provider, e.g:
$http.post("/session-to-token");
This converts their currently authenticated session into a JWT Token which it uses for future subsequent requests.
Likewise JWT is also used in http://gistlyn.com which uses a Customized JwtAuthProvider to embed the Github OAuth Access Token Secret into the JWT Token then uses the PopulateSessionFilter to extract it from the JWT Token and populate it back in the Users Session:
appHost.Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
new GithubAuthProvider(appHost.AppSettings),
//Use JWT so sessions survive across AppDomain restarts, redeployments, etc
new JwtAuthProvider(appHost.AppSettings)
{
CreatePayloadFilter = (payload, session) =>
{
var githubAuth = session.ProviderOAuthAccess.Safe()
.FirstOrDefault(x => x.Provider == "github");
payload["ats"] = githubAuth != null
? githubAuth.AccessTokenSecret : null;
},
PopulateSessionFilter = (session, obj, req) =>
{
session.ProviderOAuthAccess = new List<IAuthTokens>
{
new AuthTokens { Provider = "github", AccessTokenSecret = obj["ats"] }
};
}
},
}));
Gistlyn uses a similar approach to TechStacks to using JWT Tokens by calling /session-to-token after the User has authenticated with Github OAuth using JavaScript's new fetch API
fetch("/session-to-token", { method:"POST", credentials:"include" });
JWT Stateless Auth Tests
For other examples you can look at JWT RSA Tests which uses CreateJwtPayload which shows examples of manually creating JWT Tokens in code.

OneDrive API with C#, get authentication code programmatic

I have to write an application, no matter what language (c#, Java, shell, python ...) that can connect to OneDrive and then uploads file.
Following the OneDrive API I found that i need in one step to go to the browser (manually and to post a url that combines client_id and client_security to get an authentication code so i can connect my client with it to get the access token. (oAuth2 protocol)
I need to get the access_token pragmatically, i don't need any manual step to be involved.
I tried in c# to use the WebBrowser component to navigate to the url and to get the access token, I found that the browser stays in the same url and not getting the final url that includes the auth_code!
My code looks like:
// Initialize a new Client (without an Access/Refresh tokens
var client = new Client(options);
// Get the OAuth Request Url
var authRequestUrl = client.GetAuthorizationRequestUrl(new[] { Scope.Basic, Scope.Signin, Scope.SkyDrive, Scope.SkyDriveUpdate });
// TODO: Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
WebBrowser wb = new WebBrowser();
wb.AllowNavigation = true;
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(authRequestUrl);
Console.WriteLine(wb.Version);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
wb.Document.InvokeScript("evt_Login_onload(event)");
Uri myUrl = wb.Url;
Anyone can help with fixing this, or maybe suggest other ideas please?
Thanks in Advance!
It looks like you're creating a Windows desktop app using C#. There's actually an example at https://msdn.microsoft.com/en-us/library/hh826529.aspx for using the WebBrowser class to get the authorization code, then the token, then make an API. In short, you'll first need to send a request to the following URL with your client_id and scopes.
https://login.live.com/oauth20_authorize.srf?client_id=YOUR_CLIENT_ID&scope=YOUR_SCOPE_STRING&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf
In the response, you'll get the authorization code which you'll need to use to send another request to with your client_id, client_secret, authorization code like the following.
https://login.live.com/oauth20_token.srf?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=https://login.live.com/oauth20_desktop.srf&code=AUTHORIZATION_CODE&grant_type=authorization_code
When you finally receive the access token, you can make requests to the API using your access token similar to the following.
"https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN". The "me" can be changed to any other folder or directory.
I hope that helps.
dont u think the scope u provided are wrong, they should be wl.basic, wl.signin, and if ur using new onedrive api then it should be onedrive.readonly or onedrive.readwrite
if ur using liveconnect api for the purpose of using onedrive then scope should be wl.skydrive or wl.contacts_skydrive or wl.skydrive_update
depending upon ur uses (refer https://msdn.microsoft.com/en-us/library/hh243646.aspx)
and can u more elaborate how ur trying to get the access_token, from above it is quite confusing to me
Have you solved you issue?
Have you tried to use the LiveSDK to authenticate?
Have a look at my question there, it might help you :
Onedrive API vs LiveSDK
I have used the following code, after installing both the LiveSDK and the OneDrive SDK, and this does not require any login after the first authorization. However it "may" have to be a RT app (windows store or windows phone store)
var authClient = new LiveAuthClient();
var authResult = await authClient.LoginAsync(new string[] {
"wl.signin", "onedrive.readwrite", "onedrive.appfolder"});
if (authResult.Session == null)
throw new InvalidOperationException("You need to sign in and give consent to the app.");
var Connection = new ODConnection("https://api.onedrive.com/v1.0",
new MicrosoftAccountAuthenticationInfo() { TokenType = "Bearer",
AccessToken = odArgs.Session.AccessToken });
Toan-Nguyen's answer almost helps me. On the step 2 (when I should send a request with authorization code) I get the response with error "Public clients can't send client secret". This answer said it's neccessary to remove the attribute client_secret from url.

Yahoo is unable to process your request 95022, OAuth2 authentication error

I'm trying to use Yahoo's developer APIs in Xamarin Studio's Xamarin Auth component. I created my app in with Yahoo's Developer tools, set my permissions to read everything, but can't get authorization. I get the following error.
Oops. Yahoo is unable to process your request. We recommend that you contact the owner of the application or web site to resolve this issue. [95022]
Below is my code
string clientId = "<application id from developer.apps.yahoo.com>";
string scope = "";
Uri authorizeUrl = new Uri("https://api.login.yahoo.com/oauth2/request_auth");
Uri redirectUrl = new Uri("http://www.website.com");
var auth = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl);
auth.Completed += (sender, eventArgs) => {
Console.WriteLine("Completed!");
Console.WriteLine("eventArgs.IsAuthenticated = " + eventArgs.IsAuthenticated);
DismissViewController (true, null);
if (eventArgs.IsAuthenticated) {
// Use eventArgs.Account to do wonderful things
}
};
PresentViewController(auth.GetUI(), true, null);
Any ideas as to what I'm doing wrong here?
-------------- Update --------------
I wasn't able to get OAuth2 in Xamarin.Auth working with Yahoo, but I did get OAuth1 functional. I ended up not even using that component and instead using another implementation of OAuth that was documented in the Yahoo Developer Documentation with OAuth and BOSS found here
Using OAuth with BOSS API

Get Facebook's Application Access Token

I have to use Facebook's notification for my web app.
Facebook Graph API requires the Application Access Token for this action.
Is there a way to get this token by code (C# SDK) or is this generated by Facebook a single time?
Is this token static (and secret) or with expire datetime?
For info: https://developers.facebook.com/tools/access_token/ - App Token, not User Token!
Thanks
The answer is the dynamic way by code:
var fb = new FacebookClient();
dynamic result = fb.Get( "oauth/access_token", new
{
client_id = <myAppID>,
client_secret = <mySecretID>,
grant_type = "client_credentials"
} );
var apptoken = result.access_token;
Or by the combination or appid|secretid
You can just use the concatenation of id and secret with a pipe symbol in the middle:
app_id|app_secret
This is actually how the PHP SDK creates the app access token internally, so there should be no question about the reliability of this method. (From other endpoints where you actively query for an app access token you might get another token that does not match this scheme though.)
you can investigate the getApplicationAccessToken method as in another c# sdk project from github
https://github.com/barans/FacebookCsharpSdk/blob/master/FacebookCSharpSDK/FacebookClient/FacebookClient.cs

Categories