creating a persisted cookie with forumsauthentication - forms-authentication

I am doing the following during login, but the logins don't seem to be persisting at all:
FormsAuthentication.SetAuthCookie(userId.ToString(), true);

You have run into a bug that MS calls an undocumented security feature.
In order to set a persistent cookie you need to create it yourself and set the Expiration explicitly. The only trick is to get the FormsAuthentication timeout value, which, in their infinite wisdom, microsoft has not exposed since 1.0. I have provided my method for getting this value.
Here is a working example.
Login.aspx
<%# Page Language="C#" %>
<script runat="server">
protected void Login1_LoggedIn(object sender, EventArgs e)
{
var login = (Login)sender ;
if (login.RememberMeSet)
{
// hack to get forms timeout - it is not publicly surfaced anywhere.
var tmpTicket = FormsAuthentication.GetAuthCookie("foo", true);
var timeout = tmpTicket.Expires;
// create a new ticket
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(2, login.UserName, DateTime.Now, timeout, true, "", FormsAuthentication.FormsCookiePath);
string ticketEncrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted)
{
HttpOnly = true,
Path = FormsAuthentication.FormsCookiePath,
Secure = FormsAuthentication.RequireSSL,
Expires = ticket.Expiration
};
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cookies.Add(cookie);
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Login ID="Login1" runat="server" OnLoggedIn="Login1_LoggedIn">
</asp:Login>
</div>
</form>
</body>
</html>

Related

Did I should encode the string before assign it to a asp.net TextBox

1、Because allow users to type in html tags like <script> and so on,So I disabled the asp.net validate Request in web.config.
<httpRuntime requestValidationMode="2.0"/>
<pages validateRequest="false"/>
2、In order to prevent from xss attacking ,I have added HttpUtility.HtmlEncode to encode string.
3、In my web application Users can add and edit themselves's articles.But I do not sure If I should encode at the page load phase for the TextBox in the ArticleEdit.aspx page.
e.g:
ArticleEdit.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="text" id="articleTitle" runat="server" />
</form>
</body>
</html>
ArticleEdit.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
string titleText = "<script>alert('1111');</script>"; //string "<script>alert('1111');</script>" is fetched from DB;
articleTitle.Value = titleText;
}
Questions 1:
Did I shoud encode the titleText string like below?
string titleText =HttpUtility.HtmlEncode("<script>alert('1111');</script>");
articleTitle.Value = titleText;
Questions 2:
If encode the string.After page load complete ,user will seen an encoded string
<script>alert('1111');</script>
instead of "<script>alert('1111');</script>".
How to solve this?
Sorry for my bad english.Thanks in advance!
Did I shoud encode the titleText string like below?
No, you don't need to encode anything if you are assigning it to the Value property of a TextBox. The WebControl will automatically encode it before displaying.

Dealing with a Large Number of Post Variables ASP.Net

I am running into an issue where I have multiple forms with a number of controls on them (20-40). The problem is that when I handle the postback, I need to put their values into variables and if they are not asp.net server controls (i.e select, input, etc...) I sometimes need to make sure they even exist. So, if I have a plain html checkbox, which is unchecked, it will not be posted to the server and you need to check for its existence, before being able to get its value. After that I need to pass them into a method to save to the database. The method handles all my crud and business validation. Setting this up is tedious at best and very time consuming. What are people doing to handle this? I am using ASP.Net 4.0 Web forms and VB.Net. One thought was to pass the http context into the method and let the code in the method look for the values. Still, doesn't seem that good of a solution. Any advice would really be appreciated, since I know I am not the only one who has run into this problem. Thanks in advance.
Wade
For large forms, you can:
create javascript object on client, convert it to JSON string, put JSON string to ASP .NET control Hidden or invisible textarea;
submit form and deserialize JSON to object on server.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validation.net.webforms.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="Hidden1" />
<input type="checkbox" id="CheckBox1" checked />
<input type="checkbox" id="CheckBox2" />
<input type="text" id="text1" name="text1" value=""/>
<asp:Button runat="server" Text="Button" ID="Button1" OnClientClick="createJSON()" OnClick="Button1_Click" />
<script type="text/javascript">
function createJSON() {
$('#Hidden1').val(JSON.stringify({
field1: $('#CheckBox1').is(':checked'),
field2: $('#CheckBox2').is(':checked'),
field3: $('#text1').val()
}));
}
$(document).ready(function () {
$("#form1").validate({
onsubmit: false,
rules: {
text1: {
required: true,
digits: true
}
}
});
$("#Button1").click(function (evt) {
var isValid = $("#form1").valid();
if (!isValid) evt.preventDefault();
});
});
</script>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.Script.Serialization;
public class myClass
{
public bool field1;
public bool field2;
public string field3;
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var result = (myClass)(new JavaScriptSerializer()).Deserialize(Hidden1.Value, typeof(myClass));
}
}
Install validation:
PM> Install-Package JQuery.Validation
PM> Install-Package JQuery.Validation.WebForms
From the moment that some controls they not post back any value, like the check box if is not checked you have two options.
Know all your controls before and after the post back / or
Create with javascript all the names of the controls and post them back in a hidden field.
Now, on the post back you have all the posted values on the HttpContext.Current.Request.Form where you can read them all.
On the client side you can use simple javascript or jQuery to create the list of all input controls and send them on a hidden input. Here is an example:
var inputs, index, cNames = "";
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
cNames += "&" + inputs[index].name;
}
document.getElementById("AllControls").value = cNames;
or the same with jQuery
var cAllNames = "";
$('input').each(function() {
cAllNames += "&" + $(this).attr("name");
});
jQuery('#AllControls').val(cAllNames);
and on your page you have a hidden control like
<input type="hidden" name="AllControls" id="AllControls" />
and on the post you have all the names of your controls in a line like:
AllControls=&__VIEWSTATE&__EVENTVALIDATION&cbBoxTest&AllControls&Button1
There you can split that string, each name is seperated with the &, and there you can see what is used, what is not. You can either pass additional informations about that controls - the same way I send the name of each.
For each web form create a model class that has public properties with all the fields that may be on the form. Create name, validation and default value attributes and apply them to the properties. During the postback, find out what the model class is needed, create an instance, iterate its public properties and apply: if post has the field with property name - validate the value and apply to the field, if not - apply the default. Something like (i'll use c# but I guess it's clear anyway)
MyCrudModelForSomeForm {
[MyWebFormField(Default = 42, Type = typeof(int), Name = "txtAmount")]
public int SomeInt { get; set; }
[MyWebFormField(Default = "Hello", Type = typeof(string), Name = "txtMessage", Validate = "$[A-Z]{6}^")]
public string SomeString { get; set; }
[MyWebFormField(Default = "Zimbabwe", Type = typeof(string), Name = "txtCountryChoice")]
public string SomeOtherString { get; set; }
}
That's basically the custom implementation of M(odel) from MVC concept.
The ASP.NET Webforms arch does not support multiple forms
If you have created a page that has multiple forms then i would suggest use jQuery and Post Individual form to the respected handler to process the request
This will be simple and elegant

set mintime and maxtime of timefield dynamically in ext.net

I am working with EXT.NET 1.2
I want to set minTime and maxTime from codebehind(from cs Page).
I ha dwritten following code but not working that code.. is their any mistake or is ther any another method(through Javascript)??
Code
tmFrom.Increment = 30;
string strmin = obj.startTime.ToShortTimeString();
DateTime dtmin = DateTime.ParseExact(strmin, "H:mm tt", CultureInfo.InvariantCulture);
string strmax = obj.endTime.ToShortTimeString();
DateTime dtmax = DateTime.ParseExact(strmax, "H:mm tt", CultureInfo.InvariantCulture);
tmFrom.Format = "H:mm";
tmFrom.MinTime = dtmin.TimeOfDay;
tmFrom.MaxTime = dtmax.TimeOfDay;
I am setting minTime and maxTime from Database value.
Based on your code sample, it appears obj.startTime and obj.endTime are both already DateTime objects. You should not have to convert into Strings, then back into DateTime objects.
The following sample demonstrates the complete scenario.
Example
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
var startTime = DateTime.Now.AddMinutes(-215);
var endTime = DateTime.Now.AddMinutes(215);
var time = this.TimeField1;
time.Increment = 30;
time.Format = "H:mm";
time.MinTime = startTime.TimeOfDay;
time.MaxTime = endTime.TimeOfDay;
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET Examples</title>
</head>
<body>
<ext:ResourceManager runat="server" />
<ext:TimeField ID="TimeField1" runat="server" FieldLabel="Time" />
</body>
</html>
Hope this helps

Multiple fileuploads with ASP.NET MVC

Hi,
I have implemented this plugin by Steve Sanders from 2008. In my solution I have 3 buttons for 3 uploads and this works just fine. But ist not a perfect fit and the question is if thera is a better solution for me?
What I need is :
Be able to upload multiple files
When the Control Action is triggered It should be possible to work with the files
The enduser should be able to cancel a uploaded file(this is not possible with Steves plugin as far as I know)
Easy to use with ASP.NET MVC
If a post is done to the Control Action and a validation error is thrown back the uploads may not disappear.
Pleas Advice
How about using Uploadify? I have used it before, and it works great. But do notice that it also needs a Flash front-end in order to work...
Take a look at this StackOverflow question - there you'll find more info of how to use it with ASP.NET MVC.
Under the hood the Steve Sanders' plugin uses swfUpload which can support everything you need. His plugin however does not seem to expose all of the features of swfUpload such as canceling uploads.
I use swfUpload to it's full extent on my sites supporting multiple files, canceling uploads, validation without canceling other uploads, etc.
Here's a demo of swfUpload in action where you can cancel uploads
Another option is SlickUpload.
It's not free but definitely worth it in my opinion. I used it in an MVC project recently and was extremely happy with it. Best upload plugin I've ever used + it comes with all sorts of validation helpers.
It's fully customizable too.
Download the trial and have a look for yourself :)
It's not possible with pure ASP.NET.
You need to take JQuery uploadify.
It's the best you can find, trust me, I tried for an entire day.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="MassUpload.aspx.vb" Inherits="Raumplaner_New.MassUpload" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Mass Upload</title>
<link href="../upload/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="../scripts/swfobject.js"></script>
<script type="text/javascript" src="../scripts/jquery.uploadify.v2.1.0.min.js"></script>
<script type = "text/javascript">
$(document).ready( function()
{
$("#<%=FileUpload1.ClientID%>").uploadify({
'uploader' : '../upload/scripts/uploadify.swf',
'script' : '../cgi-bin/Upload.ashx',
'cancelImg' : '../upload/images/cancel.png',
'folder' : '../upload/temp',
'buttonImg' : '../upload/images/uploadbutton.png',
'width' : '97',
'height' : '22',
'wmode' : 'transparent',
'displayData' : 'speed',
'multi' : true,
'auto' : true,
'simUploadLimit' : 20,
'fileDesc' : 'DWG und SWF - Dateien',
'fileExt' : '*.dwg;*.swf',
'onSelect' : function(event, queueID, fileObj){ EnableObject('FileUpload1');},
'onCancel' : function(event, queueID, fileObj, data){DisableObject('FileUpload1');},
'onComplete' : function(event,queueID,fileObj,response,data){alert(fileObj.name);}
});
$("#startUploadLink").click( function()
{
$('#<%=FileUpload1.ClientID%>').uploadifyUpload();
return false;
});
$("#clearQueueLink").click( function()
{
$("#<%=FileUpload1.ClientID%>").uploadifyClearQueue();
return false;
});
});
</script>
</head>
<body style='background:black;'>
<div id='main'>
<form id="form1" runat="server">
<br/>
<div class="demo">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
Start Upload |
Clear
</div>
</form>
</div>
</body>
</html>
And here's upload.ashx
<%# WebHandler Language="VB" Class="Upload" %>
Imports System
Imports System.Web
Public Class Upload : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = context.Request("folder")
'If you prefer to use web.config for folder path, uncomment below:
'tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
savepath = context.Server.MapPath(tempPath)
Dim filename As String = postedFile.FileName
If Not System.IO.Directory.Exists(savepath) Then
System.IO.Directory.CreateDirectory(savepath)
End If
postedFile.SaveAs((savepath & "\") + filename)
context.Response.Write((tempPath & "/") + filename)
context.Response.StatusCode = 200
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Setting ResponseCode manually at CodeBehind fails with IIS7 and 2008 Server

I have developed a web app a year ago aimed to work with IIS6.
Now we are moving to IIS7 and I thought, I'd do some integration tests.
One of this fails:
The web app is more or less a search-engine, giving a 404 or 500 (thanks to your google-advisor ...) when there weren't any results or the data-container is not loaded yet. With IIS6 this worked great: The page output was eg. result.aspx, showing some message and giving back the specified http status (set at codebehind).
Now with IIS7 this behaviour is broken: If I set the http status code at codebehind, my page won't be delivered anymore - instead showing the generic error page of IIS7.
No, I do not want to do any dirty hack with the customErrors-Section ...
I just want the original behaviour back!
Is there any way to do this?
Edit:
Consider following page
<%# Page Language="C#" AutoEventWireup="true"%>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Response.StatusCode = 404;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
This page should be displayed
</div>
</form>
</body>
</html>
Vista + IIS7 = OK
2008 Server + IIS7 = Generic Error Page
have you tried this:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true;
}
HttpResponse.TrySkipIisCustomErrors Property (System.Web)
Your problem is probably that you have tried to set the Status Code (which counts as part of the Header) at some point after you've starting sending the Body of the response i.e. your pages contents - in your case the message.
To solve this you can try setting Response.Buffer to true and then if you have to set a 404/500 response code then call Response.Clear() before setting the response code.
Note that if you are sending a 404/500 then there should generally be no body to the response (although the HTTP spec does allow for it)

Resources