I implemented Facebook-Connect successfully and I'm able to retrieve User-Information using the Facebook Toolkit. But I cant sucessfully logout.
When I press the facebook-Logout button (which automatically appears when I'm logged in, because I'm using the autologoutlink-property)
<fb:login-button autologoutlink="true"></fb:login-button>
I still have all five Facebook-Cookies:
MyApiKey
MyApiKey_ss
MyApiKey_SessionKey
MyApiKey_expires
MyApiKey_user
After I'm logged out, I'm really logged out in Facebook, because I need to login again at facebook.com but isConnected() always returns true and I can still retrieve the user Information:
var connectSession = new ConnectSession(ConfigurationManager.AppSettings["ApiKey"], ConfigurationManager.AppSettings["Secret"]);
if (connectSession.IsConnected())
{
var api = new Api(connectSession);
filterContext.Controller.ViewData["FBUser"] = api.Users.GetInfo();
}
First I don't understand why I can still retrieve User Information even though I'm not logged in any more, and secondly: How I can delete this Cookies. The Following Code didn't work:
public static void ClearFacebookCookies()
{
String[] shortNames = new String[] { "_user", "_session_key", "_expires", "_ss", "" };
HttpContext currentContext = HttpContext.Current;
if (currentContext == null)
{
return;
}
string appKey = ConfigurationManager.AppSettings["APIKey"];
if (appKey == null)
{
throw new Exception("APIKey is not defined in web.config");
}
foreach (var name in shortNames)
{
string fullName = appKey + name;
HttpCookie cookie = currentContext.Response.Cookies[fullName];
if (cookie != null)
{
cookie.Value = null;
cookie.Expires= DateTime.Now.AddDays(-1d);
}
HttpCookie cookieRequest = currentContext.Request.Cookies[fullName];
if (cookieRequest != null)
{
cookieRequest.Value = null;
cookieRequest.Expires = DateTime.Now.AddDays(-1d);
}
}
}// end Method
This may be a shot in the dark, but did you make sure the fb.init is placed just before the closing body tag?
<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US"></script>
<script type="text/javascript">FB.init('somekey');</script>
That's caused me problems before.
Related
I followed example from here (https://learn.microsoft.com/en-gb/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview#invoke-c-from-javascript) to setup WebView for my project and I can invoke C# code from WebView page event, that is working fine.
However, before sending a request I have to setup a Cookie and that cookie should be passed to remote server. I followed several examples from net I am getting it to work for Android but iOS its not working.
Code I got from another Stackoverflow question as follows.
Android Working
var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie(true);
cookieManager.RemoveAllCookie();
var cookies = UserInfo.CookieContainer.GetCookies(new System.Uri(AppInfo.URL_BASE));
for (var i = 0; i < cookies.Count; i++)
{
string cookieValue = cookies[i].Value;
string cookieDomain = cookies[i].Domain;
string cookieName = cookies[i].Name;
cookieManager.SetCookie(cookieDomain, cookieName + "=" + cookieValue);
}
iOS Not Working
// Set cookies here
var cookieUrl = new Uri(AppInfo.URL_BASE);
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
foreach (var aCookie in cookieJar.Cookies)
{
cookieJar.DeleteCookie(aCookie);
}
var jCookies = UserInfo.CookieContainer.GetCookies(cookieUrl);
IList<NSHttpCookie> eCookies =
(from object jCookie in jCookies
where jCookie != null
select (Cookie) jCookie
into netCookie select new NSHttpCookie(netCookie)).ToList();
cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);
I have tried code from WebView documentation here, Cookie section (https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=macos#cookies)
I'll really appreciate if anybody can point out what I am doing wrong any hints.
Thanks.
Update
In my HybridWebViewRenderer method I am adding my custom Cookie as follows.
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
userController.RemoveAllUserScripts();
userController.RemoveScriptMessageHandler("invokeAction");
HybridWebView hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup();
}
if (e.NewElement != null)
{
string cookieDomain = new System.Uri(((HybridWebView)Element).Uri).Host;
foreach (var c in NSHttpCookieStorage.SharedStorage.Cookies)
{
Console.WriteLine("Cookie (Delete)" + c.Name);
NSHttpCookieStorage.SharedStorage.DeleteCookie(c);
}
var cookieDict = new NSMutableDictionary();
cookieDict.Add(NSHttpCookie.KeyDomain, new NSString("." + cookieDomain));
cookieDict.Add(NSHttpCookie.KeyName, new NSString("ABC"));
cookieDict.Add(NSHttpCookie.KeyValue, new NSString("123e4567-e89b-12d3-a456-426652340003"));
cookieDict.Add(NSHttpCookie.KeyPath, new NSString("/"));
cookieDict.Add(NSHttpCookie.KeyExpires, DateTime.Now.AddDays(1).ToNSDate());
var myCookie = new NSHttpCookie(cookieDict);
NSHttpCookieStorage.SharedStorage.SetCookie(myCookie);
string filename = $"{hybridView.Uri}";
var request = new NSMutableUrlRequest(new NSUrl(filename));
var wkNavigation = LoadRequest(request);
}
}
In AppDelegate I have added.
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
return base.FinishedLaunching(app, options);
}
Still no luck :( .........
You need to set the cookie in the shared storage.
Set your shared storage policy to always accept your own cookies.
In your ApplicationDelegate:
NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
I want to oauth authentication like
Login using Google OAuth 2.0 with C#
But i don't want to authentication prompt popup
i want to get token directly without popup..
public ActionResult CodeLele()
{
if (Session.Contents.Count > 0)
{
if (Session["loginWith"] != null)
{
if (Session["loginWith"].ToString() == "google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
// This is where you want to add the code if login is successful.
// getgoogleplususerdataSer(accessToken);
}
else
{ }
}
else
{ }
}
else
{ }
}
}
catch (WebException ex)
{
try
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
//var messageFromServer = obj.error.message;
//return messageFromServer;
return obj.error_description;
}
catch (Exception exc)
{
throw exc;
}
}
}
}
}
return Content("done");
}
public ActionResult JeClick()
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["loginWith"] = "google";
return Redirect(Googleurl);
}
The credentials window (popup) is how you ask the user if you can access their data. There is no way to get access to a users data without asking the user first if you may access their data. That is how Oauth2 works.
If you are accessing your own data then you can use something called a Service account. Service accounts are pre authorized. You can take the service account and grant it access to your google calendar, you could give it access to a folder in Google drive. Then you can authenticate using the service account. Service accounts are like dummy users.
My article about service accounts: Google Developer service account
I'm new to web api and I seem to be having an issue with getting the name of the signed in user inside of my post method. Im using
RequestContext.Principal.Identity.Name
However, this only seems to be returning an empty string. It works fine in my get method, but not in the post. Here's my entire method
[Route("receive")]
[HttpPost]
public HttpResponseMessage Receive(PostmarkInboundMessage message)
{
if (message != null)
{
// To access message data
var headers = message.Headers ?? new List<Header>();
// To access Attachments
if (message.Attachments != null)
{
var attachments = message.Attachments;
var c = new CVService();
var user = string.IsNullOrEmpty(RequestContext.Principal.Identity.Name) ? "unknown" : RequestContext.Principal.Identity.Name;
c.UpdateLog(user);
foreach (var attachment in attachments)
{
// Access normal members, etc
var attachmentName = attachment.Name;
// To access file data and save to c:\temp\
//if (Convert.ToInt32(attachment.ContentLength) > 0)
//{
// byte[] filebytes = Convert.FromBase64String(attachment.Content);
// var fs = new FileStream(attachmentSaveFolder + attachment.Name,
// FileMode.CreateNew,
// FileAccess.Write,
// FileShare.None);
// fs.Write(filebytes, 0, filebytes.Length);
// fs.Close();
//}
}
}
// If we succesfully received a hook, let the call know
return new HttpResponseMessage(HttpStatusCode.Created); // 201 Created
}
else
{
// If our message was null, we throw an exception
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Error parsing Inbound Message.") });
}
}
Any help will be greatly appreciated.
Be sure you send the header (token) in both methods GET and POST and also, set the [Authorize] filter in both methods or the controller itself so you will be rejected if the token is not being send
Hi my application has two types of login's one is facebook and other is normal log in. To differentiate between them and bring the values accordingly i have used cookies and clearing those in logout event like this.
But when i login through email and password and then logout and again log in through Fb the UserCookie cookie is still persisting and its entering to the first if statement again
public ActionResult Logout(string returnUrl = "/")
{
try
{
FormsAuthentication.SignOut();
}
finally
{
if (Request.Cookies["UserCookie"] != null)
{
Request.Cookies["UserCookie"].Expires = DateTime.Now;
Request.Cookies["UserCookie"].Value = "";
}
if (Request.Cookies["fbUserUserID"] != null)
{
Request.Cookies["fbUserUserID"].Expires = DateTime.Now;
Request.Cookies["fbUserUserID"].Value = "";
}
if (Request.Cookies["fbFirstName"] != null)
{
Request.Cookies["fbFirstName"].Expires = DateTime.Now;
Request.Cookies["fbFirstName"].Value = "";
}
FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
}
//return Redirect(returnUrl);
return View();
}
and in my view i am checking for cookies like this
#if (HttpContext.Current.Request.Cookies["UserCookie"] != null && HttpContext.Current.Request.Cookies["UserCookie"].Value != "")
{
}
else if (HttpContext.Current.Request.Cookies["fbFirstName"] != null && HttpContext.Current.Request.Cookies["fbFirstName"].Value != "")
{
}
but its not clearing i guess its showing empty string "" for the cookie value in the controller but i donno whats happening in view.
is there any thing that i am missing?
Request.Cookies is used to read the cookies that have come to the server from the client. If you want to set cookies, you need to use Response.Cookies so the server sends the cookie information the server response.
Try modifying your code to use Response.Cookies instead of Request.Cookies when you are trying to unset the cookies.
I am currently using Xamarin.Auth on a iOS project to handle some user authentication via Facebook and Twitter in my application. The Facebook authentication using OAuth2Authenticator works great and my implementation was based mainly off the docs (http://components.xamarin.com/gettingstarted/xamarin.auth). Twitter however still uses OAuth1 it seems and thus I based my implementation mainly off the answer in this StackOverflow questions (https://stackoverflow.com/a/21982205). Everything works properly and I am able to retrieve user, tweets, etc. but after all the code executes I receive a "Authentication Error" popup on the screen saying "Object reference not set to an instance of an object." there is nothing printed to the console however as is the case with most normal errors I have seen thus far. I can dismiss the popup and everything continues to preform correctly. I believe I have narrowed the problem down to something within the OAuth1Authenticator request as I still receive the error when all of the other handling code has been commented out. Please reference the code below to see what might be the cause of this.
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
signupBtn.TouchUpInside += delegate {
LoginToTwitter(true, this);
};
}
void LoginToTwitter(bool allowCancel, UIViewController _vc)
{
var auth = new OAuth1Authenticator (
consumerKey: "My Consumer Key",
consumerSecret: "My Consumer Secret",
requestTokenUrl: new Uri("https://api.twitter.com/oauth/request_token"),
authorizeUrl: new Uri("https://api.twitter.com/oauth/authorize"),
accessTokenUrl: new Uri("https://api.twitter.com/oauth/access_token"),
callbackUrl: new Uri("My callback url"),
getUsernameAsync: (IDictionary<string, string> accountProperties) => {
string screen_name = "";
if (accountProperties.TryGetValue("screen_name", out screen_name)) {
Console.WriteLine("SN: {0}", screen_name);
Account a = new Account(screen_name, accountProperties);
AuthenticatorCompletedEventArgs e = new AuthenticatorCompletedEventArgs(a);
TwitterCompleted(e, _vc);
}
return null;}
);
auth.AllowCancel = allowCancel;
UIViewController authView = auth.GetUI ();
_vc.PresentViewController (authView, true, null);
}
void TwitterCompleted (AuthenticatorCompletedEventArgs e, UIViewController _vc)
{
var theAccount = e.Account;
var theProperties = theAccount.Properties;
foreach (var item in theProperties) {
Console.WriteLine (item); //debugging
}
InvokeOnMainThread (delegate {
_vc.DismissViewController (true, null);
});
AccountStore.Create ().Save (e.Account, "Twitter");
if (!e.IsAuthenticated) {
Console.WriteLine("Not authorized");
return;
}
theScreenName = e.Account.Properties["screen_name"];
theCount = "2";
IDictionary<string, string> theDict = new Dictionary<string, string>();;
theDict.Add("screen_name", theScreenName);
theDict.Add("count", theCount);
var request = new OAuth1Request("GET", new Uri("https://api.twitter.com/1.1/statuses/user_timeline.json"), theDict, e.Account, false);
request.GetResponseAsync().ContinueWith (t => {
if (t.IsFaulted)
Console.WriteLine("Error: {0}", t.Exception.InnerException.Message);
else if (t.IsCanceled)
Console.WriteLine("Canceled");
else
{
var obj = JsonValue.Parse (t.Result.GetResponseText());
Console.WriteLine("object: {0}", obj); // debugging
}
}, uiScheduler);
return;
}
private readonly TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
instead of returning null in "getUsernameAsync" return Task