ASP.NET MVC - Set custom IIdentity or IPrincipal

后端 未结 9 1394
忘了有多久
忘了有多久 2020-11-21 23:06

I need to do something fairly simple: in my ASP.NET MVC application, I want to set a custom IIdentity / IPrincipal. Whichever is easier / more suitable. I want to extend the

9条回答
  •  粉色の甜心
    2020-11-21 23:54

    Based on LukeP's answer, and add some methods to setup timeout and requireSSL cooperated with Web.config.

    The references links

    • MSDN, Explained: Forms Authentication in ASP.NET 2.0
    • MSDN, FormsAuthentication Class
    • SO, .net Access Forms authentication “timeout” value in code

    Modified Codes of LukeP

    1, Set timeout based on Web.Config. The FormsAuthentication.Timeout will get the timeout value, which is defined in web.config. I wrapped the followings to be a function, which return a ticket back.

    int version = 1;
    DateTime now = DateTime.Now;
    
    // respect to the `timeout` in Web.config.
    TimeSpan timeout = FormsAuthentication.Timeout;
    DateTime expire = now.Add(timeout);
    bool isPersist = false;
    
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
         version,          
         name,
         now,
         expire,
         isPersist,
         userData);
    

    2, Configure the cookie to be secure or not, based on the RequireSSL configuration.

    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
    // respect to `RequreSSL` in `Web.Config`
    bool bSSL = FormsAuthentication.RequireSSL;
    faCookie.Secure = bSSL;
    

提交回复
热议问题