C#中FormsAuthentication用法实例
程序员文章站
2023-12-13 20:32:40
using system;
using system.web;
using system.web.security;
namespace authtest...
using system; using system.web; using system.web.security; namespace authtest { public class authentication { /// <summary> /// 设置用户登陆成功凭据(cookie存储) /// </summary> /// <param name="username">用户名</param> /// <param name="password">密码</param> /// <param name="rights">权限</param> public static void setcookie(string username,string password,string rights) { // //string password="test"; // string userdata = username + "#" + password+"#"+rights; if (true) { //数据放入ticket formsauthenticationticket ticket = new formsauthenticationticket(1, username, datetime.now, datetime.now.addminutes(60), false, userdata); //数据加密 string enyticket = formsauthentication.encrypt(ticket); httpcookie cookie = new httpcookie(formsauthentication.formscookiename, enyticket); httpcontext.current.response.cookies.add(cookie); } } /// <summary> /// 判断用户是否登陆 /// </summary> /// <returns>true,fales</returns> public static bool islogin() { return httpcontext.current.user.identity.isauthenticated; } /// <summary> /// 注销登陆 /// </summary> public static void logout() { formsauthentication.signout(); } /// <summary> /// 获取凭据中的用户名 /// </summary> /// <returns>用户名</returns> public static string getusername() { if (islogin()) { string struserdata = ((formsidentity)(httpcontext.current.user.identity)).ticket.userdata; string[] userdata = struserdata.split('#'); if (userdata.length != 0) { return userdata[0].tostring(); } else { return ""; } } else { return ""; } } /// <summary> /// 获取凭据中的密码 /// </summary> /// <returns>密码</returns> public static string getpassword() { if (islogin()) { string struserdata = ((formsidentity)(httpcontext.current.user.identity)).ticket.userdata; string[] userdata = struserdata.split('#'); if (userdata.length!=0) { return userdata[1].tostring(); } else { return ""; } } else { return ""; } } /// <summary> /// 获取凭据中的用户权限 /// </summary> /// <returns>用户权限</returns> public static string getrights() { if (islogin()) { string struserdata = ((formsidentity)(httpcontext.current.user.identity)).ticket.userdata; string[] userdata = struserdata.split('#'); if (userdata.length!=0) { return userdata[2].tostring(); } else { return ""; } } else { return ""; } } } }