This question already has answers here:
Encrypt cookies in ASP.NET
(2 answers)
Closed 9 years ago.
I have a login page with "remember me" option.
If the user wished to save his credentials in system using "remember me" option the details are saved using cookies.
The next time the user visits the site the credentials are taken from cookies as expected.
I noticed that as these values are not encrypted while saving in cookie. So I can use "Inspect element" of chrome for finding the value of password textbox(Taken from cookie)
In any way i can prevent this. Either
Encrypt the values while saving to cookie
Even if user user "Inspect Element" he will not be able to see the value of textbox(Almost Impossible I guess)
Are you using the credentials to log in the user for each request? I think you should reconsider your strategy, to do an authorization once, and then use something like FormsAuthentication which would create an encrypted session cookie which would contain the user identity.
Then you do not need to keep logging in the user, and you wouldn't need to worry about encrypting a standard cookie either (which is a very dangerous approach anyway).
For e.g. your login handling code could do:
string username = // get username;
string password = // get password;
bool rememberMe = // get remember me setting.
if (YourAuthenticationSystem.Authenticate(username, password))
{
FormsAuthentication.SetAuthCookie(username, rememberMe);
}
As you can see, this method has support for a 'remember me' option.
You will need the web.config code:
<authentication mode="Forms">
<forms name="TheNameOfYourAuthCookie" loginUrl="http://yourdomain.com/Login" path="/" domain="" timeout="40320" slidingExpiration="true" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
Read more about FormsAuthentication here: http://msdn.microsoft.com/en-us/library/xdt4thhy(v=vs.100).aspx
To encrypt the message / text like passwords you can use some DSA algorithm, which will work based on Key and some Prime numbers,
other way to encrypt by using the Hash Tables / some inbuilt stored Procedures like Membership in C# uses this encryption which is not possible to hack so easily...
I recommend you not to use cookies to store text like passwords using
encryption. use session variables to start and stop sessions, when
sessions are stared and authenticated the browser itself asks to save
your password.. etc.
The best way any developer usually uses to secure the authentication
using the tool in c# called as Membership. ( which provides all
features like Log-in, Log-Out, User , Remember_Me etc built in
features... by Microsoft c#. Please make use of it.
For More info:
Membership - Log-in Cookies and Sessions Microsoft site
Try setting the value as encrypted text
Response.Cookies['cookieName'].Value = MyEncryptMethod(model.rememberMe);
Related
ASP.NET Web Forms applications.
I checked our company's legacy code, the way they do login is like this:
when user is validated against database with (username, password), they set a session:
Session["authenticated"] = "true";
Every page other than login.aspx is inherited from a class named SecurePage. In SecurePage's OnInit() method, it checks
if (Session["authenticated"] != null)
if true, means authenticated, otherwise means not. So basically the way to do authentication is to see if there is a session named authenticated.
This seems the most crude and intuitive way of doing authentication... I want to ask: is this safe?
Another thing I feel strange is that in the web.config, they have this:
<authentication mode="Windows" />
Shouldn't it be
<authentication mode="Forms" />
since these are web applications? Users credentials are stored in database and these users are outside clients (not internal users).
A slight different version also does this after user is validated against database:
FormsAuthentication.SetAuthCookie( username, true );
what does this do? Besides this statement in login.aspx, I don't see any other pages have any code related to auth cookie. Do we need to set auth cookie by ourselves in code or does .NET framework handle this for us already?
Still another version have the following:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(login, false, 60);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
what does this do? Do we need to set this cookie by ourselves in code? or does .NET framework handle this for us already?
These web appliations were developed a long time ago, though I am not sure when. I suspect it is .NET 1.0 era? From my understanding since .NET 2.0,
it has this ASP.NET membership thing, and we can just use <authentication> and <authorization> tags in web.config (and subfolder web.config) to achieve the goal of authentication and authorization. Isn't it? Can anyone give me a history of ASP.NET framework authentiation mechanism? (membership -> simple memebership -> Identity?)
<authentication mode="Windows" />
Above should be used mostly in intranet website, because it's like saying use the computer(windows pc) authentication to access the resource. However, this will never work, since inherited class has a method to validate session key value for a login.
You should make sure that the code redirects user to login page in case the session key is not found. That means, in the else section of below code, you should take users to login page to try again. Which I am sure is happening.
if (Session["authenticated"] != null)
{ /*user is authenticated*/ }else{ /*redirect to login*/ }
Its is recommended to use <authentication mode="Forms" /> if the website is accessible over the internet. Other benefit of using this setting is that you can set default and login page.
Finally, FormsAuthenticationTicket is a class with property and values that are used when working with Forms authentication to identify authenticated users.
Read through msdn article to know more about asp.net membership.
https://msdn.microsoft.com/en-us/library/yh26yfzy%28v=vs.140%29.aspx
We are using the Simple Membership Provider with ASP.NET MVC 4, and we're using the Facebook Client to provide Facebook login support (similar to http://www.asp.net/mvc/overview/getting-started/using-oauth-providers-with-mvc).
We have gotten this working, but the session always times out within a day, and we want the login to be persistent, so the user can login and use the service just once.
In the out-of-the-box ExternalLoginCallback function, I am attempting to set the createPersistentCookie parameter to true, but it won't keep the login alive. Here is the call I am making:
OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: true)
Am I going to have to set the Forms Authentication cookie manually in order to accomplish a persistent login? Or is there another way of doing this while still taking advantage of the out-of-the-box Facebook login functionality?
The ASPXAUTH cookie is used to determine if a user is authenticated. You can track expiration time with firebug or any other web debug tool. In your project the cookie is set in ExternalLoginCallback. Here is example screen setting cookies' expiration timeout.
All what I had to do to make it work was to use SSL, and change cookie timeout in web.config. Here is example with timeout set to 1 minute. Don't forget to mark requireSSL on true.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="1" requireSSL="true"/>
</authentication>
But in your case i believe the problem is with short live access token from facebook(default around 2h). In case if the problem is with access token here is link how to extend lifetime of access token.
I am as a study project developed a website in ASP.net. In my web.config file i have autheticaion mode as windows. and i am using an appsettings connection string to connect to my SQL2005 database.
Now i want to know what kind of authentication is this?
Is this windows? forms? or anonymous authentication?
I have user table in sql 2005 and my first screen is login page. Obviously this user table has login details like username and password which will be matched to user input.
I dont understand i have read so many post on authorization and authienticaion but please clear me on this. Thanks in advance.
You are currently using Windows authentication. Your Windows username and password is used to authenticate you to asp.net.
A login page writing to a user table would be asp.net forms authentication.
Note that sql server authentication is a totally separate issue. It is up to your code to authenticate against your database. When doing so, the connection string in web.config file can be used.
If you want customize your credentials of string connection in order to access your DataBase, you can use Integrated Security
or Trusted_Connection
When the value is true, the current credentials of the Windows account used for authentication.
Nota : in yur case i think that you can use FormsAuthentification (You have Windows Authentification)
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.80).aspx
Forms Authentification :
<authentication mode="Forms">
<forms loginUrl="~/login.aspx">
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
After your click
if (IsAuthenticatedValue) //You can adjust your condition
{
FormsAuthentication.RedirectFromLoginPage (.., ..);
}
else
{
Console.WriteLine("Invalid credentials. Please try again.");
}
Link : http://msdn.microsoft.com/fr-fr/library/xdt4thhy(v=vs.80).aspx
In addition to the other answer here:
Once the user is logged in, create a Session and store the fact they are logged in using that such as
Session["LoggedIn"] = true;
Session["Username"] = username;
Then check if they are logged in using your Code and authorise access to the page using that. So on page load if they logged in continue loading the page, else send them to the login page.
When you want to log the user off simply do Session.Clear();
I've got 2 MVC3 Internet websites. One (Site1) uses Windows authentication and is in the Local Intranet Zone. The second (Site2) is publicly available and uses Forms Authentication. Both sites are in the same Domain, but have a different sub-domain. I want to share authentication cookies between the two. In order to do this, they need identical settings in the web config. Sometimes this works, most of the time it doesn't. If anyone hits Site1 from outside our network, they get a 403 error, which is good. If a network user hits Site1, they're allowed in based on their network credentials. I then check their user's roles with the code below.
var userName = string.Empty;
var winId = (WindowsIdentity)HttpContext.User.Identity;
var winPrincipal = new WindowsPrincipal(winId);
if(winPrincipal.IsInRole("SiteAdmin")) {
FormsAuthentication.SetAuthCookie("siteadmin", false);
userName = "siteadmin"; //This is a Forms Auth user
}
else if(///I check for other roles here and assign like above)
Once I've checked the roles, I forward them onto Site2, creating a cookie for them if the user is in one of the roles determined in the if...statement above.
if(!string.IsNullOrEmpty(userName)) {
//Add a cookie that Site2 will use for Authentication
var cookie = FormsAuthentication.GetAuthCookie(userName, false);
cookie.Domain = FormsAuthentication.CookieDomain; //This may need to be changed to actually set the Domain to the Domain of the TVAP site.
HttpContext.Response.Cookies.Add(cookie);
}
//Network users not found in roles will simply be forwarded without a cookie and have to login
HttpContext.Response.RedirectPermanent(tvapUrl);
I've set up in the web.config a matching MachineKey (validationkey, decryptionkey and validation) for each site.
They also both have the same authentiation settings, with the exception of the mode. So my config for this looks like this.
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" name=".ASPXFORMSAUTH" protection="All" path="/" domain="mydomain.com" enableCrossAppRedirects="true" timeout="2880" />
</authentication>
I think my problem is that the 'authentication' mode is different for each one, so Site2 won't use the authentication cookie from site1. This is just a guess though. Is there anyway I can figure out the issue?
According to this article, what I have going here should work. And there have been times where I think it's worked, but it's hard to tell, as I may have cookies cached and their getting reused. I'm hoping someone can see something I'm missing here, or has an alternative solution.
UPDATE
I checked my authentication cookie on Site2 after logging in normally and found the Domain wasn't set, so I've removed that line of code.
Also, I read about cookies expiring when the date isn't set, so I set an Expire Date on my cookie before sending with the request.
So, with those two changes, here's where I'm at.
It works on Chrome and Firefox, but not with IE. Not sure. I'm going to do some additional testing from another machine and another user so I know I haven't got any residual cookies sitting around.
I determined my problem was not setting the Expires property of my cookie. According this Microsoft article, cookies won't be written to the client unless the Expires property is set.
"If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk."
In this case, I needed the cookie to be written to disk since I was doing a server transfer to another site, thereby ending the session for that user. I'm not 100% sure that this was the fix, but it is working now, so I'm assuming that.
I have created a site in ASP.NET 3.5 & I have only 2 or 3 user login IDs who can login to the website.
What would be the best way to save these login details? Which of these approaches, or others, would be most suitable?
Using Forms Authentication, and saving credentials (username and password) in web.config
to create a text file in directory and modify it
Which approach is best from a security and maintenance perspective? What other approaches are suitable for a login system for ASP.NET?
Use the default ASP.NET Sql Membership Provider. The link will show you how to used it and get it configured.
Do you already have a database? If so, use forms authentication and ASP.NET membership like everyone says. It is real simple to integrate into your current database (assuming it's sql server - i don't know about others). I realize adding a DB for 2 or 3 users isn't always an option due to budget or whatever so you can use forms authentication and store the user in the web.config. I've done this in the past and it is very simple.
Your web.config will look like:
<authentication mode="Forms">
<forms loginUrl="Login.aspx">
<credentials passwordFormat="Clear">
<user name="myUser" password="password" />
</credentials>
</forms>
</authentication>
Then you can use the built in login controls. If you do it this way you need to implement the Autenticate event.
protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
{
string UserName = Login1.UserName;
string Password = Login1.Password;
if (FormsAuthentication.Authenticate(UserName, Password))
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
}
Of course this isn't the most secure way to go about this, and you'll probably want to at least look at encrypting the credentials in the web.config, but it is simple and works when a database isn't an option.
With ASP.NET you can use some of the built-in/provided authentication providers that let you manage the users in a database and it uses proper guidelines like hashing passwords, etc. by default.
You could use ASP.NET membership. Even though you won't have many users, it handles all of the authentication details for you.