How to make a STS using Gmail OAuth - asp.net

We want to make an STS that outsources the authentication to google.
Following the steps stated in https://developers.google.com/accounts/docs/OAuth2Login?hl=es-ES we have the following code in the Login.aspx generated by the sts web site template in vs2010:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
//I'm coming from google, already authenticated
FormsAuthentication.SetAuthCookie(GetUserName(Request.QueryString["code"]), false);
Response.Redirect("default.aspx");
}
else
{
//I want to authenticate
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=988046895016.apps.googleusercontent.com&" +
"redirect_uri=" + HttpUtility.UrlEncode("https://localhost/GmailSTS/login.aspx") + "&" +
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email")
);
}
}
But I get an error beacuse wa is not specified in the QueryString, debugging the samples and the generated template I saw that wa,wtrealm,wctx and wct are the parameters needed so I used the state parameter so they roundtrip and get them back:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
//I'm coming from google, already authenticated
FormsAuthentication.SetAuthCookie("johannsw", false);
String lQueryStrings = HttpUtility.UrlDecode(Request.QueryString["state"]);
lQueryStrings.Replace('?', '&');
Response.Redirect("default.aspx" + "?" + lQueryStrings);
}
else
{
//I want to authenticate
String lState = String.Empty;
foreach (var key in Request.QueryString.AllKeys)
{
if (String.Equals("wa", key) ||
String.Equals("wtrealm", key) ||
String.Equals("wctx", key) ||
String.Equals("wct", key))
lState += key + "=" + Request.QueryString[key] + "&";
}
lState = lState.Remove(lState.Length - 1);
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=988046895016.apps.googleusercontent.com&" +
"redirect_uri=" + HttpUtility.UrlEncode("https://localhost/GmailSTS/login.aspx") + "&" +
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email") + "&" +
"state=" + HttpUtility.UrlEncode(lState)
);
}
}
but now I get an error saying "The HTTP verb POST used to access path '/WebSite1/' is not allowed."
Any hints?
Thanks!

Well finally I made it. Here is how I solved it just in case it helps someone else:
Login.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null && Request.QueryString["error"] != "access_denied")
{
// If I got code and no error then
// ask for access_code so I can get user email
//Here I ask for the access_code.
WebRequest requestLogIn = null;
Stream stream = null;
WebResponse response = null;
StreamReader reader = null;
string sendData = "code=" + Request.QueryString["code"] + "&";
sendData += "client_id=" + ObtenerClientID() + "&";
sendData += "client_secret=" + ObtenerClientSecret() + "&";
sendData += "redirect_uri=" + System.Configuration.ConfigurationManager.AppSettings["urlLogin"] + "&"; //TODO: ver si es necesario
sendData += "grant_type=authorization_code";
requestLogIn = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
requestLogIn.Method = "POST";
requestLogIn.ContentType = "application/x-www-form-urlencoded";
byte[] arrayToSend = Encoding.UTF8.GetBytes(sendData);
requestLogIn.ContentLength = arrayToSend.Length;
stream = requestLogIn.GetRequestStream();
stream.Write(arrayToSend, 0, arrayToSend.Length);
stream.Close();
response = requestLogIn.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
reader = new StreamReader(stream);
string responseValue = reader.ReadToEnd();
reader.Close();
var lJSONResponse = new JavaScriptSerializer().Deserialize<JSONResponseToken>(responseValue);
//Now that I have the access_code ask for the user email so I can match him in my base and load claims.
WebRequest myRequest = WebRequest.Create("https://www.googleapis.com/oauth2/v2/userinfo");
myRequest.Method = "GET";
myRequest.Headers.Add("Authorization", "Bearer " + lJSONResponse.Access_Token);
response = myRequest.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
reader = new StreamReader(stream);
responseValue = reader.ReadToEnd();
var lUserMail = new JavaScriptSerializer().Deserialize<JSONResponseUserMail>(responseValue);
// User is authenticated
FormsAuthentication.SetAuthCookie(lUserMail.Email, false);
// default.aspx will load claims
Response.Redirect("default.aspx?" + Request.QueryString.ToString());
}
}
}
else
{
//redirect to google for login.
//Save original url in a cookie for later use.
Guid lGuid = Guid.NewGuid();
CreateContextCookie(lGuid.ToString(), this.Request.Url.AbsoluteUri);
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=" + ObtenerClientID() + "&" +
//I want to return here again
"redirect_uri=" + HttpUtility.UrlEncode(System.Configuration.ConfigurationManager.AppSettings["urlLogin"]) + "&" +
//Add scope so I can get user mail.
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email") + "&" +
//Reference to the cookie so I can get the original url again
"state=" + HttpUtility.UrlEncode(lGuid.ToString())
);
}
}
Default.aspx.cs:
protected void Page_PreRender(object sender, EventArgs e)
{
String lCode = Request.QueryString["code"];
String lSTate = Request.QueryString["state"];
var ctxCookie = this.Request.Cookies[lSTate];
var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(ctxCookie.Value));
//Erase cookie
var contextCookie = new HttpCookie(lSTate)
{
Expires = DateTime.UtcNow.AddDays(-1)
};
//process login request
SecurityTokenService sts =
new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
SignInResponseMessage responseMessage =
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response);
this.Response.Cookies.Add(contextCookie);
}

Related

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

Sending Push SMS from an Asp.net Application

PLease let me know a method on, How I can send a Push SMS to mobile numbers from asp.net application. Thanks in Advance.
Try out this code,
protected void Page_Load(object sender, EventArgs e)
{
textboxRecipient.Width = 400;
textboxMessage.Width = 450;
textboxMessage.Rows = 10;
textboxError.Width = 400;
textboxError.Rows = 5;
textboxError.ForeColor = System.Drawing.Color.Red;
textboxError.Visible = false;
textboxError.Text = "";
if (!Page.IsPostBack)
{
textboxRecipient.Text = "+7588451632";
textboxMessage.Text = "Hello World!";
}
}
protected void buttonSendOnClick(object sender, EventArgs e)
{
//are required fields filled in:
if (textboxRecipient.Text == "")
{
textboxError.Text += "Recipient(s) field must not be empty!\n";
textboxError.Visible = true;
return;
}
//we creating the necessary URL string:
string ozSURL = "http://127.0.0.1"; //where Ozeki NG SMS Gateway is running
string ozSPort = "9501"; //port number where Ozeki NG SMS Gateway is listening
string ozUser = HttpUtility.UrlEncode("admin"); //username for successful login
string ozPassw = HttpUtility.UrlEncode("abc123"); //user's password
string ozMessageType = "SMS:TEXT"; //type of message
string ozRecipients = HttpUtility.UrlEncode(textboxRecipient.Text); //who will get the message
string ozMessageData = HttpUtility.UrlEncode(textboxMessage.Text); //body of message
string createdURL = ozSURL + ":" + ozSPort + "/httpapi" +
"?action=sendMessage" +
"&username=" + ozUser +
"&password=" + ozPassw +
"&messageType=" + ozMessageType +
"&recipient=" + ozRecipients +
"&messageData=" + ozMessageData;
try
{
//Create the request and send data to Ozeki NG SMS Gateway Server by HTTP connection
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(createdURL);
//Get response from Ozeki NG SMS Gateway Server and read the answer
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
//inform the user
textboxError.Text = responseString;
textboxError.Visible = true;
}
catch (Exception)
{
//if sending request or getting response is not successful Ozeki NG SMS Gateway Server may do not run
textboxError.Text = "Ozeki NG SMS Gateway Server is not running!";
textboxError.Visible = true;
}
}

here is the code am using... but i want to send the html part as email.

i have converted the aspx page to html and hv stored it in a var myPageHTML . here is the code am using... but i want to send the html part as email as an attachment or as the body of the mail. please help.
//this method on providing the url of the webpage copies the image of that webpage.
protected void Button1_Click(object sender, System.EventArgs e)
{
{
WebClient myClient = new WebClient();
string myPageHTML = null;
byte[] requestHTML;
// Gets the url of the page
string currentPageUrl = Request.Url.ToString();
UTF8Encoding utf8 = new UTF8Encoding();
// by setting currentPageUrl to www.yahoo.com it will fetch the source (html)
// of the yahoo.com and put it in the myPageHTML variable.
// currentPageUrl = "http://www.yahoo.com";
requestHTML = myClient.DownloadData("http://localhost:31788");
myPageHTML = utf8.GetString(requestHTML);
Response.Write();
try
{
SendMail();
}
catch (Exception) { }
}
protected void SendMail()
{
var userName = " from email";
var toAddress = YourEmail.Text.ToString();
const string Password = "password";
string subject = YourSubject.Text.ToString();
string body = "From: " + YourName.Text + "\n";
body += "Email: " + YourEmail.Text + "\n";
body += "Subject: " + YourSubject.Text + "\n";
body += "Question: \n" + Comments.Text + "\n";
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "10.238.52.880";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(userName, Password);
smtp.Timeout = 20000;
}
smtp.Send(userName, toAddress, subject, body);
}
}
I believe you should look at below links to have understanding of Mail sending.
http://csharp.net-informations.com/communications/csharp-email-attachment.htm
http://www.codeproject.com/Articles/10828/Sending-Email-with-attachment-in-ASP-NET-using-SMT
You must also check Generate HTML file at runtime and send as email attachment for generating HTML
Happy Coding !!!

http in c# GET a page

this is my for read a web page. in c# lang.
but it got some exceptions when I execute it.
any one know why ?
try
{
string address = "http://" + txtMsg.Text;
int port = int.Parse(textBox1.Text);
System.Net.WebClient webclient = new WebClient();
String content = webclient.DownloadString(address);
Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
skt.Connect(address, port);
string hdrs = "GET " + address + ":" + port + " HTTP/1.1\r\n"
+ "Host: " + address + ":" + port + "\r\n";
byte[] req_as_bytes = Encoding.UTF8.GetBytes(hdrs);
skt.Send(req_as_bytes);
byte[] data = new byte[1024 * 200];
int t = skt.Receive(data);
lstMsg.Items.Add(Encoding.UTF8.GetString(data, 0, t));
skt.Shutdown(SocketShutdown.Both);
skt.Close();
btnConnect.Text = "done";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
OK !
I found the solution:
private void btnConnect_Click(object sender, EventArgs e)
{
var address = "http://" + txtMsg.Text;
var webclient = new System.Net.WebClient();
var content = webclient.DownloadString(address);
//any work
btnConnect.Text = "done";
}

Trying to authorize facebook Canvas app in ASP.net Web Forms

I've had some Page Tab apps working, just basic authorization as I don't need anything except name / id for what I'm doing - but I've tried the same method with the canvas app and it's not working. It seems to be with the redirect back, and I really can't see where I'm going wrong based on facebook's documentation for canvas apps http://developers.facebook.com/docs/appsonfacebook/tutorial/#auth
On loading I show a button, on clicking that it tries to get authorisation but it's not working. I've checked and double checked that I'm using the canvas url as the redirect but all I'm getting is a 404 (which is wrong as the page definitely exists, or else the button wouldn't appear). The URL on the 404 page is what really bemuses me, it's:
http://apps.mydomain.co.uk/myappname/https%3a%2f%2fwww.facebook.com%2fdialog%2foauth%3fclient_id%3d999999999999%26redirect_uri%3dhttp%253a%252f%252fapps.mydomain.co.uk%252fmyappname%252f
It has to be something to do with the redirection - any help would be appreciated.
Here's my code (shortened for clarity, urls changed):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string error = Request.QueryString["error_reason"];
if (String.IsNullOrEmpty(error))
{
if (Request.Form["signed_request"] != null)
{
signedRequest();
}
if (String.IsNullOrEmpty(_auth))
{
intro.Visible = true;
main.Visible = false;
}
else
{
intro.Visible = false;
main.Visible = true;
}
}
else
{
// show intro page
intro.Visible = true;
main.Visible = false;
}
}
}
protected void Authorise_Click(object sender, EventArgs e)
{
// redirect if needs auth
if (String.IsNullOrEmpty(_auth))
{
// get authorisation
string id = "999999999999";
string canvas = Server.UrlEncode("http://apps.mydomain.co.uk/myappname/");
string redir = Server.UrlEncode("https://www.facebook.com/dialog/oauth?client_id="+ id +"&redirect_uri=" + canvas); // test
Response.Write("<script>top.location.href='" + redir + "'</script>");
}
else
{
// already authorised
// go straight to main page
}
}
private void signedRequest()
{
string sreq = Request.Form["signed_request"];
string[] splitPayload = sreq.Split('.');
string sig = splitPayload[0];
string payload = splitPayload[1];
Dictionary<string, string> JSONpayload = DecodePayload(payload);
_auth = JSONpayload["user_id"].ToString();
_code = JSONpayload["oauth_token"].ToString();
if (!String.IsNullOrEmpty(JSONpayload["oauth_token"]))
{
var fb = new FacebookClient(JSONpayload["oauth_token"]);
var result = (IDictionary<string, object>)fb.Get("/me");
_name = (string)result["name"];
//Response.Write("<br /><br />RESULT: " + result);
ViewState["name"] = _name;
Session["name"] = _name;
}
ViewState["id"] = _auth;
Session["id"] = _auth;
}
private Dictionary<string, string> DecodePayload(string payload)
{
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var jObject = JObject.Parse(json);
Response.Write("jObject: " + jObject);
var parameters = new Dictionary<string, string>();
parameters.Add("user_id", (string)jObject["user_id"] ?? "");
parameters.Add("oauth_token", (string)jObject["oauth_token"] ?? "");
var expires = ((long?)jObject["expires"] ?? 0);
parameters.Add("expires", expires > 0 ? expires.ToString() : "");
parameters.Add("profile_id", (string)jObject["profile_id"] ?? "");
if (jObject["page"] != null)
{
var jObjectPage = JObject.Parse(jObject["page"].ToString());
bool isPageLiked = bool.Parse(jObjectPage["liked"].ToString());
parameters.Add("is_Liked", isPageLiked.ToString() ?? "");
}
else
{
_liked = false;
}
return parameters;
}

Resources