Google Gmail API - Auth - asp.net

I already have code which works fine, but for security reason I want to make other way of Auth.
In this case, user writes his username and password, but I want to make like "Allow demo.com to access your information's" click button.
How to change this code:
//Provide Login Information
Google.GData.Client.RequestSettings rsLoginInfo = new Google.GData.Client
.RequestSettings("", txtEmail.Text, txtPassword.Text);
rsLoginInfo.AutoPaging = true;
// Fetch contacts and dislay them in ListBox
Google.Contacts.ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);
Google.GData.Client.Feed<Google.Contacts.Contact> feedContacts = cRequest
.GetContacts();
foreach (Google.Contacts.Contact gmailAddresses in feedContacts.Entries) {
Console.WriteLine("\t" + gmailAddresses.Title);
lstContacts.Items.Add(gmailAddresses.Title);
foreach (EMail emailId in gmailAddresses.Emails) {
Console.WriteLine("\t" + emailId.Address);
lstContacts.Items.Add(" " + emailId.Address);
}
}

It seems like you're trying to do 3-Legged OAuth. .NET samples for performing 3-Legged OAuth 1.0a are documented here:
http://code.google.com/apis/gdata/docs/auth/oauth.html#Examples

Related

User Authentication in ASP.NET when authentication is checked by javascript functions

Please suggest or change some suitlable title for this question as i am not able to find one
I am using Facebook to allow the users to authenticate to my site.
I use Facebook Login Button and somehow i find out the user is authenticated or not.
I am developing my website in ASP.NET 4.0
I check whether the user is authenticate through Javascript.
The problem is how should i tell my server that this user is authenticated and assign some ASP.NET roles. I cannot use Ajax becuase of securoty reasons and might be a attack of Impersonation. This site may have transactions in the future so it need to be less security vunerable.
RIght now what i did is create a session using javascript and redirect to some other page and then assign roles but i am not statisfied with this method
Any help is appreciated.
The easiest way would be to use Page methods and Page methods call your service on server or authenticate directly.
http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm
To fix this, after facebook successfully authenticate the user i postback the website with the some arguments.
FB.api('/me', function (response) {
res_id = (response.id);
__doPostBack('SetSessionVariable', res_id + "$" + response.first_name + "$"+ response.last_name);
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
});
And in code i do :
string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
if (eventTarget == "SetSessionVariable")
{
// Authenticate User
}

Graph api, C# to share data from app to my wall

i am trying to develop an app which can allow me to share data on Facebook wall.
For eg: consider the Facebook Canvasapp "Run with Friends". This is a canvas app using Python and Php.
https://developers.facebook.com/docs/samples/. I will be able to share data from this app to my wall./me
Before doing this v need a access token. I was able to get the authorization, accesstoken using Graph api, Oauth2.0, C#, asp.net
public string AuthorizationLinkGet(bool bUserInfo, bool bFriends, bool bfeed, bool bPhotos, bool bEvents, bool bMessages)
{
string url = string.Format("{0}?client_id={1}&redirect_uri={2}", AUTHORIZE, this.ConsumerKey, CALLBACK_URL);
if (bUserInfo == true || bFriends == true || bfeed == true || bEvents == true || bPhotos == true || bMessages == true)
{
url += "&scope=email";
if (bUserInfo == true)
{
url += ",user_about_me,user_interests,user_likes,user_location,user_notes,user_education_history,user_hometown";
}
if (bFriends == true)
{
url += ",read_friendlists,user_groups";
}
if (bfeed == true)
{
url += ",read_stream";
}
if (bEvents == true)
{
url += ",user_events";
}
if (bEvents == true)
{
url += ",user_photo_video_tags";
}
if (bMessages == true)
{
url += ",read_mailbox";
}
}
return url;
}
<add key="APIKey" value="*************************"/>
<add key="Secret" value="**********************"/>
So now how do I be able to share data from the app onto my FB wall.
I've tried Sharekit but look like Sharekit is for mobile apps.
public void AccessTokenGet(string authToken)
{
this.Token = authToken;
string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}",
ACCESS_TOKEN, this.ConsumerKey, CALLBACK_URL, this.ConsumerSecret, authToken);
string response = WebRequest(Method.GET, accessTokenUrl, String.Empty);
if (response.Length > 0)
{
//Store the returned access_token
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["access_token"] != null)
{
this.Token = qs["access_token"];
}
}
}
does any one know how to develop this canvas app in C# using Graph Api
I have no idea abt all the curls and things in Php
Also, I see people using REST, facebookservice, facebook SDK. Where would these fit it?
Thanks
Sun
Ask for the publish stream permission.
You need to POST to https://graph.facebook.com/USER_ID/feed/access_token=lerolero, posting a json like this:
{"name": "name"
"link": "http://www.link.com/",
"caption": "title",
"description": "description",
"picture": "http://www.link.com/image.jpg"}
http://developers.facebook.com/docs/reference/api/, read the publishing section, you can send a lot of other information.
Edit:
I see two possibilities.
If the facebook integration its not part of your bussiness rules (if you will not use the user information), you can just add the SHARE widget, in this case, the user will se a button, and when he click the button, the facebook authentication page will open, and when the authentication is done, the share widget will popup automatically.
If you gonna access the user information (if will be somehow attached to the user account), then, when the user clicks the button, you have to check the user account forward a facebook account, if theres not one, you have to open a authentication popup, if the user succeeds to login into facebook, the authentication popup will return you a verification code. You must exchange the verication code for a access token and attach the access token to the user account in your database. In the authentication step, you have to ask for two special permissions, the stream publish permission and the offline access permission. The first one is about the resource to publish in the user wall, and the second one its about the access token life cycle (if you dont ask for this permission, the access token will have a short life cycle, and you will need to reauthenticate the user into facebook again and again, we dont want that).
Into the code:
When the user clicks a button, call a ajax function that checks if there's a access token in the user account. If theres, return the access token (take care here, if you create a ajax that return a access tokem based on a user id, you will have a very bad security issue), if theres not, return false.
If the code returned is false, call a function that opens a popup with the facebook authentication url. In the facebook authentication popup callback url, just exchange the verification code for a access token and store it in the database. You need to keep listening the popup.closed state, to know when the process is done and call another ajax function that checks if now theres a access token in the user account or not, if not, the user just closed the popup.
If the code returned is an access token, call a ajax function that post in the user wall, its very easy, like this:
string facebookurl = "https://graph.facebook.com/me/feed?access_token=32423"
string parameters = "message=aaaa&link=bbbb";
WebRequest req = WebRequest.Create(facebookurl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
req.ContentLength = bytes.Length;
Stream stream = req.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
WebResponse res = req.GetResponse();
StreamReader streamReader = new StreamReader(res.GetResponseStream());
If you need any other piece of code, let me know.

Active Directory Authentication

I am have made one web application in asp.net.In my project Authentication was done by matching the username and password in database.But now client ask me for the auto login in application with the help Of Active Directory authentication. Client ask suggest me to use the Email Id of user in AD for the authentication.
I tried to fetch the records in the AD, I could fetch the Fullname of user but I couldn't get the Email id,
I tried the code:
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string[] a = Context.User.Identity.Name.Split('\\');
System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
string Name = ADEntry.Properties["FullName"].Value.ToString();
Further more I Use DirectorySearcher but it genterates Error that Coulnot search the record in the client server..
I had the exact same situation while making a portal for a company.
If they dont want you to get into their AD then what you can do is to request for the NTLogins of the people who will be given access to the portal. make a simple table which have their NTLogin and simply authenticate using the system from which the portal is being accessed.
Check out the sample code i used.
// Checking if the user opening this page is listed in the allowed user list against their NT login.
String sUser = Request.ServerVariables["LOGON_USER"].ToLower();
sUser = sUser.Replace("wt\\", "");
//Authentication using a custom auth method.
DatabaseOperations authenticateUser = new DatabaseOperations();
if (!authenticateUser.authenticate(sUser))
{
//unauthorized users will be redirected to access denied page.
Server.Transfer("AccessDenied.aspx", true);
}
And making sure that you have authentication mode to windows in your web.config file
<authentication mode="Windows"></authentication>
Hope this helps.
For reading AD data, i use this class. It is setup for our AD, but basically you can just pass in all the "fields" you want to find, in the params.
But you need to know what field holds the email address. Sysinternals made a pretty good tool for browsing AD, to figure out what you are looking for, called ADExplorer.
But I don't understand why you need to look in the AD? Can you not assume that the user is already authenticated, if they are on the network, and then rely on the windows identity?
public static Hashtable GetAttributes(string initials, params string[] Attribute)
{
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://ADNAME");
DirectorySearcher ADSearcher = new DirectorySearcher(directoryEntry);
ADSearcher.Filter = "(sAMAccountName=" + initials + ")";
foreach (string para in Attribute)
{
ADSearcher.PropertiesToLoad.Add(para);
}
SearchResult adSearchResult = ADSearcher.FindOne();
Hashtable hshReturns = new Hashtable();
foreach (string para in Attribute)
{
string strReturn = "";
if (adSearchResult.Properties[para].Count == 0)
strReturn = "";
else
strReturn = ((ResultPropertyValueCollection)adSearchResult.Properties[para])[0].ToString();
hshReturns.Add(para, strReturn);
}
return hshReturns;
}

Facebook Connect and ASP.NET

I'm at step 8 of the authentication overview found here: http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works
In particular, the user has logged into facebook via Facebook Connect and their web session has been created. How do I use the facebook developer toolkit v2.0 (from clarity) to retrieve information about the user. For example, I'd like to get the user's first name and last name.
Examples in the documentation are geared towards facebook applications, which this is not.
Update
Facebook recently released the Graph API. Unless you are maintaining an application that is using Facebook Connect, you should check out the latest API: http://developers.facebook.com/docs/
I had a lot of trouble figuring out how to make server side calls once a user logged in with Facebook Connect. The key is that the Facebook Connect javascript sets cookies on the client once there's a successful login. You use the values of these cookies to perform API calls on the server.
The confusing part was looking at the PHP sample they released. Their server side API automatically takes care of reading these cookie values and setting up an API object that's ready to make requests on behalf of the logged in user.
Here's an example using the Facebook Toolkit on the server after the user has logged in with Facebook Connect.
Server code:
API api = new API();
api.ApplicationKey = Utility.ApiKey();
api.SessionKey = Utility.SessionKey();
api.Secret = Utility.SecretKey();
api.uid = Utility.GetUserID();
facebook.Schema.user user = api.users.getInfo();
string fullName = user.first_name + " " + user.last_name;
foreach (facebook.Schema.user friend in api.friends.getUserObjects())
{
// do something with the friend
}
Utility.cs
public static class Utility
{
public static string ApiKey()
{
return ConfigurationManager.AppSettings["Facebook.API_Key"];
}
public static string SecretKey()
{
return ConfigurationManager.AppSettings["Facebook.Secret_Key"];
}
public static string SessionKey()
{
return GetFacebookCookie("session_key");
}
public static int GetUserID()
{
return int.Parse(GetFacebookCookie("user"));
}
private static string GetFacebookCookie(string name)
{
if (HttpContext.Current == null)
throw new ApplicationException("HttpContext cannot be null.");
string fullName = ApiKey() + "_" + name;
if (HttpContext.Current.Request.Cookies[fullName] == null)
throw new ApplicationException("Could not find facebook cookie named " + fullName);
return HttpContext.Current.Request.Cookies[fullName].Value;
}
}
I followed up on this concept and wrote a full fledged article that solves this problem in ASP.NET. Please see the following.
How to Retrieve User Data from Facebook Connect in ASP.NET - Devtacular
Thanks to Calebt for a good start on that helper class.
Enjoy.
Facebook Connect actually isn't too difficult, there's just a lack of documentation.
Put the necessary javascript from here: http://tinyurl.com/5527og
Validate the cookies match the signature provided by facebook to prevent hacking, see: http://tinyurl.com/57ry3s for an explanation on how to get started
Create an api object (Facebook.API.FacebookAPI)
On the api object, set the application key and secret Facebook provides you when you create your app.
Set api.SessionKey and api.UserId from the cookies created for you from facebook connect.
Once that is done, you can start making calls to facebook:
Facebook.Entity.User user = api.GetUserInfo(); //will get you started with the authenticated person
This is missing from the answers listed so far:
After login is successful, Facebook recommends that you validate the cookies are in fact legit and placed on the client machine by them.
Here is two methods that can be used together to solve this. You might want to add the IsValidFacebookSignature method to calebt's Utility class. Notice I have changed his GetFacebookCookie method slightly as well.
private bool IsValidFacebookSignature()
{
//keys must remain in alphabetical order
string[] keyArray = { "expires", "session_key", "ss", "user" };
string signature = "";
foreach (string key in keyArray)
signature += string.Format("{0}={1}", key, GetFacebookCookie(key));
signature += SecretKey; //your secret key issued by FB
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(signature.Trim()));
StringBuilder sb = new StringBuilder();
foreach (byte hashByte in hash)
sb.Append(hashByte.ToString("x2", CultureInfo.InvariantCulture));
return (GetFacebookCookie("") == sb.ToString());
}
private string GetFacebookCookie(string cookieName)
{
//APIKey issued by FB
string fullCookie = string.IsNullOrEmpty(cookieName) ? ApiKey : ApiKey + "_" + cookieName;
return Request.Cookies[fullCookie].Value;
}
The SecretKey and ApiKey are values provided to you by Facebook. In this case these values need to be set, preferably coming from the .config file.
I followed up from Bill's great article, and made this little component. It takes care of identifying and validating the user from the Facebook Connect cookies.
Facebook Connect Authentication for ASP.NET
I hope that helps somebody!
Cheers,
Adam
You may also use SocialAuth.NET
It provides authentication, profiles and contacts with facebook, google, MSN and Yahoo with little development effort.
My two cents: a very simple project utilizing the "login with Facebook" feature - facebooklogin.codeplex.com
Not a library, but shows how it all works.

Using Custom MembershipProvider without a Login control in ASP.NET

We have got a custom MembershipProvider in ASP.NET. Now there are 2 possible scenario the user can be validated:
User login via login.aspx page by entering his username/password. I have used Login control and linked it with the MyMembershipProvider. This is working perfectly fine.
An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in MembershipProvider.Validate(string authenticationToken), which is actually validating the user. In this case we cannot use the Login control. Now how can I use the same MembershipProvider to validate the user without actually using the Login control? I tried to call Validate manually, but this is not signing the user in.
Here is the code snippet I am using
if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) {
string ticket = Request.QueryString["authenticationToken"];
MyMembershipProvider provider = Membership.Provider as MyMembershipProvider;
if (provider != null) {
if (provider.ValidateUser(ticket))
// Login Success
else
// Login Fail
}
}
After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx
EDIT: It is FormsAuthentication.SetAuthCookie:
http://msdn.microsoft.com/en-us/library/twk5762b.aspx
Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx
link text
You can set your own FormsAuthenticationTicket if the validation is successful.
Something like this;
if (provider != null) {
if (provider.ValidateUser(ticket)) {
// Login Success
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1, //version
someUserName, //name
DateTime.Now, //issue date
DateTime.Now.AddMinutes(lengthOfSession), //expiration
false, // persistence of login
FormsAuthentication.FormsCookiePath
);
//encrypt the ticket
string hash = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
Response.Cookies.Add(cookie);
Response.Redirect(url where you want the user to land);
} else {
// Login Fail
}
}
You are right in the case of storing the auth information as a cookie directly. But using a strong hash function (e.g. MD5 + SHA1) is great and secure.
By the way, if you use sessions (which is also just a hash cookie) you could attach auth information to it.

Resources