How to get access token? (Reddit API) - c#

I wonder if it is possible to get a permanent access token for personal use on Reddit?
It will only be me using the App.
For users, the access token expires after 1 hour.
My using the below information that I have about my client-id and secret, I put up a start attempt of trying to get an access token. (MessageBox show "Error 401")
If a user will get a token, one have to click "Allow" in the browser. Very well described here. https://github.com/reddit/reddit/wiki/OAuth2
This it NOT what I am after. I am after for, personal use, an access token only through code. Is this possible?
String requestUrl = "https://ssl.reddit.com/api/v1/access_token";
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
request.AddHeader("Content-Type", "application/json");
//request.AddHeader("Authorization", ""); //???
request.AddHeader("x-li-format", "json");
request.AddParameter("client_id", "abcdefg");
request.AddParameter("client_secret", "abc123-456");
request.AddParameter("grant_type", "abc123-456");
request.AddParameter("scope", "identity");
request.AddParameter("state", "adhasegw"); //whatever value
request.AddParameter("duration", "permanent");
request.AddParameter("redirect_uri", "http://mywebsite.co");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.Content.ToString() + "," + responseStatus.ToString());

As of right now, you cannot retrieve a permanent access token. You have 2 options that come close.
The first is to request a "refresh" token when using the standard OAuth flow. That's what you're doing by sending "duration" as "permanent" in your code. The refresh token can be used to automatically retrieve new 1 hour access tokens without user intervention; the only manual steps are on the initial retrieval of the refresh token.
The second alternative, which applies only when writing a script for personal use, is to use the password grant type. The steps are described in more detail on reddit's "OAuth Quick Start" wiki page, but I'll summarize here:
Create an OAuth client (under https://www.reddit.com/prefs/apps) with type = "script"
Make a request to https://www.reddit.com/api/v1/access_token with POST parameters grant_type=password&username=<USERNAME>&password=<PASSWORD>. Send your client ID and secret as HTTP basic authentication. <USERNAME> must be registered as a developer of the OAuth 2 client ID you send.

A client_id and client_secret can be generated for a reddit account by going to https://www.reddit.com/prefs/apps and creating an app:
The part I have hidden is my client_id.
Then you can use a client like praw to access reddit e.g. with Python:
import praw
r = praw.Reddit(client_id='insert id here',
client_secret='insert secret here',
user_agent='insert user agent')
page = r.subreddit('aww')
top_posts = page.hot(limit=None)
for post in top_posts:
print(post.title, post.ups)
You could use your current browser's user agent, which can be easily found by google searching "what is my user agent" (among other ways).

Related

What goes into a JWT refresh_token?

I built some JWT middleware for my Asp.net Core REST service based on some examples I found online. I get that the response looks like:
{
"access_token":"...",
"expires_in":3600,
"refresh_token":"???",
"token_type": "Bearer",
}
I understand how to create access_token:
Claim[] claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, strUsername),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, dtNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
};
JwtSecurityToken jwtAccess = new JwtSecurityToken(_options.Issuer, _options.Audience, claims, dtNow.DateTime,
dtNow.DateTime.Add(_options.AccessTokenExpiration), _options.SigningCredentials);
The question is how do I create refresh_token? I have searched high and low and can't find much documentation on it. Basically all every reference says is "its a token stored in a database with a longer TTL that you can create a new access_token from".
So is a refresh_token the same exact thing as access_token with just the longer TTL and the additional step that its validated against the database?
Some of the example JWT responses I've seen seem like the refresh_token is much shorter. My access_token is signed with a certificate using RSA515, so the string is kinda long...
Now personally my refresh tokens are just JWTs with longer TTL and a little more information that help me verify the resource owner.
Take a look at the following article from Auth0 and it support links
https://auth0.com/docs/tokens/refresh_token
It could even be a simple GUID used to map user/client to token where the expiry time is also stored in the database along with the token.
The following example is from the link sited above where they use what looks like a Guid for the refresh token.
So, for instance, assuming there is a user 'test' with password 'test'
and a client 'testclient' with a client secret 'secret', one could
request a new access token/refresh token pair as follows:
$ curl -X POST -H 'Authorization: Basic dGVzdGNsaWVudDpzZWNyZXQ=' -d 'grant_type=password&username=test&password=test' localhost:3000/oauth/token
{
"token_type":"bearer",
"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiVlx1MDAxNcKbwoNUwoonbFPCu8KhwrYiLCJpYXQiOjE0NDQyNjI1NDMsImV4cCI6MTQ0NDI2MjU2M30.MldruS1PvZaRZIJR4legQaauQ3_DYKxxP2rFnD37Ip4",
"expires_in":20,
"refresh_token":"fdb8fdbecf1d03ce5e6125c067733c0d51de209c"
}
Once their token has expired they make a call passing the refresh token to get a new access token.
Now we can use the refresh token to get a new access token by hitting
the token endpoint like so:
curl -X POST -H 'Authorization: Basic dGVzdGNsaWVudDpzZWNyZXQ=' -d 'refresh_token=fdb8fdbecf1d03ce5e6125c067733c0d51de209c&grant_type=refresh_token' localhost:3000/oauth/token
{
"token_type":"bearer",
"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiVlx1MDAxNcKbwoNUwoonbFPCu8KhwrYiLCJpYXQiOjE0NDQyNjI4NjYsImV4cCI6MTQ0NDI2Mjg4Nn0.Dww7TC-d0teDAgsmKHw7bhF2THNichsE6rVJq9xu_2s",
"expires_in":20,
"refresh_token":"7fd15938c823cf58e78019bea2af142f9449696a"
}
Security Considerations
Refresh Tokens are long-lived. This means when a client gets one from
a server, this token must be stored securely to keep it from being
used by potential attackers, for this reason it is not safe to store
them in the browser. If a Refresh Token is leaked, it may be used to
obtain new Access Tokens (and access protected resources) until it is
either blacklisted or it expires (which may take a long time). Refresh
Tokens must be issued to a single authenticated client to prevent use
of leaked tokens by other parties. Access Tokens must also be kept
secret, but due to its shorter life, security considerations are less
critical.

Saving Tweetinvi credentials without re-authenticating every time

Basically what I'm trying to do is to get recent tweets from a user and do stuff with them. I'm using Tweetinvi with PIN-based authentication, as described on the website, like this:
// Create a new set of credentials for the application
var appCredentials = new TwitterCredentials("CONSUMER_KEY", "CONSUMER_SECRET");
// Go to the URL so that Twitter authenticates the user and gives him a PIN code
var url = CredentialsCreator.GetAuthorizationURL(appCredentials);
// This line is an example, on how to make the user go on the URL
Process.Start(url);
// Ask the user to enter the pin code given by Twitter
var pinCode = Console.ReadLine();
// With this pin code it is now possible to get the credentials back from Twitter
var userCredentials = CredentialsCreator.GetCredentialsFromVerifierCode(pinCode, appCredentials);
// Use the user credentials in your application
Auth.SetCredentials(userCredentials);
Now the problem is that I have to sign in and connect to Twitter every time I launch my application via browser, which is mildly annoying. I've tried to save my authentication details in a text file (Consumer Key, Consumer Secret, Access Token, Access Token Secret), and then just insert the info into appCredentials and userCredentials, but with no results, as I keep getting TwitterNullCredentialsException. So how do I save my credentials so that I don't have to reconnect on every launch?
I am the main developer of Tweetinvi.
If you store the 4 credentials information you can then reuse them with 2 different solutions :
Auth.SetUserCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
// OR
var creds = new TwitterCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
Auth.SetCredentials(creds);
The documentation might help you set up your application : https://github.com/linvi/tweetinvi/wiki/Introduction

AdminSettings API using service account in a C# Console application

I'm trying to use the Google Admin Settings API with a Service Account with no success from a C# Console application.
From what I've understood, I first have to get an OAuth token. I've tried 2 methods successfully for this: using Google.Apis.Auth.OAuth2.ServiceAccountCredentials or by creating manually the JWT assertion.
But when I call an Admin Settings API with the OAuth token (maximumNumberOfUsers for instance), I always get a 403 error with " You are not authorized to perform operations on the domain xxx" message.
I downloaded GAM as the author calls this API too so that I can compose the same HTTP requests. Like explained in GAM wiki, I followed all the steps to create a new Service Account and a new OAuth Client ID so that I can be sure it's not a scope issue. I also activated the debug mode like proposed by Jay Lee in this thread. Like explained in the thread comments, it still doesn't work with my OAuth token but the call to the API succeeds with GAM OAuth token.
So it seems it's related to the OAuth token itself. An issue I get while creating the OAuth token is that I can't specify the "sub" property (or User for ServiceAccountCredentials). If I add it, I get a 403 Forbidden response with "Requested client not authorized." as error_description while generating the token i.e. before calling the API. So maybe it is the issue but I don't see how to fix it as I use an Admin email.
Another possibility is that this API needs the OAuth Client credentials as GAM requires 2 different types of credentials, Service Account and OAuth Client. As I only can use Service Account credentials in my project, I'm afraid I will be stuck if it is the case...
I don't see other options and I'm stuck with both, so any help appreciated. Thanks!
My code:
public static string GetEnterpriseUsersCount()
{
string domain = MYDOMAIN;
string certPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
certPath = certPath.Substring(0, certPath.LastIndexOf("\\") + 1) + "GAMCreds.p12";
var certData = File.ReadAllBytes(certPath);
X509Certificate2 privateCertificate = new X509Certificate2(certData, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
{
Scopes = new[] { "https://apps-apis.google.com/a/feeds/domain/" },
User = ADMIN_EMAIL
}.FromCertificate(privateCertificate));
Task<bool> oAuthRequest = credential.RequestAccessTokenAsync(new CancellationToken());
oAuthRequest.Wait();
string uri = string.Format("https://apps-apis.google.com/a/feeds/domain/2.0/{0}/general/maximumNumberOfUsers", domain);
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
if (request != null)
{
request.Method = "GET";
request.Headers.Add("Authorization", string.Format("Bearer {0}", credential.Token.AccessToken));
// Return the response
using (WebResponse response = request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
return null;
}
Edit: I focused on scopes like advised by Jay Lee below and it appears that the missing scope was 'https://www.googleapis.com/auth/admin.directory.domain'. However, nowhere is this written in Admin Settings API documentation page. At least, I didn't find it. 'https://apps-apis.google.com/a/feeds/domain/' is necessary too but I already added it to the list of allowed scopes. Thanks Jay!
Edit 2: I also updated the source code so that it can help in the future.
You need to grant your service account's client ID access to the scopes for admins settings API. Follow the Drive domain wide delegation instructions except sub in the correct correct scope. Then you can set sub= without an error.

Facebook SDK for .NET: Uploading pics to a page from backend

What I am looking to achieve.
I have a WPF application where in, I will be getting access to some pics generated on run time and I wanna post these pics to an album on FB Page(Think server to server interaction ). This process is supposed to be completely self reliant without any input from users. So I did some research and figured you gotta create an app to be able to do it. On further research the process seems to be as follows:
1) Using app secret and app id , get the app access token
2) Get the user access token
3) using this user access token, call {userId}/accounts and from the resulting JSON parse the page id and get the Page Access token.
Now I have successfully retrieved the App Access token and now I am not able to figure out how to get UserAccessToken without which I cant proceed to step 3.
I am using C# SDK for facebook and here is some code
Step 1.
var fbAccess = new FacebookClient();
dynamic resultAccess = fbAccess.Get("oauth/access_token", new
{
client_id = "XXXXXXXXX",
client_secret = "XXXXXXXXXXX",
grant_type = "client_credentials",
redirect_uri = "",
perms = "manage_pages, photo_upload, publish_stream"
});
String app_access_token = resultAccess["access_token"];
Step 2:
FacebookClient fbClient = new FacebookClient(app_access_token );
dynamic resultAccess = fbClient.Get("/{UserID}/accounts", new
{
client_id = "XXXXXXX",
client_secret = "XXXXXXXXXXXXXXXXX",
perms = "manage_pages, photo_upload, publish_stream"
});
The error I am getting is "A user access token is required to request this resource." I have already given the required permission to the app using Graph API Explorer.
Thanks in Advance

C# Facebook SDK - How to use web forms to server side authorize canvas application

There are lots of sample applications in MVC but the current project I'm working on requires that I use web forms.
I can authorize the application using the javascript method but I want to use server side. Below is what I started with on the page.load
dynamic parameters = new ExpandoObject();
parameters.client_id = AppId;
parameters.client_secret = appSecret;
parameters.response_type = "code";
//parameters.state = state;
parameters.redirect_uri = "http://fb.local/page.aspx";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
//parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(ExtendedPermissions))
parameters.scope = ExtendedPermissions;
// generate the login url
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(parameters);
Response.Redirect(loginUrl.AbsoluteUri, true);
I can authorize but I'm not able to get the access token from the URL.
On the next page I can view source and see the access token in the url bar but I'm not sure how to go about getting it into the code. once I have the token, I'm all set.
page.aspx#access_token=AAACrxQhmdpY
I used to this code on my page load and works, its not a very clean code, but you may figure out how to change it for your best use. so the algorithm is that when the page loads you redirect the user to Facebook authentication page using response.redirect to a string that contains three parameters:your app ID(appid), what permissions you are asking your user(scope), where you want Facebook to redirect the user after authorization, and a parameter as state which i guess it should be a random number. so after the user authorized your application he/she will be redirected to your page, with a request URL that contains the same state you prepared Facebook with(and you can use to identify who which request was which if there are many requests i guess) and also a new "code" parameter which you pass on to Facebook to obtain access token, you can use Facebook c# sdk to obtain the access token.in my code there is a line that says "if code is not null, go to alireza" and alireza is a line tag after the response.redirect code, this is because you dont want the process to be repeated all over and over (and of course probably the browser show an error).
int intstate;
string strstate;
string redirecturltofb;
string scope;
string appid;
code = Request.QueryString["code"];
if (!String.IsNullOrWhiteSpace(code))
{
goto alireza;
}
appid = "424047057656831";
scope = "user_about_me,user_activities,user_groups,email,publish_stream,user_birthday";
intstate = 45;
strstate = Convert.ToString(intstate);
redirecturltofb = "https://www.facebook.com/dialog/oauth?client_id=" + appid + "&redirect_uri=http://test5-2.apphb.com/&scope=" + scope + "&state=" + strstate;
Response.Redirect(redirecturltofb);
You have to use Javascript SDK to get access token back to code behind.
Use FB.Init as in http://csharpsdk.org/docs/web/getting-started
and do post back on certain conditions to get the access token.
Thank you,
Dharmendra

Categories

Resources