How can I set the Page.User Property in ASP.NET?
This is mostly a theory question, for example if I wanted to create my own alternative to 开发者_JAVA技巧forms authentication.
Page.User
just returns Page.Context.User
, which should be set in a handler for HttpApplication.AuthenticateRequest
via module or global.asax
. You can provide a custom implementation of IPrincipal
, which could then return a custom implementation of IIdentity
.
For example:
public class App : HttpApplication
{
public App()
{
AuthenticateRequest += App_AuthenticateRequest;
}
void App_AuthenticateRequest(object sender, EventArgs e)
{
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var userData = GetUserData(cookie.Value);
var userIdentity = new MyIdentity(userData);
Context.User = new MyPrincipal(userIdentity);
}
private string GetUserData(string value)
{
try
{
var ticket = FormsAuthentication.Decrypt(value);
return ticket == null ? null : ticket.UserData;
}
catch (ArgumentException)
{
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
return null;
}
}
}
You need to write your own authentication module - see this excellent article that explains how to write an ASP.NET authentication module supporting basic & digest authentication.
In case, you are thinking of only forms authentication scheme then you really don't have to write one. The in-build Forms Authenticate module is quite extensible (and offers a lot of flexibility).
After some googling, I found this blogpost. It describes quite well how to do it. Basically you need to create a custom HTTP module and handle the OnAuthenticateRequest
event of HttpApplication
object.
精彩评论