how to get userId followers and following list with instaSharp? - c#

i use instaSharp api to create an instagram web app
after i get token access i want to see followers and following list of my profile and another people profile
i need some method to Get another user followers and following !
in the official instagram web app you cant see followers and following list (just see amount) , So does this api support it ? How i Can do it ?
this api has a poor document and samples ,
How i can use this method ? instaSharpDoc
thanks

You can see user's followers and followings list with the official Instagram API.
https://instagram.com/developer/endpoints/relationships/ - documentation
https://api.instagram.com/v1/users/{user-id}/follows?access_token=ACCESS-TOKEN - Get the list of users this user follows.
https://api.instagram.com/v1/users/{user-id}/followed-by?access_token=ACCESS-TOKEN - Get the list of users this user is followed by.

You cannot request data from another user, e.g. followers and following, without the user authorization step.
Firstly, you need to redirect the user to an authorization page. After the user inputs his credentials, he will be redirected to a page(redirect_uri value) you have sent in the authorization request, where you will request the access_token to make requests on his account.
There is another option: you can add the username you want to make requests onto your app's Sandbox (require user verification). The username will receive a notification to authorize or revoke the access to your account. After authorizing it, you will be able to make requests on his account.
If you would like to understand more detailed information, please, have a quick look at the documentation about Sandbox at https://www.instagram.com/developer/sandbox/. It will help you clarify your mind and your implementation code.
I hope it helps you.

This solved for me using InstaSharper (without accessToken but using username and password for loggin in):
var following = await api.GetUserFollowingAsync("yourUserName",PaginationParameters.Empty);
var followers = await api.GetUserFollowersAsync("yourUserName", PaginationParameters.Empty);
This is the repository: https://github.com/a-legotin/InstaSharper
Tutorial to get starting: https://www.youtube.com/watch?v=f9leg398KAw

I don't know if this is useful but for me it works:
IResult<InstaUserShortList> followers = await api.GetUserFollowersAsync(userToScrape,
PaginationParameters.MaxPagesToLoad(5));
for (int i = 0; i < followers.Value.Count; i++)
{
Console.WriteLine($"\n\t{followers.Value[i].UserName}\n\t");
}
It gives you back the username of all of the followers of a user (change UserToScrape with the one that you prefer).

Related

How do I generate an assertion token for Sharepoint Access on behalf of another user in C#

I have a web application with a number of modules. One of the modules grabs a number of excel files from SharePoint directories, and then combines the data in them. So far, I have been just mapping the folders to OneDrive and accessing them that way. But this always uses my OneDrive credentials, which need to be refreshed from time to time. The right way to do this is to access them directly from Sharepoint on behalf of the user logged into my web application. I have the delegated API permission things set up in Azure, and I have the client ID and secret, etc.. I've been reading a number of articles on how to do this. All of them talk about how to get the token on behalf of someone else. These articles also talk about the assertion token needing to be passed in order to get the on behalf of token. However, they don't tell you how to get the assertion token in the first place. Here is the code I currently have:
'''var client = new RestClient("https://login.microsoftonline.com/XXXX/oauth2/v2.0/token");
var request = new RestRequest();
request.Method = Method.Post;
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("client_id", "MYCLIENTID", ParameterType.GetOrPost);
request.AddParameter("client_secret", "MYSECRET", ParameterType.GetOrPost);
request.AddParameter("scope", "https://MYTenent.sharepoint.com/.default", ParameterType.GetOrPost);
request.AddParameter("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer", ParameterType.GetOrPost);
request.AddParameter("requested_token_use", "on_behalf_of", ParameterType.GetOrPost);
RestResponse response = client.Execute(request);'''
The result of this is of course an error that the assertion was not supplied. I didn't supply any more code, because I can't even get passed this. The rest of my code takes the token and passes it to an auth provider, which is then used to instantiate the GraphServiceClient. Based on what I've read, that client is then used to get the lists, files, etc...
So, my question is, how do I get the assertion token in the first place? I'm hoping the code I have written so far is in the correct direction and all I'm missing is the assertion token.
UPDATE:
I've gotten one answer that really didn't help. I pretty much copied and pasted the code (replacing the clientID, etc..) and I received an error> I was going to copy and paste it from the solution comments provided in the answer, but I guess you can't do that while editing.
Someone also asked if I was able to get the auth code from the URL. The answer to that is no. We use 2 factor authentication, and I tried to manually look at the URLS as I was logging in, while using break points to slow things down a bit. And I did not see an auth code. I did put a break point directly after the line of code:
var info = await _signInManager.GetExternalLoginInfoAsync();
And when I look at the info variable, I can see 4 tokens. One of them is an access token and another is an ID token. The last one is an expiration date. I don't see an auth code, and from what I understand, by the time I see the access code, it's too late. The auth code was already used to get the access code.
UPDATE 2:
I know that OBO is not what I want. I also know that in order to use delegated permissions, I need to use the Auth Code flow and not client credentials. I can't seem to get the auth code from the users initial log in. And I don't know how to get it otherwise.
For those of you that might be thinking "Does he need to be spoon fed?", the answer is yes, I do. I need a simple code example that will get me the auth code, so I can use it in the rest of the code I already have. If anyone can paste that code into an answer and not provide a link, that would be great. I'm sorry, but the links I have been given, just go to microsoft learn sites that go through the explaination, but don't give any code samples.
The OBO flow is obviously not applicable in your context, and if you're going to get an access token on behalf of a logged in user, then you should focus on auth code flow or ROPC flow.
The corresponding C# code segment is:
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://{tenant-name}.sharepoint.com/.default" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "tenant id";
// Values from app registration
var clientId = "client id";
var clientSecret = "client secret";
// For authorization code flow, the user signs into the Microsoft
// identity platform, and the browser is redirected back to your app
// with an authorization code in the query parameters
var authorizationCode = "authorization code ";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// https://learn.microsoft.com/dotnet/api/azure.identity.authorizationcodecredential
var authCodeCredential = new AuthorizationCodeCredential(
tenantId, clientId, clientSecret, authorizationCode, options);
var accessToken = await authCodeCredential.GetTokenAsync(new Azure.Core.TokenRequestContext(scopes) { });
Console.WriteLine(accessToken.Token);
//var graphClient = new GraphServiceClient(authCodeCredential, scopes);

Azure AD JWT authentication - Claims are missing

I'm trying to get a user groups from the Azure AD.
I'm getting a token with these simple lines of code :
if (this.user == null)
user = await AuthenticationManager.DefaultManager.CurrentClient.LoginAsync(this, MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory);
if (user != null)
{
System.Diagnostics.Debug.WriteLine("Token = " + user.MobileServiceAuthenticationToken);
}
When I paste the token in the JWT debugger present on this website :
https://jwt.io/ I get some informations (stable_sid, sid, sub, idp,
ver, iss, aud, exp, nbf) but I can't seem to get the groups claim in them.
I added in Azured AD the required permissions to read groups for Microsoft graph and Azure active directory but it did not change anything in the tokens.
What am I missing to get the users groups ?
Thank you in advance.
EDIT : Commenter pointed that I forgot to mention that I modified the manifest to "groupMembershipClaims": "SecurityGroup", I also tried "All" but still no claims.
Okay, so there is actually no issue here.
What we are supposed to do to acces the user groups is use the authentication token in order to make calls to the Microsoft Graph API, which will then give us access to the groups and users in the tenant.
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api-quickstart

How to get user name, email, etc. from MobileServiceUser?

After a lot of digging around I've got my WPF application signing users in via Azure Mobile Service. My Mobile Service is connected to an Azure Active Directory that I have set up. However, when I log the user in with MobileServiceClient.LoginAsync(...) the MobileServiceUser UserId is in an unreadable hash it seems. For example it looks like: "Aad:X3pvh6mmo2AgTyHdCA3Hwn6uBy91rXXXXXXXXXX". What exactly is this?
I'd like to grab the user's display name to use but I can't figure out how.
That is the userID of Azure Active Directory. You need to create a service to expose your AAD info through a service and retrieve the additional information using the access token you get from your user.
First:
ServiceUser user = this.User as ServiceUser;
var identities = await user.GetIdentitiesAsync();
var aad = identities.OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
var aadAccessToken = aad.AccessToken;
var aadObjectId = aad.ObjectId;
This will give you the access token and objectID , then you need to query the information through AAD graphy API.
https://msdn.microsoft.com/library/azure/dn151678.aspx
Look at the sample request part. You should provide the query with the access token you got and objectId.
Here is an alternative approach, after reading http://justazure.com/azure-active-directory-part-2-building-web-applications-azure-ad/ scroll to the section on Identity in .Net it talks how claims are a standard part of the framework. So once you get the credentials object like provided by #beast
var aad = identities.OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
You can actually grab a dictionary with the various properties. Examples of some the properties can be found at https://msdn.microsoft.com/en-us/library/system.identitymodel.claims.claimtypes(v=vs.110).aspx
So from there you can do the following:
if (aad != null)
{
var d = aad.Claims;
var email = d[ClaimTypes.Email];
}
I did this to pull the user id which was cross referenced in a table. FYI I am using App Service, but I believe the credentials object is the same in Mobile Service

twitter api in c# without pop authorize dialog

I want to write a console app that runs as a background task that searches twitter.
I want the job to kick off without popping up an authorize dialog. Is there a way I can call the twitter api without any dialog popping up?
I just found out that I need to use Application Only authentication. Where can I find a good example of application only authentication
You can use Single User Authorization or a newer featured called Application-Only authorization. Here's an example of how to do Application Only with LINQ to Twitter:
private static void HandleApplicationOnlyAuthentication()
{
var auth = new ApplicationOnlyAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]
}
};
auth.Authorize();
//auth.Invalidate();
var twitterCtx = new TwitterContext(auth);
var srch =
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == "LINQ to Twitter"
select search)
.SingleOrDefault();
Console.WriteLine("\nQuery: {0}\n", srch.SearchMetaData.Query);
srch.Statuses.ForEach(entry =>
Console.WriteLine(
"ID: {0, -15}, Source: {1}\nContent: {2}\n",
entry.StatusID, entry.Source, entry.Text));
}
The call to Invalidate is commented out, but you'll want to put a timer on that and Twitter's rule of thumb is to invalidate the bearer token every 15 minutes or so.
The LINQ to Twitter site has documentation on Single User Authorization too. There's a Samples page on the site and the downloadable source code has working demos. BTW, Twitter user tokens generally don't ever expire, so you can store and continue to use the same tokens.
Joe, works like a CHARM! Thanks a lot for you efforts to build such elegant solution on top of not so friendly REST interface. Still looking for different search criteria :)
No, your console app cannot authorize without user interaction. The whole point of authorization is that users have to take action to allow applications to use their accounts.
Trust me, you really wouldn't want any application to be able to take control of your Twitter account without your explicit permission. :)

Facebook C# SDK and Access Token

I'd like to be able to authenticate myself (my profile, not just my app) on my own web application using the Facebook C# SDK. Using the Graph API, I can get an access token, but that token does not seem to work properly with the Facebook C# as it seems to be stateless.
The error that is thrown is:
(OAuthException) An active access token must be used to query information about the current user.
I've poked around the Facebook C# SDK and documentation and most of the info I'm seeing is to redirect users to a login page which is not what I'm looking for.
Does anyone have a good sample of auto-logging in myself so I can pull up my own information?
TIA
When you say "yourself" do you mean the app or your actual facebook user?
If it's just your app, you can get an access token by POSTing to this URL:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APP_ID_HERE&client_secret=APP_SECRET_HERE
You can use this access token to perform actions on behalf of your users if they have authorized your app to do so.
I had the same problem where the access token didn't include the session part. Please check out my answer to this similar question - exchange code for token facebook-c#-sdk.
Here's a sample from my Home controller
[CanvasAuthorize]
public ActionResult Index()
{
var app = new FacebookClient(new Authorizer().Session.AccessToken);
dynamic me = app.Get("me");
ViewBag.Firstname = me.first_name;
ViewBag.Lastname = me.last_name;
return View();
}
Edit
Now I understand the question better. What about this?
var auth = new Authorizer(FacebookContext.Current.AppId, FacebookContext.Current.AppSecret, HttpContext);
auth.Authorize();
From the documentation:
public bool Authorize()
Member of Facebook.Web.Authorizer
Summary:
Authorizes the user if the user is not logged in or the application does not have all the sepcified permissions.
Returns:
Return true if the user is authenticated and the application has all the specified permissions.
I dont know if this will work for you:
using Facebook.Web;
using Facebook;
using System.Dynamic;
var auth = new CanvasAuthorizer { Permissions = new[] { "user_about_me"} };
if (auth.Authorize())
{
}
and include this in the aspx:
<input type="hidden" name="signed_request" value="<%: Request.Params["signed_request"]%>"/>
good luck !!

Categories