You should just use FormsAuthentication to set the cookie:
FormsAuthentication.SetAuthCookie(theUserID, true);
And then get it back:
string userId = HttpContext.Current.User.Identity.Name;
If you are worried about security, you can consider only using secure cookies (you will only be able to read that cookie over https).
There's more info on this in a related post: Manual Access control in ASP .Net
Update: According to your comment, you don't think you can set a Forms Authentication cookie in your custom login form. So I created a blank ASP.NET 4 project, where I created a custom login -- it will log in any unauthenticated user. Here are the three pieces:
The web.config
(your project should have something similar since you have a form on your site where people login):
<authentication mode="Forms"></authentication>
The code front:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="emptyWebApp._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Username: <asp:Label ID="_username" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
The code behind:
using System;
using System.Web;
using System.Web.Security;
namespace emptyWebApp
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
_username.Text = HttpContext.Current.User.Identity.Name;
}
else
{
_username.Text = "Not logged in";
FormsAuthentication.SetAuthCookie("CookieMan", true);
}
}
}
}
As you can see, you can set an Authentication cookie using FormsAuthentication.SetAuthCookie
in your own custom authentication function, even one as irrational as this.
In this case, the first time they hit the page, it will show Username: Not logged in
and then it will log them in as "CookieMan". Refreshing the page will show Username: CookieMan
.