Get current exchange token - c#

I am having difficulty acquiring my current FaceBook exchange token.
Currently I can get a short term access token by using -
String OAuthURl = "https://graph.facebook.com/oauth/access_token?client_id={MY-CLIENT-ID}&client_secret={MY-CLIENT-SECRET}&grant_type=client_credentials";
Which brings back a response like -
123456789|ABCDEFGH
I am trying to generate a new long term access token by building the following URL-
String OAuthURl = "https://graph.facebook.com/oauth/access_token?client_id={MY-CLIENT-ID}&client_secret={MY-CLIENT-SECRET}&grant_type=fb_exchange_token";
This brings back the response-
fb_exchange_token parameter not specified
So I tried -
String OAuthURl = "https://graph.facebook.com/oauth/access_token?client_id={MY-CLIENT-ID}&client_secret={MY-CLIENT-SECRET}&grant_type=fb_exchange_token&fb_exchange_token=123456789|ABCDEFGH
However this is an invalid exchange token.
I believe the first URL I am trying is bringing back a client_credentials however how can I request my fb_exchange_token from a URL without having to manually go into my APP console?

The first URL is requesting an application access token. Application access tokens can be used to modify application settings and perform some operations with users who have authorized your app. Application access tokens do not expire (unless you reset your app secret), and you do not need to exchange them for longer term tokens.

Related

Can you use refresh tokens in Blazor Server app with cookie authentication and no Api's and no local storage?

Just looking into Blazor and my company decided to explore Server Side App (no WASM).
I got the basic project setup and because we want the app to work with out current user db, I modified our User Server (Microservice) to authenticate a user and return a JWT token. In the Login page once we have the token, we authenticate and the cookie is stored.
var auth = await HttpContext.AuthenticateAsync();
auth.Properties.RedirectUri = "/";
var accessToken = new AuthenticationToken()
{
Name = OpenIdConnectParameterNames.AccessToken,
Value = Token
};
AuthenticationToken[] tokens = { accessToken };
auth.Properties.StoreTokens(tokens);
auth.Properties.IsPersistent = true;
await HttpContext.SignInAsync("Cookies", auth.Principal, auth.Properties);
So I want to say at this point everything is working fine.
Now back to the question. I wish to increase security by using Refresh Tokens, and this is where I hit the problem. Every tutorial or guide I google/bing that talks about Refresh tokens goes by the basses that I am using WASM or an API that I call. There are a few articles that say to use Local Storage but then that can bring up a whole new conversation of Local Storage vs Cookies vs Session, and I was hoping to stick with most of the built in stuff.
I understand that Server-Side issues with the HTTP context, hence why the login page is done on a .cshtml page and the fact that the cookies are set as HTTPOnly so JavaScript cannot access them.
So, is there away to do it?
Just to clarify, this is a Server-Side app only, no client apps or API's or anything else and I wish to stick with most of the built in stuff using cookies.

apis.live.net/v5.0 - How to validate token on server

I have a resource (REST) server (written in Java/Spring) that I need to validate a Microsoft token from a client. I need to:
Check that the token is valid for my app
Get the token's email address and lookup that user in my app (I can do this)
I currently use Google, Facebook and am adding Windows auth.
For Google, I check my token at:
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token={accessToken}
For Facebook, I use:
https://graph.facebook.com/debug_token?input_token={accessToken}&access_token={appId}|{appSecret}
What do I use for live?
https://apis.live.net/v5.0/????
I need something that returns my app id so I can make sure the token was created by my app.
I can get the user info from the token just fine (the URL is https://apis.live.net/v5.0/me?access_token={accessToken}) but it does not allow me to verify that the user is for my app that is registered.
What is the token validation scheme here? It's not a JWT token, because it does not have any '.' characters in it...
According to this https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview:
Access tokens issued by Azure AD are base 64 encoded JSON Web Tokens (JWT).
However, when I try to base64 decode my token, it is binary. https://apis.live.net/v5.0/me shows that it's a valid token, though.
Here is an expired token:
EwAwA61DBAAUcSSzoTJJsy+XrnQXgAKO5cj4yc8AAfD7xbB6agxt1xZJhCeONQNzKUS97NgwifhSev98+2Boa/kdgnR/hk6KzNBiFz0mNsPWQrEhTsQRbta9QyGGezyVhpYLtMbWbWHUhNh/lY3w31x/5yeuUmw/ITXwu7Qk3L8t3ESzYoy9NCJT7AzkFHf6hUgDg5lNeFbwZD5mFe3Y6NH3p3kYHDBJwDHO7VN+AlTCWc3z1n06NSxQOisOjZYZ3YrWhdaffMZ9yaBfRYcSLvBLeA8u//jfhIdunfPXQyaXnNEHp3GAlVASPcskQnRmZHIz9IcqE9ZZPpXNHcgz36UIKV1aqkDGnYIqzDsAqvmICN3tWJhrabFfPC00yUIDZgAACM68oajVfXdPAAKTFEdhizTgVDOWT7yytFJCHesQFy3yfKiJ+/lANntrgT0peCZt6cHsS1iqdF7A3WMhFc4hQP7kV29PCPTouLyNj8Ygcnl024H3usPbBqCqDrRsNNjJAdKkR2Cni9Kchw/i02NfC+DUy2LmUBTb5oHZXG7zx21K+l/HBbOUn0VRb4l+rsx7CTiabu1s3cdCrmhDDuIwWv2W8Id6Y6VBYs6zddHRY58B1YRZSQevcsT05xehrebS40E+Pyy/Z9vJXb2FTM+pY1+HvtPpxqxqn73Bp3wX1A8YH8Lbe4J/J+aHbE6mEnEvQMiavB0nrh0gTAydrBkkWuY3zbuQaQFE96/i3yWad8j0A0cU8/YquXFBo6k1oD0dWOKNOQ9x+Dad7W3yFEB2gF9jZtxU5OdV4S3uRmdqyaj2kGVI2eVrX4/13f97tKA3a2ZIF7ZUZKgpwNybOrz9COAilxZvr3Z+X1jTdTYOXWMs8tuOOpru2g64sZUzgtj0JETWJcHfg9yLC72DSaAFzDR/KRa2u+C7XGaywIPEqoUs/4iRaLc5RPtdRlLHCp0rgmIlMc0/iwR7K6N2Q5odVP7QzxlBNtGW51iHNCFgRDrQ8zNkv2hdexxt7Of2i+lqe2N3Z3ENUoQa6SRBYzFDPOka+Mr5qWVxeMeulYmXFkBh0NyKaLJIqrkSMy0C

On-Behalf-Of Azure Mobile backend - MS Graph

Another attempt to ask a different question surrounding my month long problem:
I'm now trying to initiate the "On-Behalf-Of" flow to get a MS Graph token when users login with a Microsoft Account. As documented here:
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-on-behalf-of
On the client, users log in with a server-flow:
var user = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
On the .NET backend, I am trying to retrieve the MS Graph token:
string clientId = "id-shown-in-app-registration-portal";
string clientSecret = "secret-shown-in-app-registration-portal";
IEnumerable<string> msIdTokenOut = null;
Request.Headers.TryGetValues("x-ms-token-microsoftaccount-access-token", out msIdTokenOut);
string msIdToken = msIdTokenOut.FirstOrDefault();
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common/oauth2/v2.0");
UserAssertion assertion = new UserAssertion(msIdToken);
ClientCredential cred = new ClientCredential(clientId, clientSecret);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", cred, assertion);
I get the following error:
aadsts50027: invalid jwt token. token format not valid.
I've tried every possible combination, from using server-flow to login, using MSAL for client-flow (which doesn't authenticate against App Services with the retrieved token). This has been driving me crazy for over a month. I can't believe how many hoops I have jumped through to get 2 Microsoft products working together. If anyone can steer me towards a solution I would be beyond grateful.
Here is a workaround, I suggest you could enable the mobile server custom authentication by using MSAL returned access token.
More details, you could refer to below steps:
Firstly, you could create a login page which will use MSAL login with the microsoft account. It will return the access token.
Then you could send the request with the access token to the mobile service backend to ask for authentication.
Notice: The logic in the backend which used to check the access token is right, you need achieve by yourself. You could decode the access jwt token to get the aud value. If this value is as same as the client id that means the user have the permission to access mobile backend data.
Then you could use jwt token to get the user information from graph api. After get the user information, you could set the user information value to claims to generate the auth token(using this method AppServiceLoginHandler.CreateToken[Add Microsoft.Azure.Mobile.Server.Login NuGet package]). By using this token the mobile client user could access the mobile backend.
The access token like this:
More details, you could refer to this article to know how to enable custom auth in mobile backend.

How to validate Facebook user token server side

I am having problem understanding how to implement a Facebook login workflow for my web app. I am stuck in the validation of the user token server side.
I am using C# SDK library. I am trying to validate the user token using the following code:
var fb = new FacebookClient();
fb.AppId = "0000000000000";
fb.AppSecret = "000000000000000000000";
dynamic result = fb.Get("debug_token", new { input_token = c_accessToken });
I get the following error when running the Get command.
OAuthException - #100) (#100) You must provide an app access token
or a user access token that is an owner or developer of the app
I changed the appId and appSecret for privacy reasons, but I double checked them and they are valid.
You need to send App Access Token That is the error you are getting. To get an App access token follow this documentation from facebook
https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens
To generate App Access Token you need to make a GET request from your FacebookClient() or using HttpClient()to this API endpoint.
GET /oauth/access_token
?client_id={app-id}
&client_secret={app-secret}
&grant_type=client_credentials
this the documentation link for 'debug_token' endpoint
https://developers.facebook.com/docs/facebook-login/access-tokens/debugging-and-error-handling

Service Account Google Analytics OAuth AccessType = Offline C#

I've got credentials of an account with access to Google Analytics,
I'm looking to utilise the Analytics Core Reporting API http://code.google.com/apis/analytics/docs/gdata/home.html
I've found examples which use username/password calling setUserCredentials, but have seen comments this is less secure/has a low request limit (And doesn't exist in the lastest client).
Plus I've seem examples which use oauth, but require user interaction and grant access to the users google account.
However I'm looking to run a service which doesn't require any user interaction, and connects to a predefined google account (un-related to the user viewing it).
I can then store the results in a database, and end users can query the results from the database.
I've seen information about using AccessType = Offline when you first login, which then returns an access token and a refreshtoken.
http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#offline
In my example though, the end user will never login to the application.
Could I have a seperate admin application which gets a refresh token, and stores the refresh token in the config/lookup table?
Then the main application can use the refresh token pulling from the config/lookup table, and get an access token to be able to query the Google Analytics account.
I'm looking for a C# example which uses AccessType = Offline, and seperates out the fetching of the refresh token and using the refresh token to get an access token to query the google analytics account.
Create your app https://code.google.com/apis/console/
For you App, turn on access to Google Analytics, and create an OAuth 2.0 client ID for your website.
Browse to:
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=YOUR_APP_ID.apps.googleusercontent.com&access_type=offline&scope=https://www.googleapis.com/auth/analytics.readonly&redirect_uri=HTTP://YOUR_CALL_BACK_URL
Having changed YOUR_APP_ID, YOUR_CALL_BACK_URL to the relevant values.
Important to include access_type=offline.
Press Grant Access, this will redirect to HTTP://YOUR_CALL_BACK_URL?code=THIS_IS_YOUR_CODE. Copy the code in the URL.
With the code, request the Refresh Token using CMD prompt.
curl -d "code=THIS_IS_YOUR_CODE&client_id=YOUR_APP_ID.apps.googleusercontent.com&client_secret=YOUR_APPS_SECRET_CODE&redirect_uri=HTTP://YOUR_CALL_BACK_URL&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
Having changed THIS_IS_YOUR_CODE, YOUR_APP_ID, YOUR_APPS_SECRET_CODE, YOUR_CALL_BACK_URL to the relevant values.
Record the refresh_token returned.
Download the latest version of the Core Reporting V3.0 .net libraries
http://code.google.com/p/google-api-dotnet-client/wiki/Downloads
There is a bug in the current version of Google.Apis.Analytics.v3.cs, to fix this copy the code in this file to your local solution (And don’t reference Google.Apis.Analytics.v3.bin)
http://code.google.com/p/google-api-dotnet-client/source/browse/Services/Google.Apis.Analytics.v3.cs?repo=samples&name=20111123-1.1.4344-beta
And change the property Dimensions from a List<system.string> to a string.
Or you'll get an error like me and this guy did http://www.evolutiadesign.co.uk/blog/using-the-google-analytics-api-with-c-shar/
You can then use your Refresh Token, to generate you an Access Token without user interaction, and use the Access Token to run a report against Google Analytics.
using System;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using AnalyticsService = Google.Apis.Analytics.v3.AnalyticsService;
class Program
{
public static void Main()
{
var client = new WebServerClient(GoogleAuthenticationServer.Description, "YOUR_APP_ID.apps.googleusercontent.com", "YOUR_APPS_SECRET_CODE");
var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);
var asv = new AnalyticsService(auth);
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
request.Dimensions = "ga:pagePath";
request.Sort = "-ga:visitors";
request.MaxResults = 5;
var report = request.Fetch();
Console.ReadLine();
}
private static IAuthorizationState Authenticate(WebServerClient client)
{
IAuthorizationState state = new AuthorizationState(new string[]{}) { RefreshToken = "REFRESH_TOKEN" };
client.RefreshToken(state);
return state;
}
}
Great Answer Ian and it helped me to get going in the correct Direction more than any other answer I could find online. Something must have changed in the AnalyticsService object because the line:
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
did not work for me and I had to use the following:
var request = asv.Data.Ga.Get("ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID", "2012-01-01", "2012-02-20", "ga:visitors");
Hopefully this will help others like your answer helped me. Thanks!
Ian's answer helped me a lot but I kept getting an error running the curl command. Did some research and found that the steps to get the access code and refresh token can be made easier by going to https://code.google.com/oauthplayground/ and checking your oAuth configuration settings. Top right of the page there is a settings button. selected "Use your own OAuth credentials". You can get your access code and request a refresh token all from here.
Hope this helps.
You can manually get a refresh token from the OAuth Playground.
If you are needing a refresh token for a Service Account as I was, make sure you
Click on the settings on the right.
Check Use your own OAuth credentials
Fill in your Client ID and Secret
Close the settings
Click the Refresh button on step 2
Then save the refresh token for use in your app

Categories