private void CreateFormsAuthTicket(string username, int ValidMinutes, bool rememberMe) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddMinutes(ValidMinutes), rememberMe, username ); // Bileti şifrele. string encryptedTicket = FormsAuthentication.Encrypt(ticket); // Bileti sakla. HttpCookie formsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); HttpContext.Current.Response.Cookies.Add(formsCookie); // FormsAuthentication kimliğini yarat. FormsIdentity formsId = new FormsIdentity(ticket); //roles string[] roles = new string[] { "user" }; // Yeni kullanıcı bilgisini yarat. HttpContext.Current.User = new GenericPrincipal(formsId, roles); }
private static IIdentity GetIdentity() { HttpCookie ticketCookie = HttpContext.Current.Request.Cookies["ticket"]; if (ticketCookie == null) { return null; } string val = ticketCookie.Value; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(val); var ident = new FormsIdentity(ticket); return ident; }
void Application_PostAuthenticateRequest() { IPrincipal user = HttpContext.Current.User; if (user.Identity.IsAuthenticated && user.Identity.AuthenticationType == "Forms") { FormsIdentity formsIdentity = (FormsIdentity)user.Identity; FormsAuthenticationTicket ticket = formsIdentity.Ticket; CustomIdentity customIdentity = new CustomIdentity(ticket); var accountRepository = DependencyResolver.Current.GetService <IAccountRepository>(); var userEntity = accountRepository.Get(customIdentity.Name); CustomPrincipal customPrincipal = new CustomPrincipal(customIdentity, userEntity); HttpContext.Current.User = customPrincipal; Thread.CurrentPrincipal = customPrincipal; } }
public Model_UsuarioAutenticado(FormsIdentity fIdentity) { string[] usuarioData = new string[4]; usuarioData = fIdentity.Ticket.Name.Split('|'); RolID = Convert.ToInt32(usuarioData[1]); if (RolID == 1) { UsuarioID = Convert.ToInt32(usuarioData[0]); RolID = Convert.ToInt32(usuarioData[1]); } else { UsuarioID = Convert.ToInt32(usuarioData[0]); RolID = Convert.ToInt32(usuarioData[1]); EmpresaID = Convert.ToInt32(usuarioData[2]); SucursalID = Convert.ToInt32(usuarioData[3]); } }
/// <summary> /// This changes the behavior of AuthorizeCore so that it will only authorize /// users if a valid token is submitted with the request. /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { string token = httpContext.Request.Params[TOKEN_KEY]; if (token != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token); if (ticket != null) { FormsIdentity identity = new FormsIdentity(ticket); string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name); GenericPrincipal principal = new GenericPrincipal(identity, roles); httpContext.User = principal; } } return(base.AuthorizeCore(httpContext)); }
public WEB_PAGECONFIG JsonToEntity(JObject json) { WEB_PAGECONFIG en = new WEB_PAGECONFIG(); try { if (!string.IsNullOrEmpty(json.Value <string>("ID"))) { en.ID = Convert.ToInt32(json.Value <string>("ID")); } else { en.ID = -1; } en.CODE = json.Value <string>("CODE"); en.NAME = json.Value <string>("NAME"); en.PAGENAME = json.Value <string>("PAGENAME"); en.CUSTOMERCODE = json.Value <string>("CUSTOMERCODE"); if (!string.IsNullOrEmpty(json.Value <string>("ENABLED"))) { en.ENABLED = Convert.ToInt32(json.Value <string>("ENABLED")); } else { en.ENABLED = 1; } en.BUSITYPE = json.Value <string>("BUSITYPE"); en.BUSIDETAIL = json.Value <string>("BUSIDETAIL"); en.CONFIGCONTENT = "业务类型=" + en.BUSITYPE + ";业务细项=" + en.BUSIDETAIL; FormsIdentity identity = HttpContext.Current.User.Identity as FormsIdentity; string userName = identity.Name; JObject json_user = Extension.Get_UserInfo(userName); en.USERID = (Int32)json_user.GetValue("ID"); en.USERNAME = (string)json_user.GetValue("REALNAME"); en.REASON = json.Value <string>("REASON"); return(en); } catch { return(null); } }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { bool hasUser = HttpContext.Current.User != null; bool isAuthenticated = hasUser && HttpContext.Current.User.Identity.IsAuthenticated; bool isIdentity = isAuthenticated && HttpContext.Current.User.Identity is FormsIdentity; if (isIdentity) { //取得表單驗證身份 FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; //取得FormsAuthenticationticket物件 FormsAuthenticationTicket ticket = id.Ticket; //取得userData所儲存的role資料 string[] roles = ticket.UserData.Split(','); HttpContext.Current.User = new GenericPrincipal(id, roles); } }
public User GetAuthenticatedUser(FormsIdentity identity) { var userData = identity.Ticket.UserData; if (userData.StartsWith("account-")) { return(null); } userData = userData.Substring(8); int userId; if (!int.TryParse(userData, out userId)) { //Logger.Fatal("User id not a parsable integer"); return(null); } return(_userService.GetUserById(userId)); }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; string userData = ticket.UserData; string[] roles = userData.Split(','); HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles); } } } }
/// <summary> /// 重写该方法,用来判断,是否进行了登录认证 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { var authorized = base.AuthorizeCore(httpContext); // 未登录直接返回false if (!authorized) { // The user is not authenticated errormsg = "抱歉,您未登录"; return(false); } IPrincipal principal = HttpContext.Current.User; if (principal == null) { errormsg = "抱歉,您未登录"; return(false); } FormsIdentity formsIdentity = principal.Identity as FormsIdentity; FormsAuthenticationTicket ticket = formsIdentity.Ticket; Credentials userInfo = JsonConvert.DeserializeObject <Credentials>(ticket.UserData); if (roleList != RoleEnum.None) { // TODO 获取当前用户真实角色 以KTDepartmentLeader测试 RoleEnum userRole = RoleEnum.KTDepartmentLeader; if (((RoleEnum)this.roleList & userRole) == userRole) { // 有权限做某事 return(true); } else { // 无权限做某事 errormsg = "抱歉,您没有进行该操作的权限"; return(false); } } return(true); }
//Dynamically setting nav bar protected void setNavBar() { FormsIdentity id = (FormsIdentity)User.Identity; FormsAuthenticationTicket ticket = id.Ticket; string userData = ticket.UserData; //userData = "Vihanga Liyanage;admin;CO00001" string[] data = userData.Split(';'); if (data[1] == "manageReport") { manageReportNavBar.Style.Add("display", "block"); } else if (data[1] == "generateReportUser") { generateReportUserNavBar.Style.Add("display", "block"); } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity id = (FormsIdentity)(HttpContext.Current.User.Identity); FormsAuthenticationTicket ticket = id.Ticket; string[] roles = new string[1]; roles[0] = ticket.UserData; HttpContext.Current.User = new GenericPrincipal(id, roles); } } } }
/// <summary> /// This should be called from the Application_AuthenticateRequest method in Global.asax. /// It adds the authenticated user's role to their identity. /// </summary> public static void AuthenticateRequest() { IPrincipal user = HttpContext.Current.User; if (user != null && user.Identity.IsAuthenticated && user.Identity is FormsIdentity) { FormsIdentity identity = (FormsIdentity)user.Identity; FormsAuthenticationTicket ticket = identity.Ticket; if (!FormsAuthentication.CookiesSupported) { // Decrypt our custom ticket from the one ASP.NET stored in the URL ticket = FormsAuthentication.Decrypt(ticket.Name); } // Extend the current identity with the user's role HttpContext.Current.User = new GenericPrincipal(identity, new[] { ticket.UserData }); } }
protected void Authenticate_User() { FormsIdentity id = (FormsIdentity)User.Identity; FormsAuthenticationTicket ticket = id.Ticket; string userData = ticket.UserData; //userData = "Vihanga Liyanage;admin;CO00001" string[] data = userData.Split(';'); if (data[1] != "manageAssetUser") { FormsAuthentication.SignOut(); ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "alert('You do not have access to this page. Please sign in to continue.'); window.location='" + Request.ApplicationPath + "Login.aspx';", true); } }
public static Team GetTeamFromFormsAuthentication() { Team result = null; if (HttpContext.Current.User.Identity.IsAuthenticated) { FormsIdentity fi = (FormsIdentity)HttpContext.Current.User.Identity; if (fi.IsAuthenticated) { result = new Team() { Id = int.Parse(fi.Ticket.UserData), //Session["teamId"], Name = fi.Name }; } } return(result); }
public ActionResult AddCart(string ProductID, int Quantity) { var cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { FormsIdentity id = (FormsIdentity)User.Identity; FormsAuthenticationTicket ticket = id.Ticket; string CustomerID = ticket.Name; productservice.CartEvent(CustomerID, ProductID, Quantity); TempData["Message"] = "成功加入購物車"; return(RedirectToAction("ProductItem", "Product", new { Id = ProductID })); } else { TempData["Message"] = "尚未登入會員"; return(RedirectToAction("Index", "Home")); } }
public static bool IsAuthenticated(Route route) { if (HttpContext.Current.User != null && HttpContext.Current.User.Identity is FormsIdentity && HttpContext.Current.User.Identity.IsAuthenticated) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; var user = ClarityDB.Instance.Users.FirstOrDefault(x => x.UserName == HttpContext.Current.User.Identity.Name); if (!ticket.Expired && user != null) { if (user.Role == Role.Admin) { return(true); } var classAuthentication = route.Method.DeclaringType.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(AuthenticateAttribute)); int classAuthentidationFlag = GetPermission(user, classAuthentication); switch (classAuthentidationFlag) { case 0: return(false); case 1: return(true); case -1: var methodAuthentication = route.Method.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(AuthenticateAttribute)); int methodAuthenticationFlag = GetPermission(user, methodAuthentication); if (methodAuthenticationFlag == 0) { return(false); } return(true); default: break; } } } return(false); }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; // Get the stored user-data, in this case, our roles string userData = ticket.UserData; string[] roles = userData.Split(','); HttpContext.Current.User = new GenericPrincipal(id, roles); } } } }
protected void Page_Load(object sender, EventArgs e) { string rola; FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket bilet = id.Ticket; Label1.Text = "Zalogowany jako: " + User.Identity.Name; // Get the stored user-data, in this case, our roles rola = bilet.UserData; if (rola != "admins") { Response.Redirect("index.aspx"); } DataSet ds = new DataSet(); DataTable dt = new DataTable(); NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=projekt;Database=projekt;"); conn.Open(); // quite complex sql statement string sql = "SELECT * FROM pracownicy"; // data adapter making request from our connection NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn); // i always reset DataSet before i do // something with it.... i don't know why :-) ds.Reset(); // filling DataSet with result from NpgsqlDataAdapter da.Fill(ds); // since it C# DataSet can handle multiple tables, we will select first dt = ds.Tables[0]; dt.Columns.Add("Usuń"); dt.Columns.Add("Edytuj"); // connect grid to DataTable GridView1.DataSource = dt; GridView1.DataBind(); }
protected void Application_AuthenticateRequest(Object objectSender, EventArgs e) { HttpContext currentContext = HttpContext.Current; if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity id = HttpContext.Current.User.Identity as FormsIdentity; FormsAuthenticationTicket ticket = id.Ticket; List <string> userData = new List <string>(); userData.Add(ticket.UserData); HttpContext.Current.User = new GenericPrincipal(id, userData.ToArray()); } } } }
public int insert_base_alterrecord(JObject json, DataTable dt) { FormsIdentity identity = HttpContext.Current.User.Identity as FormsIdentity; string userName = identity.Name; JObject json_user = Extension.Get_UserInfo(userName); string sql = @"insert into base_alterrecord(id, tabid,tabkind,alterman, reason,contentes,alterdate) values(base_alterrecord_id.nextval, '{0}','{1}','{2}', '{3}','{4}',sysdate)"; sql = String.Format(sql, json.Value <string>("ID"), (int)Base_YearKindEnum.Insp_ContainerStandard, json_user.GetValue("ID"), json.Value <string>("REASON"), getChange(dt, json)); int i = DBMgrBase.ExecuteNonQuery(sql); return(i); }
void Application_OnPostAuthenticateRequest(object sender, EventArgs e) { // Get a reference to the current User IPrincipal usr = HttpContext.Current.User; // If we are dealing with an authenticated forms authentication request if (usr.Identity.IsAuthenticated && usr.Identity.AuthenticationType == "Forms") { FormsIdentity fIdent = usr.Identity as FormsIdentity; // Create a CustomIdentity based on the FormsAuthenticationTicket CustomIdentity ci = new CustomIdentity(fIdent.Ticket); // Create the CustomPrincipal CustomPrincipal p = new CustomPrincipal(ci); // Attach the CustomPrincipal to HttpContext.User and Thread.CurrentPrincipal HttpContext.Current.User = p; Thread.CurrentPrincipal = p; } }
protected void Page_Load(object sender, EventArgs e) { FormsAuthenticationTicket ticket = null; try { FormsIdentity formsIdentity = HttpContext.Current.User.Identity as FormsIdentity; ticket = formsIdentity.Ticket; } catch { Response.Redirect("Default.aspx"); } empresaid = ticket.UserData.Split('|')[0]; ruc = ticket.UserData.Split('|')[1]; var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>(); if (!IsPostBack) { // Determine the sections to render if (HasPassword(manager)) { changePasswordHolder.Visible = true; } else { setPassword.Visible = true; changePasswordHolder.Visible = false; } // Render success message var message = Request.QueryString["m"]; if (message != null) { // Strip the query string from action Form.Action = ResolveUrl("~/Account/Manage"); } } }
} //rolename public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!string.IsNullOrEmpty(Roles)) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { string redirectOnSuccess = filterContext.HttpContext.Request.RawUrl; string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess); string loginUrl = FormsAuthentication.LoginUrl + redirectUrl; //filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Account", action = "LogOn" })); filterContext.HttpContext.Response.Redirect(loginUrl, true); } else { //whether has a role FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; string roles = ticket.UserData; bool isAuthorized = false; if (this.Roles.IndexOf(roles) > -1) { isAuthorized = true; } else { isAuthorized = false; } //bool isAuthorized = filterContext.HttpContext.User.IsInRole(this.RoleToCheckFor); //why always return false? if (!isAuthorized) { filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Shared", action = "UserAuthorizedError" })); } //throw new UnauthorizedAccessException("no permission"); } } else { throw new InvalidOperationException("non rolename"); } }
/// <summary> /// Application_AuthenticateRequest Event /// If the client is authenticated with the application, then determine /// which security roles he/she belongs to and replace the "User" intrinsic /// with a custom IPrincipal security object that permits "User.IsInRole" /// role checks within the application /// /// Roles are cached in the browser in an in-memory encrypted cookie. If the /// cookie doesn't exist yet for this session, create it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> // // protected void Application_AuthenticateRequest(Object sender, EventArgs e) { // SWEnet roles // Extract the forms authentication cookie string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (authCookie == null) { // There is no authentication cookie. return; } FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { throw; } if (null == authTicket) { // Cookie failed to decrypt. throw new Exception("failed to decrypt"); return; } // When the ticket was created, the UserData property was assigned a // pipe delimited string of role names. string[] roles = authTicket.UserData.Split(new char[] { '|' }); // Create an Identity object FormsIdentity id = new FormsIdentity(authTicket); // This principal will flow throughout the request. GenericPrincipal principal = new GenericPrincipal(id, roles); // Attach the new principal object to the current HttpContext object Context.User = principal; }
protected override bool AuthorizeCore(HttpContextBase httpContext) { var accessToken = String.Empty; if (httpContext.Request.QueryString.AllKeys.Contains(mArgumentName)) { accessToken = httpContext.Request.QueryString[mArgumentName]; } else if (httpContext.Request.Form.AllKeys.Contains(mArgumentName)) { accessToken = httpContext.Request.Form[mArgumentName]; } var userId = 0; try { userId = AccessTokenService.GetUserIdByAccessToken(accessToken); } catch (Exception ex) { var resultCode = ResultCode.ServerError; if (ex is ApiException) { resultCode = ((ApiException)ex).ResultCode; } TokenHelper.ResponseError(httpContext, ex.Message, (int)resultCode); httpContext.Response.End(); } if (userId == 0) { return(false); } var ticket = new FormsAuthenticationTicket(userId.ToString(), true, Int32.MaxValue); var formsIdentity = new FormsIdentity(ticket); var principal = new GenericPrincipal(formsIdentity, new[] { "Basic" }); httpContext.User = principal; return(true); }
public string SubAns(string ans, string question) { string message = ""; try { FormsIdentity id = (FormsIdentity)User.Identity; FormsAuthenticationTicket ticket = id.Ticket; //確認是否已答題 var UserAns = (from uans in userdb.Wedding_UserAns where uans.uid == question && uans.name == User.Identity.Name select uans).FirstOrDefault(); if (UserAns != null) { return(message = "你回答過囉!!"); } //確認題目是否關閉 var questionstate = from wedding in userdb.Wedding_Question where wedding.uid == question && wedding.name == ticket.UserData && wedding.state == "V" select wedding; if (questionstate.Count() == 0) { return(message = "此題目已關閉囉!!"); } Wedding_UserAns user = new Wedding_UserAns() { name = User.Identity.Name, ans = int.Parse(ans), anstime = dt, weddingname = ticket.UserData, uid = question, XorV = "X", }; userdb.Wedding_UserAns.Add(user); userdb.SaveChanges(); message = "完成"; } catch (Exception ex) { message = ex.Message; } return(message); }
/// <summary> /// Raises when a security module has established the identity of the user. /// </summary> /// <param name="sender">The sourceRow of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> protected virtual void Application_AuthenticateRequest(object sender, EventArgs e) { string pageUrl = Request.AppRelativeCurrentExecutionFilePath; if (ResourceProvider.IsResourceUrl(pageUrl)) { Context.SkipAuthorization = true; } else if (ActionProvider.IsPublicPage(pageUrl)) { if ((!FrameworkConfiguration.Current.WebApplication.Password.EnablePasswordRetrieval) && (string.Compare(pageUrl, ResourceProvider.PasswordRecoveryPageVirtualPath, StringComparison.OrdinalIgnoreCase) == 0)) { throw new HttpException(404, Resources.Error_404); } else { Micajah.Common.Bll.Action action = ActionProvider.FindAction(CustomUrlProvider.CreateApplicationAbsoluteUrl(Request.Url.PathAndQuery)); if (action != null) { Context.SkipAuthorization = (!action.AuthenticationRequired); } else { Context.SkipAuthorization = true; } switch (FrameworkConfiguration.Current.WebApplication.AuthenticationMode) { case AuthenticationMode.Forms: HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) { FormsIdentity id = new FormsIdentity(new FormsAuthenticationTicket(string.Empty, false, FrameworkConfiguration.Current.WebApplication.Login.Timeout)); GenericPrincipal principal = new GenericPrincipal(id, null); Context.User = principal; } break; } } } }
public TUser GetUser() { IPrincipal currentUser = ServiceContext.User; if ((currentUser != null) && currentUser.Identity.IsAuthenticated) { FormsAuthenticationTicket ticket = null; FormsIdentity userIdentity = currentUser.Identity as FormsIdentity; if (userIdentity != null) { ticket = userIdentity.Ticket; if (ticket != null) { return(GetCurrentUser(currentUser.Identity.Name, ticket.UserData)); } } } return(GetDefaultUser()); }
/// <summary> /// 是否是管理员登陆 /// </summary> /// <returns></returns> public static bool isAdmin() { if (HttpContext.Current.Request.IsAuthenticated) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; if ("admin".Equals(ticket.UserData.Split(',')[1]))//判断是前台登陆还是后台登陆 { return(true); } else { return(false); } } else { return(false); } }
public int insert_relaCompanyNature(JObject json, string stopman) { FormsIdentity identity = HttpContext.Current.User.Identity as FormsIdentity; string userName = identity.Name; JObject json_user = Extension.Get_UserInfo(userName); // string sql = @"insert into rela_country (id,declcountry,inspcountry,createman,stopman,createdate,startdate,enddate,enabled,remark,yearid) //values(rela_country_id.nextval,'{0-declcountry}','{1-inspcountry}','{2-createman}','{3-stopman}',sysdate,to_date('4-startdate','yyyy-mm-dd hh24:mi:ss'), //to_date('5-enddate','yyyy-mm-dd hh24:mi:ss'),'{6-enabled}','{7-remark}','')"; string sql = @"insert into rela_companynature (id,declcompanynature,inspcompanynature,createman,stopman,createdate,startdate,enddate,enabled,remark) values(rela_companynature_id.nextval,'{0}','{1}','{2}','{3}',sysdate,to_date('{4}','yyyy-mm-dd hh24:mi:ss'), to_date('{5}','yyyy-mm-dd hh24:mi:ss'),'{6}','{7}')"; sql = string.Format(sql, json.Value <string>("DECLCOMPANYNATURE"), json.Value <string>("INSPCOMPANYNATURE"), json_user.GetValue("ID"), stopman, json.Value <string>("STARTDATE") == "" ? DateTime.MinValue.ToShortDateString() : json.Value <string>("STARTDATE"), json.Value <string>("ENDDATE") == "" ? DateTime.MaxValue.ToShortDateString() : json.Value <string>("ENDDATE"), json.Value <string>("ENABLED"), json.Value <string>("REMARK")); int i = DBMgrBase.ExecuteNonQuery(sql); return(i); }
/// <summary> /// 登录验证、s授权 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_AuthenticateRequest(Object sender, EventArgs e) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { return; } string[] roles = authTicket.UserData.Split(','); FormsIdentity id = new FormsIdentity(authTicket); GenericPrincipal principal = new GenericPrincipal(id, roles); Context.User = principal;//存到HttpContext.User中 }
/** * 2. Fired after LogginIn method to perform authentication */ protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { bool authenticated = false; string userNameTxt = Login1.UserName; string passTxt = Login1.Password; authenticated = userServices.authenticateUser(userNameTxt, passTxt); e.Authenticated = authenticated; // set login status. if (authenticated) { string roles = userServices.getRoles(userNameTxt); // Create the authentication ticket FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket (1, // Version userNameTxt, // User name DateTime.Now, // Creation DateTime.Now.AddMinutes(60), // Expiration false, // Persistent roles); // User data // Code to create an encrypted string representation of the ticket and store it as data within an HttpCookie object. // Now encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Add the cookie to the cookies collection returned to the user's browser. Response.Cookies.Add(authCookie); // Redirect the user to the originally requested page // Response.Redirect(FormsAuthentication.GetRedirectUrl(userNameTxt, false)); } // Extract the forms authentication cookie string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie2 = Context.Request.Cookies[cookieName]; if (null == authCookie2) { // There is no authentication cookie. return; } //Add the following code to extract and decrypt the authentication ticket from the forms authentication cookie. FormsAuthenticationTicket authTicket2 = null; try { authTicket2 = FormsAuthentication.Decrypt(authCookie2.Value); } catch (Exception ex) { // Log exception details (omitted for simplicity) return; } if (null == authTicket2) { // Cookie failed to decrypt. return; } //Add the following code to parse out the pipe separate list of role names attached to the ticket when the user was originally authenticated. // When the ticket was created, the UserData property was assigned a // pipe delimited string of role names. string[] roles2 = authTicket2.UserData.Split(new char[] { '|' }); //Add the following code to create a FormsIdentity object with the user name obtained from the ticket name and a GenericPrincipal object that contains this identity together with the user's role list. // Create an Identity object FormsIdentity id = new FormsIdentity(authTicket2); // This principal will flow throughout the request. GenericPrincipal principal = new GenericPrincipal(id, roles2); // Attach the new principal object to the current HttpContext object Context.User = principal; }
public bool CheckAuthentication() { HttpCookie cookie = Request.RequestContext.HttpContext.Request.Cookies[Constants.COOKIE_CRM]; if (cookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); FormsIdentity identity = new FormsIdentity(ticket); UserData udata = UserData.CreateUserData(ticket.UserData); AuthenticationProjectPrincipal principal = new AuthenticationProjectPrincipal(identity, udata); //return CommonFunc.CheckAuthorized(190, (int)Modules.Question, (int)Permissions.Read); return CommonFunc.CheckAuthorized(principal.UserData.UserID, (int)Modules.Question, (int)Permissions.Read); } return false; }