I have created an asp.net web page and I am using twitterizer.framework.dll.
Below is my c# code.
protected void btnTwitt_Click(object sender, EventArgs e)
{
//OAuthTokens tokens = new OAuthTokens();
//tokens.AccessToken = "--REDACTED--";
//tokens.AccessTokenSecret = "--REDACTED--";
//tokens.ConsumerKey = "--REDACTED--";
//tokens.ConsumerSecret = "--REDACTED--";
/////
//TwitterResponse<TwitterUser> showUserResponse = TwitterUser.Show(tokens, "twit_er_izer");
string TwitterUserName = "My twitter username";
string TwitterPassword = "my password";
// string TwitterMessage = txtShout.Text;
if (TwitterUserName != string.Empty && TwitterPassword != string.Empty)
{
try
{
//Twitter
// TwitterAccount twitter = new TwitterAccount(TwitterUserName, TwitterPassword);
//Twitter tw
Twitter twitter = new Twitter(TwitterUserName, TwitterPassword);
string TwitterMsg = txtShout.Text;
if (txtShout.Text.Length > 120)
{
TwitterMsg = TwitterMsg.Substring(0, 130) + "... For more update logon to DailyFreeCode.com";
}
else
{
TwitterMsg = TwitterMsg + "... For more update logon to DailyFreeCode.com";
}
twitter.Status.Update(TwitterMsg);
//Twitterizer.TwitterStatus.Update(tokens,TwitterMsg);
lblTwitMsg.Text = "Your have shout successfully on http://twitter.com/" + TwitterUserName;
}
catch (Exception ex)
{
Response.Write("<b>" + ex.Message + "</b><br>" + ex.StackTrace);
}
}
}
Now, I am getting error authorization failed.
On this line
twitter.Status.Update(TwitterMsg);
Plz help me, thanks!
It appears as though you're using Twitterizer version 1.x, but trying to copy code examples from Twitterizer version 2.x. Twitter twitter = new Twitter(TwitterUserName, TwitterPassword); is a dead giveaway. 2.x no longer uses that syntax.
Twitter no longer allows access to the API by supplying username and password. The tokens ARE your username and password, in a manner of speaking.
If you use the twitterizer framework you shouldn't be passing the username/password. You need to fill:
OAuthTokens tokens = new OAuthTokens();
tokens.AccessToken = "XXX";
tokens.AccessTokenSecret = "XXX";
tokens.ConsumerKey = "XXX";
tokens.ConsumerSecret = "XXX";
you can do this by using the following three methods from the framework:
1:
public static Uri BuildAuthorizationUri(
string requestToken
)
2:
public static OAuthTokenResponse GetRequestToken(
string consumerKey,
string consumerSecret,
string callbackAddress
)
3:
OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, requestToken, verifier);
look it up here
Related
it is the first time I'm working with LDAP and Active Directory. I have to make a web api with .NetCore that have to authenticate with ActiveDirectory (WindowsServer 2008 r2), I'm following the samples in Novell.Directory.Ldap.NETStandard but i can't understand the way that I must set the parameters.
This is the users that I created in ActiveDirectory Server:
In Novell's samples
if (args.Length != 5)
{
System.Console.Out.WriteLine("Usage: mono VerifyPassword <host name>" + " <login dn> <password> <object dn>\n" + " <test password>");
System.Console.Out.WriteLine("Example: mono VerifyPassword Acme.com " + "\"cn=Admin,o=Acme\" secret\n" + " \"cn=JSmith,ou=Sales,o=Acme\" testPassword");
System.Environment.Exit(0);
}
int ldapPort = LdapConnection.DEFAULT_PORT;
int ldapVersion = LdapConnection.Ldap_V3;
System.String ldapHost = args[0];
System.String loginDN = args[1];
System.String password = args[2];
System.String objectDN = args[3];
System.String testPassword = args[4];
LdapConnection conn = new LdapConnection();
try
{
// connect to the server
conn.Connect(ldapHost, ldapPort);
// authenticate to the server
conn.Bind(ldapVersion, loginDN, password);
LdapAttribute attr = new LdapAttribute("userPassword", testPassword);
bool correct = conn.Compare(objectDN, attr);
System.Console.Out.WriteLine(correct?"The password is correct.":"The password is incorrect.\n");
// disconnect with the server
conn.Disconnect();
}
In Novell's samples the "user" parameters looks like this "ou=sales,o=Acme", so I was trying:
int ldapPort = LdapConnection.DEFAULT_PORT;
int ldapVersion = LdapConnection.Ldap_V3;
bool compareResults = false;
String ldapHost = "192.168.58.251";
String loginDN = #"cn=jperez";
String password1 = "Jperez123";
String dn = "mydn";
LdapConnection lc = new LdapConnection();
LdapAttribute attr = null;
try
{
// connect to the server
lc.Connect(ldapHost, ldapPort);
var sdn = lc.GetSchemaDN();
// authenticate to the server
lc.Bind(ldapVersion, loginDN, password1);
...
}
catch (LdapException e)
{
Console.WriteLine("Error: " + e.ToString());
}
But I get this error:
LDAP:
LdapException: Invalid Credentials (49) Invalid Credentials
LdapException: Server Message: 80090308: LdapErr: DSID-0C0903A8,
comment: AcceptSecurityContext error, data 52e, v1db1\u0000
LdapException: Matched DN:
I also get the schemaDn with this funciton: lc.GetSchemaDN(), that return this result: CN=Aggregate,CN=Schema,CN=Configuration,DC=mydn,DC=local
After googling there is no much information with .Netcore than the Novell's samples, please I need your help.
Been working on this as well and ran into the same error. I had to use the Windows domain and username to log in:
String loginDN = "DOMAIN\\jperez";
String password1 = "Jperez123";
lc.Bind(loginDN, password1);
Once I did that, I got in without issue.
I had the same issue and the only way I got it working was by supplying the login like this
lc.Bind("user#domain", "pwd")
I had the same issue until I used this
lc.Bind("uid=" + objUser.UserName + ",ou=SomeValue,dc=SomeValue,dc=SomeValue",password);
also I did not supply a version like in your example
It also works for me:
var ldapVersion = LdapConnection.Ldap_V3;
var loginDN = "CN=victor,CN=Users,DC=example,DC=com";
var password = "123";
conn.Bind(ldapVersion, loginDN, password);
Works on Windows Server 2012r2 with the default domain settings.
If you want to get loginDNs for your domain users, just execute next cmd command on domain controller:
dsquery user
More information here
Yet another variation, I found I had to logon as:
"PartA PartB" of an AD username. (notice the space in the name.)
example being "App Alerts" whereas I normally can login with "AppAlerts"... but this is the Fully Qualified name i found with dsquery user:
"CN=App Alerts,OU=SBSUsers,OU=Users,OU=MyBusiness,DC=myinc,DC=local"
DotNet Version : 6
Novel nuget Package: Novell.Directory.Ldap.NETStandard
Active Directory : 2019 AD server
Step 1 :Add a console Application:
step 2 : Add a class and then put this method in it :
public string Validate(string _username, string _password)
{
string username = _username;
string password = _password;
string domainName = "spenter.com";
string userDn = $"spenterdomain\\{username}";
int ldapVersion = LdapConnection.LdapV3;
// var connection = new LdapConnection { SecureSocketLayer = true };
try
{
using (var ldapConnection = new LdapConnection { SecureSocketLayer = false })
{
ldapConnection.Connect(domainName, LdapConnection.DefaultPort);
ldapConnection.Bind(userDn, password);
if (ldapConnection.Bound)
return $"{username} : has been Authenthicated";
}
}
catch (LdapException ex)
{
Console.WriteLine(ex);
}
return "Credentials Incorrect";
}
Step 3 Main Program Code:
using ldap;
yourclass l1 = new yourclass();
Console.WriteLine("Enter your AD ID");
string uName = Console.ReadLine().ToString();
Console.WriteLine("Enter your AD Pwd");
string Pwd = Console.ReadLine().ToString();
var result = l1.Validate(uName, Pwd);
Console.WriteLine(result);
Console.ReadLine();
I want to get access token from instagram api in windows store app
Here's my code:
string endURL = "ms-app://.."; string clientID = "..";
Uri endUri = new Uri(endURL);
string startURL = "https://api.instagram.com/oauth/authorize/?"
+ "client_id=" + clientID
+ "&redirect_uri=" + endURL
+ "&response_type=code";
try
{
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync
(WebAuthenticationOptions.None, startUri);
if (result.ResponseStatus == WebAuthenticationStatus.Success) {
string token = webAuthenticationResult.ResponseData;
}
catch(Exception) { }
I get that error:
The specified protocol is unknown. (Exception from HRESULT: 0x800C000D)
Why don't you directly use InstaAPI
github & codeplex?
List<Scope> scopes = new List<Scope>() { Scope.basic };
InstaConfig config = new InstaConfig("CLIENT_ID", "CLIENT_SECRET", "REDIRECT_URI", scopes);
// use this to redirect user for authenticating your application
String AuthenticationUriString = config.GetAuthenticationUriString();
OAuth oauth = new OAuth(config, "CODE_ATTACHED_WITH_REDIRECTEDURI_AFTERSUCCESSFUL_AUTHENTICATION");
AuthUser user = oauth.GetAuhtorisedUser();
Console.WriteLine(user.AccessToken);
I want to get the user information from the twitter and show in windows phone 7. I found some examples for twitter integration.
Link 1
Link 2
But in this examples i can only login to the twitter. I can not post or can not get the user information. Can any one provide a sample application or links for windows phone 7 twitter integration.
After getting login i try like this:
private void btntest_Click(object sender, RoutedEventArgs e)
{
string newURL = string.Format("https://api.twitter.com/1.1/users/show.json?screen_name={0}", userScreenName);
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webBrowser_Navigated);
webClient.DownloadStringAsync(new Uri(newURL));
}
void webBrowser_Navigated(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("Error ");
return;
}
Console.WriteLine("Result==> " + e.Result);
//List<Tweet> tweets = JsonConvert.DeserializeObject<List<Tweet>>(e.Result);
//this.lbTweets.ItemsSource = tweets;
}
But here i can not get the user information. Please help me to get the user infoemation.
Thanks in advance.
Did you try using the Tweetinvi API from Codeplex, where you could grab the user details as well you could post tweets.
Tweetinvi a friendly Twitter C# API
Have a look at this one too:
Windows Phone 8 - Twitter API
Finally i found the Solution..!!! :-)
public void GetTwitterDetail(string _userScreenName)
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
};
var restClient = new RestClient
{
Authority = "https://api.twitter.com/1.1",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = string.Format("/users/show.json?screen_name={0}&include_entities=true", _userScreenName),
Method = WebMethod.Get
};
restClient.BeginRequest(restRequest, new RestCallback(test));
}
private void test(RestRequest request, RestResponse response, object obj)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Console.WriteLine("Content==> " + response.Content.ToString());
Console.WriteLine("StatusCode==> " + response.StatusCode);
});
}
Now i got the User's In formations..!!! 5 days struggling comes to end..!! Thanks to all..!!
i'm using oauth and twitterizer in my C# apps, and after trying for several times. and it won't get any exception, error. but it's doesn't want to post it to twitter.
here is my code
protected void Page_Load(object sender, EventArgs e)
{
BLTgUser objBLTgUser = new BLTgUser();
if (!objBLTgUser.IsLogin) objBLTgUser.GoToLoginPage(HttpContext.Current.Request.Url.AbsoluteUri);
m_strIdGods = objBLTgUser.IdGods;
BLGodsProfile objGods = new BLGodsProfile();
tbmgodsprofile objGodsProfile = objGods.GetGodsByIdGods(m_strIdGods);
string reqToken = Request.QueryString["oauth_token"].ToString();
string pin = Request.QueryString["oauth_verifier"].ToString();
var oauth_consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
var oauth_consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"];
var tokens = OAuthUtility.GetAccessToken(
oauth_consumerKey,
oauth_consumerSecret,
reqToken,
pin);
string accessToken = tokens.Token;
string accessTokenSecret = tokens.TokenSecret;
objGodsProfile.twittertoken = accessToken;
objGodsProfile.twitterpin = accessTokenSecret;
objGodsProfile.twitterstatus = "1";
objGods.UpdateGodsProfile(objGodsProfile);
}
i'm trying store the token and tokensecret to Database, it's for the next uses.
string v_str = "";
BLEnumHelper m_BLEnumHelper = new BLEnumHelper();
BLGodsProfile userprofile = new BLGodsProfile();
tbmgodsprofile godsAccessToken = userprofile.GetGodsByIdGods(m_strIdGods);
string reqToken = godsAccessToken.twittertoken;
string reqTokenAccess = godsAccessToken.twitterpin;
var oauth_consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
var oauth_consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"];
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = reqToken,
AccessTokenSecret = reqTokenAccess ,
ConsumerKey = oauth_consumerKey,
ConsumerSecret = oauth_consumerSecret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accesstoken,p_strMessage);
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
and after the 2nd code be called, it wont' post to twitter.
Twitterizer is no longer maintained.
https://github.com/Twitterizer/Twitterizer/blob/develop/README.mediawiki
Twitterizer not supporting Twitter's new API version 1.1, you can't use it for development.
As an alternative, I recommend CoreTweet for you.
I am writing an Metrol Style App to update status on my Twitter. I use LINQ to Twitter library. But I don't understand why my app throws exception 401 Unauthorized. Here is my code:
private void UpdateStatus()
{
// configure the OAuth object
var auth = new SingleUserAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = "ConsumerKey",
ConsumerSecret = "ConsumerSecret",
OAuthToken = "TwitterAccessToken",
AccessToken = "TwitterAccessTokenSecret"
}
};
using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/", "https://search.twitter.com/"))
{
var tweet = twitterCtx.UpdateStatus("Hi everybody!"); // error here
viewTextBlock.Text = String.Empty;
viewTextBlock.Text = viewTextBlock.Text + "Status returned: " +
"(" + tweet.StatusID + ")" +
tweet.User.Name + ", " +
tweet.Text + "\n";
}
}
I just posted a blog entry on using OAuth in Windows 8 with LINQ to Twitter:
http://geekswithblogs.net/WinAZ/archive/2012/07/02/using-linq-to-twitter-oauth-with-windows-8.aspx
I also included a 401 FAQ in the LINQ to Twitter docs here:
http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20FAQ&referringTitle=Documentation
You can implement it using the Twitterizer assembly.
Firstly you can create a token which can be used to access Twitter and then using that particular token you can update TwitterStatus (Twitterizer.Core.TwitterObject.TwitterStatus).
Sample code is as follows.
public void CreateCachedAccessToken(string requestToken)
{
string ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
string ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];
OAuthTokenResponse responseToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, requestToken);
//Cache the UserId
Session["GetCachedUserId"] = responseToken.UserId;
OAuthTokens accessToken = new OAuthTokens();
accessToken.AccessToken = responseToken.Token;
accessToken.AccessTokenSecret = responseToken.TokenSecret;
accessToken.ConsumerKey = ConsumerKey;
accessToken.ConsumerSecret = ConsumerSecret;
Session["AccessToken"] = accessToken;
}
To update the TwitterStatus you can do as follows.
public OAuthTokens GetCachedAccessToken()
{
if (Session["AccessToken"] != null)
{
return (OAuthTokens)(Session["AccessToken"]);
}
else
{
return null;
}
}
TwitterStatus.Update(GetCachedAccessToken(), txtTweet.Trim());
The below mentioned method can be used to implement sign in.
protected string GetTwitterAuthorizationUrl()
{
string ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
string ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret);
return "https://twitter.com/oauth/authorize?oauth_token=" + reqToken.Token;
}
Hope this helps.
If there are any clarifications please raise. Thanks