getting security warning in facebook authentication - c#

I am getting security warning while using authentication in facebook app.My code is as shown with screenShot with security warning
private void imageFacebook_Tap(object sender, GestureEventArgs e)
{
FaceBookBlocker.Visibility = Visibility.Visible;
pop_up.IsOpen = true;
//Get this from the facebook
string appId = "My Facebook App Id";
var parameters = new Dictionary<string, object>();
parameters["client_id"] = appId;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
string extendedPermissions = "user_about_me,read_stream,publish_stream";
// add the 'scope' only if we have extendedPermissions.
if (!string.IsNullOrEmpty(extendedPermissions))
{
// A comma-delimited list of permissions
parameters["scope"] = extendedPermissions;
}
var oauth = new FacebookOAuthClient();
//Create the login url
var loginUrl = oauth.GetLoginUrl(parameters);
////Open the facebook login page into the browser
_webBrowser.Navigate(loginUrl);
}

I do have resolved.Check my answer here. Escape from Facebook security Warning
Also replace http: with https: in the Facebook GraphAPI.

There is going to be your code,where you connect to Facebook.Best guess would be Facebook has rolled out a security change to their API and the code being used by you has not been updated to work with the new API
Alternatively
You need to delete this bit of code
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "// connect . facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
Looks like it is in your footer?

I just hide BrowserControl if navigating to the success page
private void BrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
if (e.Uri.AbsolutePath.ToString() == "/connect/login_success.html")
{
BrowserControl.Visibility = Visibility.Collapsed;
}
if (NavigatingCallback != null)
{
NavigatingCallback();
}
}

Related

Get firstname, lastname and email address from Facebook using ASP.NET

I have the below code in my Startup.Auth.cs file but I can't find a way to get the firstname and lastname from Facebook:
var facebookOptions = new FacebookAuthenticationOptions()
{
AppId = "",
AppSecret = "",
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,email"
};
facebookOptions.Scope.Add("email");
facebookOptions.Scope.Add("public_profile");
app.UseFacebookAuthentication(facebookOptions);
Here is a quick example of how you can get the user information from Facebook in asp.net winforms. This example uses the Facebook SDK for .Net.
This snippet logs in the user with Facebook and then gets the extra user info, but can also be used for just getting the extra profile data.
static string Facebook_Key = "yourAppID";
static string Facebook_Secret = "yourAppSecret";
protected void Page_Load(object sender, EventArgs e)
{
//check if the user is returning from Facebook
if (Request.QueryString["code"] != null)
{
FacebookClient fbc = new FacebookClient();
//retreive the access token
dynamic result = fbc.Post("oauth/access_token", new
{
client_id = Facebook_Key,
client_secret = Facebook_Secret,
redirect_uri = Request.Url.AbsoluteUri,
code = Request.QueryString["code"].ToString()
});
fbc.AccessToken = result.access_token;
//get the extra profile data
dynamic user = fbc.Get("me?fields=first_name,last_name,id,email");
//display the results
FacebookLoginLabel.Text += user.id + "<br>";
FacebookLoginLabel.Text += user.first_name + "<br>";
FacebookLoginLabel.Text += user.last_name + "<br>";
FacebookLoginLabel.Text += user.email + "<br>";
//start the actual aspnet registration or login
LoginOrRegisterUser();
}
}
protected void FacebookLoginButton_Click(object sender, EventArgs e)
{
FacebookClient fbc = new FacebookClient();
//start the Facebook login request
var loginUrl = fbc.GetLoginUrl(new
{
client_id = Facebook_Key,
redirect_uri = Request.Url.AbsoluteUri,
response_type = "code",
scope = "email"
});
//redirect the user to Facebook for authentication
Response.Redirect(loginUrl.AbsoluteUri);
}
ASPX
<asp:Button ID="FacebookLoginButton" runat="server" Text="Log in with Facebook" OnClick="FacebookLoginButton_Click" />
<asp:Label ID="FacebookLoginLabel" runat="server" Text=""></asp:Label>

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

Twitter Integration In windows Phone 7

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..!!

Upload image directly to twitter

I need help in uploading images directly to twitter in Windows Phone 7.
I am done with oauth flow of twitter and can also could update tweets but I have not been able to upload image to twitter using wp7?
I have worked out a solution for this, by using the Hammock.WindowsPhone.Mango library.
(TweetSharp internally uses Hammock library for oAuth and other functionalities, but I have never used TweetSharp or Twitterizer)
I have installed the latest version of Hammock from Nuget
And then the following code is used for photo upload to Twitter:
public void uploadPhoto(Stream photoStream, string photoName)
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.consumerKey,
ConsumerSecret = TwitterSettings.consumerKeySecret,
Token = TwitterSettings.accessToken,
TokenSecret = TwitterSettings.accessTokenSecret,
Version = "1.0a"
};
RestClient restClient = new RestClient
{
Authority = "https://upload.twitter.com",
HasElevatedPermissions = true,
Credentials = credentials,
Method = WebMethod.Post
};
RestRequest restRequest = new RestRequest
{
Path = "1/statuses/update_with_media.json"
};
restRequest.AddParameter("status", tbxNewTweet.Text);
restRequest.AddFile("media[]", photoName, photoStream, "image/jpg");
}
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
}
private void PostTweetRequestCallback(RestRequest request, Hammock.RestResponse response, object obj)
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Success code
}
}
Here,
photoName is the name of the image selected ( "e.OriginalFileName")
photoStream is the "e.ChosenPhoto" from the PhotoChooserTask
and the 4th parameter for .AddFile() should be taken care (I have not considered other formats while doing this sample, you have to take care in your apps)
I hope this helps!!
LINQ to Twitter supports WP7 and has a TweetWithMedia method that works like this:
private void PostButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(TweetTextBox.Text))
MessageBox.Show("Please enter text to tweet.");
ITwitterAuthorizer auth = SharedState.Authorizer;
if (auth == null || !auth.IsAuthorized)
{
NavigationService.Navigate(new Uri("/OAuth.xaml", UriKind.Relative));
}
else
{
var twitterCtx = new TwitterContext(auth);
var media = GetMedia();
twitterCtx.TweetWithMedia(
TweetTextBox.Text, false, StatusExtensions.NoCoordinate, StatusExtensions.NoCoordinate, null, false,
media,
updateResp => Dispatcher.BeginInvoke(() =>
{
HandleResponse(updateResp);
}));
}
}
Joe

how to update twitter status from my asp.net web page

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

Categories

Resources