I'm using facebook to authenticate users at my website. I need to delete facebook cookie on logout from serverside with C#. could you please show me how to do it? tested and working example
Assuming you know the name of the cookie, you can set it's expiry date to some time in the past. When the browser receives the cookie, it will see that it's expired and delete it.
If you're using a System.Web.HttpCookieCollection, this MSDN article has example code which demonstrates this (example adapted from that on MSDN):
if (Request.Cookies["NameOfFacebookCookie"] != null) {
HttpCookie myCookie = new HttpCookie("NameOfFacebookCookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Since you're authenticating users through Facebook, I'm assuming you're using OAuth. In this case, you don't know the name of the cookie, and in any case it isn't your cookie, it's set by facebook.com during the login process. To log off a user who's signed in via Facebook, see this answer.
I don't understand why I can't "comment" when, but whatever; to add to the discussion between Alexei and Cameron above, the assumption there is that the cookie is controlled by Facebook. If you used the Javascript SDK, then yes, Cameron's comment is true. However, if instead you created a manual login flow (no SDK) so that you could server-side handle the login, then you likely created your own cookie to save the retrieved access_token, and of course, you could delete that.
Related
We have a straight forward ASP.NET web application with a login page. After the user enters credentials and submits the form, the server processes the details and if successful, Response.Redirect()'s the user to the Main Menu page. (We also have a navigation bar where the user can navigate to other pages via similar response.redirects)
One of our customers is setting up an IBM Data Power Web Application Firewall, and has told us this Redirect after a POST is an RFC violation and consequently the application does not work.
There are a few questions here that are related to Get/Post/Redirect, and they indicate that its up to the discretion of the browser to use the 302 response as a get or a post. I have also found other links on the public internet that lead me to believe this something the IBM device could be configured to handle.
Before I suggest changing the IBM device configuration, are there any configuration based (or simple code) ways to make a trivial login page (not using the asp.net login control) work where a GET request can send the login credentials, or make all postbacks in the site use a GET instead of POST?
Also, if anyone has tips for working with this IBM device, they would be appreciated.
An example of the code...
var userName = txtUserName.Text.Trim();
var password = txtPassword.Text.Trim();
var authResult = GetAuthService().AuthenticateUser(userName, password);
if (authResult == true)
{
//set forms auth cookie
Response.Redirect("Menu.aspx", false);
}
else
{
lblError.Text = "Unable to login";
}
A POST followed by a redirect is a usual mechanism found in many implementation. For example, consider using JAAS authentication. You present a form to a user and it is posted on '*/j_security_check' URL. Once authenticated you are redirected to a resource page, else you are re-directed to an error page.
I am not sure what is configured on datapower, but if your developer is using MPGW construct for this, then he can try playing around with two properties found in 'Advanced' tab of it. One is 'follow redirects' and another one is allow 'empty request'.
May be this helps you.
I have an asp.net web form. when a user authenticate, it create a Secured cookie called .aspxauth
uppon logout, I call these 2 methods
FormsAuthentication.SignOut();
Session.Abandon()
Problem is that we had penetration test and if I steal the cookie, logout and manually reinsert the cookie, I become loggued in again. So the .aspauth isn't invalidated server side.
I've googled it and I can't find the answer to that security breach.
Microsoft has acknowledged this issue here: https://support.microsoft.com/en-us/kb/900111
They offer several ideas for mitigating this vulnerability:
protect the application by using SSL
Enforce TTL and absolute expiration
Use HttpOnly cookies and forms authentication in ASP.NET 2.0
Use the Membership class in ASP.NET 2.0
Regarding the last one, I'll paste the contents from the site for convenience/preservation:
When you implement forms authentication in ASP.NET 2.0, you have the option of storing user information in a Membership provider. This option is a new feature that is introduced in ASP.NET 2.0. The MembershipUser object contains specific users.
If the user is logged in, you can store this information in the Comment property of the MembershipUser object. If you use this property, you can develop a mechanism to reduce cookie replay issues in ASP.NET 2.0. This mechanism would follow these steps:
You create an HttpModule that hooks the PostAuthenticateRequest event.
If a FormsIdentity object is in the HttpContext.User property, the FormsAuthenticationModule class recognizes the forms authentication ticket as valid.
Then, the custom HttpModule class obtains a reference to the MembershipUser instance that is associated with the authenticated user.
You examine the Comment property to determine whether the user is currently logged in.
Important: You must store information in the Comment property that indicates when the user explicitly signed out. Also, you must clear the information that is in the Comment property when the customer eventually signs in again.
If the user is not currently logged in as indicated by the Comment property, you must take the following actions:
Clear the cookie.
Set the Response.Status property to 401.
Make a call to the Response.End method that will implicitly redirect the request to the logon page.
By using this method, the forms authentication cookie will only be accepted if the user has not been explicitly signed out and the forms authentication ticket has not yet expired.
Read this article about Session fixation and how to get rid of it once and for all:
http://www.dotnetfunda.com/articles/show/1395/how-to-avoid-the-session-fixation-vulnerability-in-aspnet
This remains an issue in .NET Framework. Everyone seems to think Session.Abandon() is the answer, but the sad truth is that command does not invalidate the session on the server's side. Anyone with the right token value can still resurrect a dead session, until the session expires based on the Web.config settings (default = 20minutes).
A similar questioner posed this question a long time ago here:
Session Fixation in ASP.NET
Most of those links are dead, and Microsoft has no new news on the topic.
https://forums.asp.net/t/2154458.aspx?Preventing+Cookie+Replay+Attacks+MS+support+article+is+now+a+dead+link
Worse still, you're still vulnerable to this cookie replay attack even if you're implementing a completely stateless MVC application and don't use the Session object to store data between views. You can even turn off session state in the web.config settings and still replay cookies to gain access to a logged-out session.
The true solution is hack-y and described here, and you need to have session data enabled InProc to use it.
When the user logs in, set a boolean value in the session data, like Session["LoggedIn"] = true;, which is stored on the server side.
When the user logs out, set that value to false.
Check the session value on every request--an attacker trying to replay a session isn't going to be nice to you and come in through the Login page only. It's probably easiest to do this using a custom filter and registering it globally in the global.asax file (so you don't have to duplicate the code everywhere, or attribute every controller/method).
Even if the attacker has all the cookie values, they won't be able to re-use that same session ID, and the server will automatically delete it once it reaches the specified timeout.
if you are using the FormsAuthentication, you can use this code. By using this code you can destroy the created cookies by setting the Expire property of HttpCookie. It will help you:
FormsAuthentication.SignOut();
Session.Clear();
Session.Abandon();
Session.RemoveAll();
// clear authentication cookie
HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
httpCookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(httpCookie);
Here is the story of me creating a web application using ASP.NET 4.5 with EntityFramework. I use ASP.NET control for login and logout functionalities. Now, my issue is that I want to create such application in which I need user to be always logged in to the application after closing the browser or system as a Gmail account.
I tried searching on net but didn't get any proper results. How I can implement this by using session for any browser?
Session is the term derived one instance of the browser, means till the browser gets closed.
To have user session even if browser gets closed, create a cookie.
HttpCookie myCookie = new HttpCookie("cookieUser");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(10);
// Add the cookie.
Response.Cookies.Add(myCookie);
Gmail also works in the same way.
Remember me at this computer explicitly saves the cookie
Hope this helps.
i started to implement my login class from scratch, and have a big problem in security
this is my algorithm for logging page:
if(userName and password == true)
{
creating session from login object
encrypt username
creating cookie from encrypted username
go to private page
}
and on my page_load() private page:
if(session existed)
{
update cookie timeout
}
else
{
if(cookie existed)
{
unencrypte value
if(username existed from unencrypted cookie value)
{
create session
update cookie timeout
}
}
else
{
go to logging pgae
}
}
so my question:
1.does this algorithm has security problem?(because i think every one could save cookie value and created bye own, is that right? )
2.i am using cookie because i had problem for session time out, and want to keep login my user for more than a day. is that a good way?
3. what are some site like facebook do for keep log in their user?
thanks for your attention
1) Yes, everyone can create cookies, but not everyone can encrypt the value you want to set. The encryption is done server side with a private key only you, or your code, should have access to.
2) Cookie can be set to be available only during the browser session of until a specific expiration date, so yes that would be a good option.
3) I would not know for all users, but a cookie is a good option. Sites like live.com and google.com just create cookies with a long expiration date. Keep in mind that you should provide a means to let the user decide this (for instance using a checkbox).
Maybe I'm missing some context by why invent the wheel and not just use ASP.NET Forms Authentication. That will do just what U describe in your algorithm.
You can combine it with the Membership Provider Framework or the new ASP.NET Identity Framework.
I've got credentials of an account with access to Google Analytics,
I'm looking to utilise the Analytics Core Reporting API http://code.google.com/apis/analytics/docs/gdata/home.html
I've found examples which use username/password calling setUserCredentials, but have seen comments this is less secure/has a low request limit (And doesn't exist in the lastest client).
Plus I've seem examples which use oauth, but require user interaction and grant access to the users google account.
However I'm looking to run a service which doesn't require any user interaction, and connects to a predefined google account (un-related to the user viewing it).
I can then store the results in a database, and end users can query the results from the database.
I've seen information about using AccessType = Offline when you first login, which then returns an access token and a refreshtoken.
http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#offline
In my example though, the end user will never login to the application.
Could I have a seperate admin application which gets a refresh token, and stores the refresh token in the config/lookup table?
Then the main application can use the refresh token pulling from the config/lookup table, and get an access token to be able to query the Google Analytics account.
I'm looking for a C# example which uses AccessType = Offline, and seperates out the fetching of the refresh token and using the refresh token to get an access token to query the google analytics account.
Create your app https://code.google.com/apis/console/
For you App, turn on access to Google Analytics, and create an OAuth 2.0 client ID for your website.
Browse to:
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=YOUR_APP_ID.apps.googleusercontent.com&access_type=offline&scope=https://www.googleapis.com/auth/analytics.readonly&redirect_uri=HTTP://YOUR_CALL_BACK_URL
Having changed YOUR_APP_ID, YOUR_CALL_BACK_URL to the relevant values.
Important to include access_type=offline.
Press Grant Access, this will redirect to HTTP://YOUR_CALL_BACK_URL?code=THIS_IS_YOUR_CODE. Copy the code in the URL.
With the code, request the Refresh Token using CMD prompt.
curl -d "code=THIS_IS_YOUR_CODE&client_id=YOUR_APP_ID.apps.googleusercontent.com&client_secret=YOUR_APPS_SECRET_CODE&redirect_uri=HTTP://YOUR_CALL_BACK_URL&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
Having changed THIS_IS_YOUR_CODE, YOUR_APP_ID, YOUR_APPS_SECRET_CODE, YOUR_CALL_BACK_URL to the relevant values.
Record the refresh_token returned.
Download the latest version of the Core Reporting V3.0 .net libraries
http://code.google.com/p/google-api-dotnet-client/wiki/Downloads
There is a bug in the current version of Google.Apis.Analytics.v3.cs, to fix this copy the code in this file to your local solution (And don’t reference Google.Apis.Analytics.v3.bin)
http://code.google.com/p/google-api-dotnet-client/source/browse/Services/Google.Apis.Analytics.v3.cs?repo=samples&name=20111123-1.1.4344-beta
And change the property Dimensions from a List<system.string> to a string.
Or you'll get an error like me and this guy did http://www.evolutiadesign.co.uk/blog/using-the-google-analytics-api-with-c-shar/
You can then use your Refresh Token, to generate you an Access Token without user interaction, and use the Access Token to run a report against Google Analytics.
using System;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using AnalyticsService = Google.Apis.Analytics.v3.AnalyticsService;
class Program
{
public static void Main()
{
var client = new WebServerClient(GoogleAuthenticationServer.Description, "YOUR_APP_ID.apps.googleusercontent.com", "YOUR_APPS_SECRET_CODE");
var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);
var asv = new AnalyticsService(auth);
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
request.Dimensions = "ga:pagePath";
request.Sort = "-ga:visitors";
request.MaxResults = 5;
var report = request.Fetch();
Console.ReadLine();
}
private static IAuthorizationState Authenticate(WebServerClient client)
{
IAuthorizationState state = new AuthorizationState(new string[]{}) { RefreshToken = "REFRESH_TOKEN" };
client.RefreshToken(state);
return state;
}
}
Great Answer Ian and it helped me to get going in the correct Direction more than any other answer I could find online. Something must have changed in the AnalyticsService object because the line:
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
did not work for me and I had to use the following:
var request = asv.Data.Ga.Get("ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID", "2012-01-01", "2012-02-20", "ga:visitors");
Hopefully this will help others like your answer helped me. Thanks!
Ian's answer helped me a lot but I kept getting an error running the curl command. Did some research and found that the steps to get the access code and refresh token can be made easier by going to https://code.google.com/oauthplayground/ and checking your oAuth configuration settings. Top right of the page there is a settings button. selected "Use your own OAuth credentials". You can get your access code and request a refresh token all from here.
Hope this helps.
You can manually get a refresh token from the OAuth Playground.
If you are needing a refresh token for a Service Account as I was, make sure you
Click on the settings on the right.
Check Use your own OAuth credentials
Fill in your Client ID and Secret
Close the settings
Click the Refresh button on step 2
Then save the refresh token for use in your app