Skip to content

Instantly share code, notes, and snippets.

@bestpika
Last active March 6, 2017 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save bestpika/3901b65112595156826b to your computer and use it in GitHub Desktop.
Save bestpika/3901b65112595156826b to your computer and use it in GitHub Desktop.
自製登入說明

http://blog.miniasp.com/post/2008/06/11/How-to-define-Roles-but-not-implementing-Role-Provider-in-ASPNET.aspx

Web.config 設定表單驗證

<system.web>
    <authentication mode="Forms">
        <forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH" />
    </authentication>
    <authorization>
        <deny users="?" />
    </authorization>
    <!-- 使用 sitemap -->
    <siteMap defaultProvider="Def" enabled="true">
        <providers>
            <clear />
            <add name="Def" type="System.Web.XmlSiteMapProvider" siteMapFile="..." />
            <add name="Web" type="System.Web.XmlSiteMapProvider" siteMapFile="..." securityTrimmingEnabled="true" />
        </providers>
    </siteMap>
</system.web>

Global.asax 加入

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (Request.IsAuthenticated && Request.Path.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) // 後面那個是忽略大小寫
    {
        FormsIdentity fi = User.Identity as FormsIdentity;
        FormsAuthenticationTicket fat = fi.Ticket;
        string[] roles = fat.UserData.Split(new char[] { ',' });
        Context.User = new GenericPrincipal(Context.User.Identity, roles);
    }
}

使用 user 登入,這段跑完就等於登入了

FormsAuthentication.RedirectFromLoginPage(user, false)

登出

FormsAuthentication.SignOut();

要取得是否登入

User.Identity.IsAuthenticated; // bool

要知道使用者是不是有某個權限

User.IsInRole("..."); // bool

這個很重要

FormsAuthentication

sample

public static void loginAuth(string user, string name, string role)
{
    FormsAuthentication.RedirectFromLoginPage(user, false); // 登入的這件事

    var v = 1023;
    DateTime st = DateTime.Now, ed = st.AddHours(12);
    var isPersistent = false;

    var fatUser = new FormsAuthenticationTicket(v, name, st, ed, isPersistent, user);
    var fatRole = new FormsAuthenticationTicket(v, name, st, ed, isPersistent, role);

    var faeUser = FormsAuthentication.Encrypt(fatUser);
    var faeRole = FormsAuthentication.Encrypt(fatRole);

    HttpContext.Current.Response.Cookies.Add(new HttpCookie("login", faeUser));
    HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, faeRole));
}

public static string getUserData()
{
    HttpCookie login = HttpContext.Current.Request.Cookies["login"];
    FormsAuthenticationTicket fatLogin = FormsAuthentication.Decrypt(login.Value);
    var user = fatLogin.UserData;
    return user;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment