InstaSharper Token - c#

I am trying to learn how to use InstaSharper but I've got a problem. Everytime when I run my code to see the new code working, I have to login, but if I do this too many times, I will be blocked by Instagram. I was blocked on two accounts allready. So I need a solution not to always have to login like a token or something.
My login:
public static async void Login()
{
api = InstaApiBuilder.CreateBuilder()
.SetUser(user)
.UseLogger(new DebugLogger(LogLevel.Exceptions))
.SetRequestDelay(RequestDelay.FromSeconds(5, 10))
.Build();
var loginRequest = await api.LoginAsync();
if (loginRequest.Succeeded)
{
Console.WriteLine("Login In Success!");
Follow("artofbokeh");
}
else
{
Console.WriteLine("Login Failed");
}
}

Yes you can save your state in a a file and load it again.
Please give this piece of code a try, it is taken form the official github repo which can be found under this link: Github repo
// create user session data and provide login details
var userSession = new UserSessionData
{
UserName = "username",
Password = "password"
};
// create new InstaApi instance using Builder
_instaApi = InstaApiBuilder.CreateBuilder()
.SetUser(userSession)
.UseLogger(new DebugLogger(LogLevel.Exceptions)) // use logger for requests and debug messages
.SetRequestDelay(TimeSpan.FromSeconds(2))
.Build();
const string stateFile = "state.bin";
try
{
if (File.Exists(stateFile))
{
Console.WriteLine("Loading state from file");
Stream fs = File.OpenRead(stateFile);
fs.Seek(0, SeekOrigin.Begin);
_instaApi.LoadStateDataFromStream(fs);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
if (!_instaApi.IsUserAuthenticated)
{
// login
Console.WriteLine($"Logging in as {userSession.UserName}");
var logInResult = await _instaApi.LoginAsync();
if (!logInResult.Succeeded)
{
Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
return false;
}
}
var state = _instaApi.GetStateDataAsStream();
using (var fileStream = File.Create(stateFile))
{
state.Seek(0, SeekOrigin.Begin);
state.CopyTo(fileStream);
}
Edit the function to get the state data does the following:
public Stream GetStateDataAsStream()
{
var state = new StateData
{
DeviceInfo = _deviceInfo,
IsAuthenticated = IsUserAuthenticated,
UserSession = _user,
Cookies = _httpRequestProcessor.HttpHandler.CookieContainer
};
return SerializationHelper.SerializeToStream(state);
}
So yes you save all needed information to not login everytime. If this doesnt work for you you are doing something wrong. Please post your code where you load / save the state file.

Related

Create Instagram Account Using C#

I am using InstagramApiSharp
Here is my code :
public static async void CreateAccount()
{
var _instaApi = InstaApiBuilder.CreateBuilder().Build();
var email = "ramtinaaka#live.com";
var username = "rmt40306";
var password = "rmt122345678";
var firstName = "Ramtiinnn";
var checkEmail = await _instaApi.CheckEmailAsync(email);
if(checkEmail.Succeeded && checkEmail.Value.Available)
{
var create = await _instaApi.CreateNewAccountAsync(username, password, email, firstName);
if (create.Succeeded)
{
Console.WriteLine("Success");
return;
}
Console.WriteLine("Error");
}
return;
}
I get Error printed on console when I call CreateAccount method as well as no account created.
Create Account Wiki
I believe I gave all needed info, I don't think there is anything else to add.

Accessing file on network with user outside of the domain

I need to access a file from a network drive with a user who may not be in the domain.
My current code is:
private async Task GetUxVersionsFromServer()
{
string path = #$"\\{IpAddress}\...\...\...";
if(!await GetFiles(path))
{
using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
{
bool retry = true;
do
{
(var ok, var username, var password) = _dialogService.ShowPasswordInput();
if (ok)
{
if (unc.NetUseWithCredentials(path, username, "domain", password))
{
await GetFiles(path);
retry = false;
}
}
else
{
retry = false;
}
} while (retry);
}
}
}
private async Task<bool> GetFiles(string path)
{
try
{
var zipFiles = await Task.FromResult(System.IO.Directory.GetFiles(path, "VERSION*.zip"));
Versions = new ObservableCollection<string>(zipFiles);
return true;
}
catch (IOException)
{
return false;
}
}
I use the class UNCAccessWithCredential from here
It works fine.
If the user has access to the directory, the password entry should not appear.
The only problem is that I can't test if the Windows user has access to the directory without catching an exception.
Is there a way to query if the logged in Windows user has access to a network directory or not?
Is there a way to query if the logged on Windows user is in the domain?
Plenty of ways to figure out directory permissions here: How do you check for permissions to write to a directory or file?
As for the domain membership, use this: https://learn.microsoft.com/en-us/dotnet/api/system.environment.userdomainname?view=netframework-4.8
The UserDomainName property first attempts to get the domain name component of the Windows account name for the current user. If that attempt fails, this property attempts to get the domain name associated with the user name provided by the UserName property. If that attempt fails because the host computer is not joined to a domain, then the host computer name is returned.
Finally I solved it this way:
private async Task GetUxVersionsFromServer()
{
string path = #$"\\{server}\...";
if (Environment.UserDomainName.ToLower() != "myDomain")
{
bool success = false;
bool ok;
do
{
(bool result, var username, var password) = _dialogService.ShowPasswordInput();
ok = result;
if (ok)
{
try
{
using (new NetworkConnection(path, new NetworkCredential($#"myDomain\{username}", password)))
{
success = await GetFiles(path);
}
}
catch (System.ComponentModel.Win32Exception ex)
{
success = false;
}
}
} while (!success && ok);
if(!ok)
{
int test = 0;
}
}
else
{
await GetFiles(path);
}
}
I took the class NetworkConnection from here

Authenticate with OneDrive SDK in a c# console project

I'm trying to create a program that will download all my OneNote files from OneDrive. But when I try to authenticate using msaAuthenticationProvider a white window appears and then nothing happens. I think the window is supposed to be the Microsoft login, but nothing appears in it.
Here's my code:
string[] scopes = new string[] {
"onedrive.readonly",
"wl.signin"
};
var msaAuthenticationProvider = new MsaAuthenticationProvider(
clientId,
returnURL,
scopes);
await msaAuthenticationProvider.AuthenticateUserAsync();
var client = new OneDriveClient(URL, msaAuthenticationProvider);
It gets to the AuthenticateUserAsync method, then the window apperas, and after that nothing happens.
I'm also not sure what the returnURL is supposed to be because all examples where either for an app version or just said return URL without giving any examples.
sorry for the delay. Have you tried this method:
msaAuthenticationProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync();
Edit : If the last known connection token is usable, this method can be used to authenticate the user without prompt it. So, this restore the last authentication cache if it can or prompt the user to give his login and password. This can replace the already used AuthenticateUserAsync method. I had the same issue and this method solved it.
Edit 2 : The OneDrive SDK documentation is very poor, I found this myself fiercely as I found that you can get the connection token (to save it for example) and inject it when you need like that in an async task :
if (_OneDriveCacheBlob == null)
{
bool needtosaveblob = true;
_OneDriveCacheBlob = null;
CredentialCache cc = new CredentialCache();
_OneDriveCacheBlob = GetUser(CurrentUserName).OneDriveAuthProviderBlob;
if (_OneDriveCacheBlob != null)
{
cc.InitializeCacheFromBlob(_OneDriveCacheBlob);
needtosaveblob = false;
}
MsaAuthenticationProvider msaAuthProvider = new MsaAuthenticationProvider(OneDriveClass.clientId, OneDriveClass.returnUrl, scopes, cc);
int timeout = 15;
_ = Task.Run(() => WaitForODConnection(msaAuthProvider));
while (!WaitForODConnectionExecuted)
{
if (timeout <= 0)
break;
await Task.Delay(TimeSpan.FromSeconds(1));
timeout -= 1;
}
WaitForODConnectionExecuted = false;
if (timeout <= 0)
{
// Request for reconnection to OneDrive because of invalid Blob
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
{
//This method requests a new login by a simple msaAuthProvider.AuthenticateUserAsync() call from a new instance of MsaAuthenticationProvider and a new instance of CredentialCache.
//ChangeOneDriveAccount();
});
}
else
{
_OneDriveClient = new OneDriveClient(OneDriveClass.basUrl, msaAuthProvider);
}
string accessToken = msaAuthProvider.CurrentAccountSession.AccessToken;
JObject json = await GetUserInfos(msaAuthProvider.CurrentAccountSession.AccessToken);
if (json != null)
{
// If you need
oneDriveUserName = json["name"].ToString();
oneDriveEmail = json["emails"]["account"].ToString();
}
else
{
//Unable to get OneDrive user informations;
}
if (needtosaveblob)
{
_OneDriveCacheBlob = cc.GetCacheBlob();
//You can save _OneDriveCacheBlob to reuse it later;
}
}
To get the user infos :
/// <summary>
/// Return User informations as a JObject. To get username and email, if return isn't null :
/// username = json["name"].ToString();
/// email = json["emails"]["account"].ToString();
/// </summary>
/// <param name="accessToken">accesstoken of Onedrive account</param>
/// <returns>JObject value</returns>
public static async Task<JObject> GetUserInfos(string accessToken)
{
JObject json = null;
Uri uri = new Uri($"https://apis.live.net/v5.0/me?access_token={accessToken}");
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage result = await httpClient.GetAsync(uri);
//user info returnd as JSON
string jsonUserInfo = await result.Content.ReadAsStringAsync();
if (jsonUserInfo != null)
{
json = JObject.Parse(jsonUserInfo);
//username = json["name"].ToString();
//email = json["emails"]["account"].ToString();
}
return json;
}
And because the OneDrive method never expires if the token is no longer usable :
bool WaitForODConnectionExecuted = false;
private async Task WaitForODConnection(MsaAuthenticationProvider msaAuthProvider)
{
await msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync();
WaitForODConnectionExecuted = true;
}
It was not funny and I think my code is not clean so do not use it as it is without working a little on it.

Remembering log in credentials/permissions UWP/C# (Microsoft Cloud API)

I'm creating an app that access the Microsoft Cloud API to get health data. It uses OAuth to log in when you hit the Sign In Button
private void signinButton_Click(object sender, RoutedEventArgs e)
{
UriBuilder uri = new UriBuilder("https://login.live.com/oauth20_authorize.srf");
var query = new StringBuilder();
query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(RedirectUri));
query.AppendFormat("&client_id={0}", Uri.EscapeDataString(ClientId));
query.AppendFormat("&scope={0}", Uri.EscapeDataString(Scopes));
query.Append("&response_type=code");
uri.Query = query.ToString();
this.webView.Visibility = Visibility.Visible;
this.webView.Navigate(uri.Uri);
}
This brings up a webView with the page to log in using Microsoft credentials. Once completed, it leads to this:
private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
//
// When the web view navigates to our redirect URI, extract the authorization code from
// the URI and use it to fetch our access token. If no authorization code is present,
// we're completing a sign-out flow.
//
if (args.Uri.LocalPath.StartsWith("/oauth20_desktop.srf", StringComparison.OrdinalIgnoreCase))
{
WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(args.Uri.Query);
var code = decoder.FirstOrDefault((entry) => entry.Name.Equals("code", StringComparison.OrdinalIgnoreCase));
var error = decoder.FirstOrDefault((entry) => entry.Name.Equals("error", StringComparison.OrdinalIgnoreCase));
var errorDesc = decoder.FirstOrDefault((entry) => entry.Name.Equals("error_description", StringComparison.OrdinalIgnoreCase));
// Check the code to see if this is sign-in or sign-out
if (code != null)
{
// Hide the browser again, no matter what happened...
sender.Visibility = Visibility.Collapsed;
if (error != null)
{
this.responseText.Text = string.Format("{0}\r\n{1}", error.Value, errorDesc.Value);
return;
}
var tokenError = await this.GetToken(code.Value, false);
if (string.IsNullOrEmpty(tokenError))
{
this.responseText.Text = "Successful sign-in!";
this.signoutButton.IsEnabled = true;
this.signinButton.IsEnabled = false;
this.getProfileButton.IsEnabled = true;
this.getDevicesButton.IsEnabled = true;
this.getActivitiesButton.IsEnabled = true;
this.getDailySummaryButton.IsEnabled = true;
this.getHourlySummaryButton.IsEnabled = true;
}
else
{
this.responseText.Text = tokenError;
}
}
else
{
this.responseText.Text = "Successful sign-out!";
this.signoutButton.IsEnabled = false;
this.signinButton.IsEnabled = true;
this.getProfileButton.IsEnabled = false;
this.getDevicesButton.IsEnabled = false;
this.getActivitiesButton.IsEnabled = false;
this.getDailySummaryButton.IsEnabled = true;
this.getHourlySummaryButton.IsEnabled = false;
}
}
}
private async Task<string> GetToken(string code, bool isRefresh)
{
UriBuilder uri = new UriBuilder("https://login.live.com/oauth20_token.srf");
var query = new StringBuilder();
query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(RedirectUri));
query.AppendFormat("&client_id={0}", Uri.EscapeDataString(ClientId));
query.AppendFormat("&client_secret={0}", Uri.EscapeDataString(ClientSecret));
if (isRefresh)
{
query.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(code));
query.Append("&grant_type=refresh_token");
}
else
{
query.AppendFormat("&code={0}", Uri.EscapeDataString(code));
query.Append("&grant_type=authorization_code");
}
uri.Query = query.ToString();
var request = WebRequest.Create(uri.Uri);
try
{
using (var response = await request.GetResponseAsync())
{
using (var stream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(stream))
{
var responseString = streamReader.ReadToEnd();
var jsonResponse = JObject.Parse(responseString);
this.creds.AccessToken = (string)jsonResponse["access_token"];
this.creds.ExpiresIn = (long)jsonResponse["expires_in"];
this.creds.RefreshToken = (string)jsonResponse["refresh_token"];
string error = (string)jsonResponse["error"];
return error;
}
}
}
}
catch (Exception ex)
{
return ex.Message;
}
}
I don't want users to have to accept the permissions every time the app is launched. Is there a way to save credentials locally so that it automatically authenticates on launch? Thanks!
You can use
Windows.Storage.ApplicationData.Current.LocalSettings
This process good described by this answer Best Way to keep Settings for a WinRT App?
The code in link identity to UWP
Store the needed oauth parts in the credential locker API. Never store these kind of information in the normal settings API.
On start read the oauth information and use the refreshtoken to get a new access token.
More Information here.
https://msdn.microsoft.com/en-us/library/windows/apps/mt270189.aspx

DropNet unable to save Access Token for consequent requests?

As many people before me, I'm failing miserably to successfully save an access token between launches of my application. This application is actually only going to be used with one specific dropbox account, though I'm trying to make it easy to set up and a bit more dynamic.
Of course, if the settings are empty (initial run), the user can correctly log in and authorize the app, and coming back to the app it works as intended. On subsequent runs, however, when it grabs the token and secret from the settings collection it fails miserably with
Received Response [Unauthorized] : Expected to see [OK]. The HTTP
response was [{"error": "Invalid signature."}].
I'm obviously doing something wrong, what is it? Thanks!
Code below!
using System;
using DropNet;
namespace DS_Uploader_DropBox {
class Program {
private const string AppKey = "my super secret app key";
private const string AppSecret = "my super secret app secret";
static void Main(string[] args) {
DropNetClient client;
DropNet.Models.UserLogin token;
string userToken = Settings.Default.userToken;
string userSecret = Settings.Default.userSecret;
bool needAccessToken = (String.IsNullOrEmpty(userToken) || string.IsNullOrEmpty(userSecret));
//needAccessToken = true;
if (needAccessToken) {
client = new DropNet.DropNetClient(AppKey, AppSecret);
client.UseSandbox = true;
client.GetToken();
// Auth with dropbox
var url = client.BuildAuthorizeUrl();
// Prompt for user to auth
Console.WriteLine("go auth here " + url);
Console.ReadLine();
// If the user authed, let's get that token
try {
token = client.GetAccessToken();
}
catch (Exception e) {
Console.WriteLine("Exception! " + e.Message);
return;
}
// save for later
userToken = token.Token;
userSecret = token.Secret;
Settings.Default.userToken = userToken;
Settings.Default.userSecret = userSecret;
Settings.Default.Save();
} else {
client = new DropNet.DropNetClient(AppKey, AppSecret, userToken, userSecret);
client.UseSandbox = true;
client.GetToken();
// get that token
try {
token = client.GetAccessToken();
} catch (Exception e) {
Console.WriteLine("Exception! " + e.Message);
return;
}
}
var acctInfo = client.AccountInfo();
Console.WriteLine(acctInfo.display_name);
Console.ReadLine();
}
}
}
Code that worked to follow:
using System;
using DropNet;
namespace DS_Uploader_DropBox {
class Program {
private const string AppKey = "my super secret app key";
private const string AppSecret = "my super secret app secret";
static void Main(string[] args) {
DropNetClient client;
DropNet.Models.UserLogin token;
string userToken = Settings.Default.userToken;
string userSecret = Settings.Default.userSecret;
bool needAccessToken = (String.IsNullOrEmpty(userToken) || string.IsNullOrEmpty(userSecret));
//needAccessToken = true;
if (needAccessToken) {
client = new DropNet.DropNetClient(AppKey, AppSecret);
client.UseSandbox = true;
client.GetToken();
// Auth with dropbox
var url = client.BuildAuthorizeUrl();
// Prompt for user to auth
Console.WriteLine("go auth here " + url);
Console.ReadLine();
// If the user authed, let's get that token
try {
token = client.GetAccessToken();
}
catch (Exception e) {
Console.WriteLine("Exception! " + e.Message);
return;
}
// save for later
userToken = token.Token;
userSecret = token.Secret;
Settings.Default.userToken = userToken;
Settings.Default.userSecret = userSecret;
Settings.Default.Save();
} else {
client = new DropNet.DropNetClient(AppKey, AppSecret, userToken, userSecret);
client.UseSandbox = true;
}
var acctInfo = client.AccountInfo();
Console.WriteLine(acctInfo.display_name);
Console.ReadLine();
}
}
}
In the code path where needAccessToken is false, you're calling GetToken and GetAccessToken again, in an attempt to get a new request token and a new access token, respectively. This is unnecessary, as you already have and retrieved the existing access token in userToken and userSecret.

Categories

Resources