Open ID with Google and dotnetopenauth - Passing query string - c#

I have some code that uses Google Apps as an Open ID provider to authenticate to my web application that is based on the example https://developers.google.com/google-apps/marketplace/tutorial_dotnet.
It all works as expected. However, when redirected to the Google Login screen, the 'Stay Signed In' checkbox is selected by default. I have found that if I manually add &rm=false to then end of the URL, the checkbox is unselected, which I believe is a more secure default option.
My question is, how can I pass &rm=false in my code. I've looked at AddCallbackArguments but this doesn't seem to be the way to do it.
Code is
private static readonly HostMetaDiscoveryService GoogleAppsDiscovery = new HostMetaDiscoveryService
{
UseGoogleHostedHostMeta = true,
};
private static readonly OpenIdRelyingParty relyingParty;
static login()
{
relyingParty = new OpenIdRelyingParty();
relyingParty.DiscoveryServices.Clear();
relyingParty.DiscoveryServices.Insert(0, GoogleAppsDiscovery);
}
protected void buLogin_Click(object sender, EventArgs e)
{
IAuthenticationRequest request = relyingParty.CreateRequest("mydomain");
request.RedirectToProvider();
}

Related

Call a web service method dynamically from client app

I am testing a client application with a web reference to a web service; the web reference is called "PrinterStatus".
In this application I populate a dropdown list with list of available method names. I want to call the method user has selected and not sure how to set it up.
private void PopulateDropdown()
{
// web service URL
string url = "http://1.2.3.4/PS_WS/PrinterStatus.asmx?WSDL";
WebServiceInfo webServiceInfo = WebServiceInfo.OpenWsdl(new Uri(url));
foreach (WebMethodInfo method in webServiceInfo.WebMethods)
{
ListItem li = new ListItem(method.Name);
ddlMethods.Items.Add(li);
}
}
This populates the drop down list with list of available methods (the code for "WebServiceInfo" is at this link).
When user clicks "Submit", I want to be able to call:
PrinterStatus ps = new PrinterStatus();
string sResp = ps.<method_name_user_selected>();
Update
Following Xerillio's recommendation, I made the following changes to get this to work. In my test client app I have a dropdown populated with available method names (ddlMethods) and two textboxes for IP address and port number of printer whose status I am interested in (tbIP and tbPort) and a "submit" button. I have removed all validation stuff.
Also, the web reference created in client app is named "PrinterStatus". The methods in web service return a JSON object.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string sMethodName = ddlMethods.SelectedValue;
string sIPAddress = tbIP.Text.Trim();
string sPort = tbPort.Text.Trim();
int iPort = int.Parse(sPort);
PrinterStatus ps = new PrinterStatus();
Type thisType = ps.GetType();
MethodInfo theMethod = thisType.GetMethod(sMethodName);
string sResp = theMethod.Invoke(ps, new object[] {sIPAddress, iPort}) as string;
Response resp = JsonConvert.DeserializeObject<Response>(sResp);

SetAttribute for value isnt working correctly

I've been trying to get SetAttribute with the webBrowser.Document for a while, and for some reason the webBrowser fields don't get filled in.
I'm certain that I have the ID's correct, but perhaps i'm just overlooking something. I am setting textfields for the netflix login website.
My code is as follows:
var emailField = webBrowser1.Document.GetElementById("email");
var passField = webBrowser1.Document.GetElementById("password");
emailField.SetAttribute("value", username);
passField.SetAttribute("value", password);
Thanks for any help, the username is a string which includes the email, and password contains the password, also in a string.
You should put your code in DocumentCompleted.
Example
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var emailField = webBrowser1.Document.GetElementById("email");
var passField = webBrowser1.Document.GetElementById("password");
emailField.SetAttribute("value", "123");
passField.SetAttribute("value", "456");
}
Try it again.

Problems using captured access token to retrieve user's facebook information

I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx

Creating Facebook Application in asp.net

I want to create a Facebook IFRAME applicaton with asp.net. I just want to know should I need to host the application some where over internet? If yes, how could I test my application on localhost?
Update:
I just want a simple app for displaying a user name with "Hello." Can anyone show me the code for that with the complete web.config configuration?
I'm trying this code
using facebook.web;
namespace TestFbApplication
{
public partial class _Default:facebook.web.CanvasFBMLBasePage
{
facebook.Components.FacebookService _fbService = new facebook.Components.FacebookService();
private const string FACEBOOK_APPKEY = "66a8278bb94d969247a80815bab686e5"; // From the Facebook application page
private const string FACEBOOK_SECRET = "de76280e4ddaef72ac2166afe7ffb9d5"; // From the Facebook application page
protected void Page_PreInit(object sender, EventArgs e)
{
base.RequireLogin = false;
_fbService.IsDesktopApplication = false;
_fbService.ApplicationKey = FACEBOOK_APPKEY;
_fbService.Secret = FACEBOOK_SECRET;
_fbService.IsDesktopApplication = false;
_fbService.ConnectToFacebook();
abc.InnerText = _fbService.users.getInfo().ToString();
}
and it is throwing and Exception in the last line that that the object reference is not set.
You will need to host your production application somewhere, but you can test locally. If you set your Canvas URL to http://localhost:81 in Facebook, this should work. It did for me a couple of months ago, but they may have changed it since then.
this might be an interesting for you:
http://www.stevetrefethen.com/blog/DevelopingFacebookapplicationsinCwithASPNET.aspx

Sign in as different user when using Integrated Windows Authentication

I have restricted access to a site by using Integrated Windows Authentication and turning off anonymous access. This way I can then show them their real name (from looking up on Active Directory and using the server variable LOGON_USER) and do other related Active Directory tasks.
How can I then prompt again for their user credentials, through a 'sign in as other user' link , showing the browser prompt (like you would get on a browser like Chrome or Firefox, or if the site was not in the 'Intranet' zone in IE) rather than a Web Form?
Since SharePoint offers this functionality, I assume there is a way to do this through code, but I don't know what code can do this (using C#). I can send a 401 header which makes the prompt appear, but how do you then confirm if they are logged in?
Maybe this can help you out.
ASP .NET – C# – How to “Sign in as Different User” like in Microsoft SharePoint with Windows Authentication
Try this approach. It is based on disassembled code of the method Microsoft.SharePoint.ApplicationPages.AccessDeniedPage.LogInAsAnotherUser()
First of all, I'm accessing the AccessDeniedPage page using javascript because Sharepoint does something similar:
function GoToSignAs() {
window.location.replace("./SignAs.aspx?signAs=true&returnUrl=" + window.location.toString());
}
<a onclick="GoToSignAs(); return false;" href="javascript:;">SignAs</a>
Then, in your page AccessDeniedPage you use this:
public partial class SignAs : Page
{
private const string LoginAttempts = "LoginAttempts";
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
HttpContext current = HttpContext.Current;
if (current == null)
{
throw new InvalidOperationException();
}
if (GetUrlParameter<bool>("signAs"))
{
HandleSignAs(current, GetUrlParameter<string>("returnUrl"));
}
}
// ...
private static void HandleSignAs(HttpContext context, string returnUrl)
{
int attempts = 0;
HttpCookie attemptsCookie = context.Request.Cookies[LoginAttempts];
if (attemptsCookie == null || string.IsNullOrEmpty(attemptsCookie.Value))
{
attemptsCookie = new HttpCookie(LoginAttempts);
}
else
{
attempts = int.Parse(attemptsCookie.Value, CultureInfo.InvariantCulture);
}
if (!string.IsNullOrEmpty(context.Request.Headers["Authorization"]))
{
// Attempts are counted only if an authorization token is informed.
attempts++;
}
if (attempts>1)
{
attemptsCookie.Value = string.Empty;
context.Response.Cookies.Add(attemptsCookie);
context.Response.Redirect(returnUrl, true);
}
else
{
attemptsCookie.Value = attempts.ToString(CultureInfo.InvariantCulture);
context.Response.Cookies.Add(attemptsCookie);
SendEndResponse(context, 401, "401 Unauthorized");
}
}
private static void SendEndResponse(HttpContext context, int code, string description)
{
HttpResponse response = context.Response;
context.Items["ResponseEnded"] = true;
context.ClearError();
response.StatusCode = code;
response.Clear();
response.StatusDescription = description;
response.AppendHeader("Connection", "close");
response.AddHeader("WWW-Authenticate", "Negotiate");
response.AddHeader("WWW-Authenticate", "NTLM");
response.End();
}
}
FIX: you must use the IIS to work properly

Categories