• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Security.FormsAuthenticationTicket类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Web.Security.FormsAuthenticationTicket的典型用法代码示例。如果您正苦于以下问题:C# FormsAuthenticationTicket类的具体用法?C# FormsAuthenticationTicket怎么用?C# FormsAuthenticationTicket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



FormsAuthenticationTicket类属于System.Web.Security命名空间,在下文中一共展示了FormsAuthenticationTicket类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: LogOn

        public ActionResult LogOn(LoginModel model, string returnUrl)
        {
            ViewBag.Message = "Please enter username and password for login.";
            if (ModelState.IsValid)
            {
                User user = ValidateUser(model.username, model.password);

                if (user != null)
                {

                    var authTicket = new FormsAuthenticationTicket(1, model.username, DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe,
                                                                "1");
                    string cookieContents = FormsAuthentication.Encrypt(authTicket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                    {
                        Expires = authTicket.Expiration,
                        Path = FormsAuthentication.FormsCookiePath
                    };
                    Response.Cookies.Add(cookie);

                    if (!string.IsNullOrEmpty(returnUrl))
                        Response.Redirect(returnUrl);

                    return RedirectToAction("Index", "Dashboard");
                }
                else
                {
                    ViewBag.Message = "The user name or password provided is incorrect. Please try again";
               }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
开发者ID:aminul,项目名称:NewTest,代码行数:34,代码来源:LoginController.cs


示例2: SignIn

        public virtual void SignIn(Customer customer, bool createPersistentCookie)
        {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
                now,
                now.Add(_expirationTimeSpan),
                createPersistentCookie,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            _httpContext.Response.Cookies.Add(cookie);
            _cachedCustomer = customer;
        }
开发者ID:kouweizhong,项目名称:NopCommerce,代码行数:31,代码来源:FormsAuthenticationService.cs


示例3: LogOn

        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {

            Session["Notification"] = "";
            if (ModelState.IsValid)
            {
                KIREIP.Core.Manager.UserManager CM = new KIREIP.Core.Manager.UserManager();
                KIREIP.Core.DAL.Login usr = CM.LoginUser(model.UserName, model.Password);
                if (usr != null)
                {
                    FormsAuthentication.Initialize();
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, usr.UserName.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, FormsAuthentication.FormsCookiePath);
                    string hash = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                    if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
                    Response.Cookies.Add(cookie);
                    if ((!String.IsNullOrEmpty(returnUrl)) && returnUrl.Length > 1)
                        return Redirect(returnUrl);
                    else
                    {
                        return RedirectToAction("Index", "Message");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Incorrect user name or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
开发者ID:Tia-Demo,项目名称:KendoVS4,代码行数:32,代码来源:AccountController.cs


示例4: login

        private void login(string userName, string password)
        {
            Model.User userObj = Model.Repositories.UsersRepository.GetUserByCredentials(userName, password);
            if (userObj == null)
                return;

            int userID = userObj.ID;
            string userRoles = "";
            foreach (Model.UserRole userRole in userObj.UserRoles)
            {
                if (userRoles == "")
                    userRoles = userRole.ID.ToString();
                else
                    userRoles += "," + userRole.ID.ToString();
            }

            if (userRoles == "")
                return;

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userID.ToString(), DateTime.Now,
                                                                             DateTime.Now.AddMinutes(30), false,
                                                                             userRoles,
                                                                             FormsAuthentication.FormsCookiePath);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));

            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
            Response.Cookies.Add(cookie);

            string returnUrl = Request.QueryString["ReturnUrl"];
            if (String.IsNullOrEmpty(returnUrl))
                returnUrl = "Default.aspx";
            Response.Redirect(returnUrl);
        }
开发者ID:AdhamMowafy,项目名称:AlHuda,代码行数:34,代码来源:Login.aspx.cs


示例5: Login

        /// <summary>
        /// �û���¼����
        /// </summary>
        /// <param name="username">�û���</param>
        /// <param name="roles">�û���ɫ</param>
        /// <param name="isPersistent">�Ƿ�־�cookie</param>
        public static void Login(string username, string roles, bool isPersistent)
        {
            DateTime dt = isPersistent ? DateTime.Now.AddMinutes(99999) : DateTime.Now.AddMinutes(60);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                                                1, // Ʊ�ݰ汾��
                                                                                username, // Ʊ�ݳ�����
                                                                                DateTime.Now, //����Ʊ�ݵ�ʱ��
                                                                                dt, // ʧЧʱ��
                                                                                isPersistent, // ��Ҫ�û��� cookie
                                                                                roles, // �û����ݣ�������ʵ�����û��Ľ�ɫ
                                                                                FormsAuthentication.FormsCookiePath);//cookie��׷��

            //ʹ�û�����machine key����cookie��Ϊ�˰�ȫ����
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); //����֮���cookie

            //��cookie��ʧЧʱ������Ϊ��Ʊ��tikets��ʧЧʱ��һ��
            HttpCookie u_cookie = new HttpCookie("username", username);
            if (ticket.IsPersistent)
            {
                u_cookie.Expires = ticket.Expiration;
                cookie.Expires = ticket.Expiration;
            }

            //���cookie��ҳ��������Ӧ��
            HttpContext.Current.Response.Cookies.Add(cookie);
            HttpContext.Current.Response.Cookies.Add(u_cookie);
        }
开发者ID:Andy-Yin,项目名称:MY_OA_RM,代码行数:34,代码来源:User.cs


示例6: SignIn

        public ActionResult SignIn(SignInViewModel logInViewModel)
        {
            if (ModelState.IsValid)
            {
                string errorMessage;
                User user = _accountService.ValidateUser(logInViewModel.UserName, logInViewModel.Password, out errorMessage);
                if (user != null)
                {
                    SimpleSessionPersister.Username = user.Username;
                    SimpleSessionPersister.Roles = user.Roles.Select(x => x.Name).ToList();
                    if (logInViewModel.StayLoggedIn)
                    {
                        FormsAuthenticationTicket formsAuthenticationTicket = new FormsAuthenticationTicket(SimpleSessionPersister.Username, true, 10080);
                        string encrypt = FormsAuthentication.Encrypt(formsAuthenticationTicket);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypt);
                        Response.Cookies.Add(cookie);
                    }

                    return RedirectToAction("Index", "Feed");
                }
                ModelState.AddModelError(string.Empty, errorMessage);
            }

            return View();
        }
开发者ID:ekutsenko-softheme,项目名称:clouduri,代码行数:25,代码来源:ProfileController.cs


示例7: Authenticate

 public HttpResponseMessage Authenticate()
 {
     var credentials = Request.Content.ReadAsStringAsync().Result;
     var postData = JObject.Parse(credentials);
     var username = postData["Username"].ToString().Trim();
     var password = postData["Password"].ToString().Trim();
     var match = DynamoDBConnection.Instance.GetUser(username);
     if (match == null) {
         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unrecognized username or password");
     }
     var data = JObject.Parse(match["UserInfo"]);
     var hashedPassword = data["Password"].ToString();
     bool authenticated;
     if (hashedPassword != "test") {
         byte[] charArray = hashedPassword.Select(i => (byte)i).ToArray();
         var passwordHash = new PasswordHash(charArray);
         authenticated = passwordHash.Verify(password);
     } else {
         authenticated = true;
     }
     if (authenticated) {
         var toReturn = new HttpResponseMessage(HttpStatusCode.OK);
         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(username, true, 525600);
         var sessionKey = FormsAuthentication.Encrypt(ticket);
         toReturn.Headers.Add("Set-Cookie", string.Format("session_id={0}; Path=/", sessionKey));
         toReturn.Headers.Add("Set-Cookie", string.Format("user_id={0}; Path=/", username));
         toReturn.Content = new StringContent(sessionKey.ToString());
         return toReturn;
     } else {
         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unrecognized username or password");
     }
 }
开发者ID:Amichai,项目名称:Annotation,代码行数:32,代码来源:AuthenticationController.cs


示例8: btnLogin_Click

        protected void btnLogin_Click(object sender, EventArgs e)
        {
               Users _loginUser = _dal.VerifyPassword(txtUserName.Text, txtPassword.Text);

               if (_loginUser == null)
                   lblerror.Text = "Invalid Login";
               else
               {


                   UserData userData = new UserData
                   {
                       fullName = _loginUser.firstName,
                       userName = _loginUser.LoweredUserName,
                       userId = _loginUser.UserId
                   };
                   
 
                   string[] roles = new string[3];

                   if (_loginUser.canAdd == true)
                       roles[0] = "canAdd";
                   if (_loginUser.canDelete == true)
                       roles[1] = "canDelete";
                   if (_loginUser.canEdit == true)
                       roles[2] = "canEdit";

                   string _roles = String.Join(",", roles);

                   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                     1,                                     // ticket version
                     _loginUser.UserName,                              // authenticated username
                     DateTime.Now,                          // issueDate
                     DateTime.Now.AddMinutes(30),           // expiryDate
                      true,                          // true to persist across browser sessions we want to be always for end user unless they log out.
                     _roles,                 // can be used to store additional user data
                     FormsAuthentication.FormsCookiePath);  // the path for the cookie

                   // Encrypt the ticket using the machine key
                   string encryptedTicket = FormsAuthentication.Encrypt(ticket);

                   // Add the cookie to the request to save it
                   HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                   cookie.HttpOnly = true;
                   Response.Cookies.Add(cookie);

                   lblerror.Text = "Success!";

                   // if its a player throw them into front end other wise fire them into the back end
                   if (_loginUser.accountType == Constants.playerGuid &&  _loginUser.accountType == Constants.adminGuid)
                   {
                       Response.Redirect("~/dashboard/dashboard.aspx");

                   }
                   else if (_loginUser.accountType == Constants.teamGuid && _loginUser.accountType == Constants.leagueGuid && _loginUser.accountType == Constants.clubGuid)
                   {
                       Response.Redirect("~/Backdoor/default.aspx");
                   }
               }
        }
开发者ID:cmsni,项目名称:skylarkarean,代码行数:60,代码来源:dashboardlogin.aspx.cs


示例9: Login

        public ActionResult Login(LoginViewModel viewModel)
        {
            var apresentador = new LoginApresentador();
            var requisicao = new LoginRequisicao
            {
                Email = viewModel.Email,
                Senha = viewModel.Senha
            };

            this.loginExecutor.Apresentador = apresentador;
            this.loginExecutor.Executar(requisicao);

            if (apresentador.UsuarioExiste)
            {
                //create the authentication ticket
                var authTicket = new FormsAuthenticationTicket(
                  1,
                  viewModel.Email,  //user id
                  DateTime.Now,
                  DateTime.Now.AddMinutes(20),  // expiry
                  true,  //true to remember
                  "", //roles
                  "/"
                );

                //encrypt the ticket and add it to a cookie
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
                Response.Cookies.Add(cookie);
                return RedirectToAction("Index", "Blog");
            }

            return View();
        }
开发者ID:BrenoSarkis,项目名称:Blog,代码行数:33,代码来源:AdministradorController.cs


示例10: Login

        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var currentUser = clientService.GetClientByLoginAndPassword(model.Login, model.Password);

                if(currentUser != null)
                {
                    string name;
                    if (currentUser.FirstName != null)
                        name = currentUser.FirstName + " " + currentUser.LastName;
                    name = currentUser.Login;

                    var authTicket = new FormsAuthenticationTicket(
                        1,
                        currentUser.UserId.ToString(),
                        DateTime.Now,
                        DateTime.Now.AddMinutes(60),
                        true,
                        name
                        );

                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    HttpContext.Response.Cookies.Add(authCookie);
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(model);
        }
开发者ID:PavloRomanov,项目名称:TrainingProjects,代码行数:30,代码来源:ClientController.cs


示例11: Index

        public ActionResult Index(BiscuitChief.Models.Login login, string ReturnUrl = "")
        {
            if (ModelState.IsValid)
            {

                bool isvalidlogin = Models.Login.ValidateLogin(login.UserName, login.Password);

                if (isvalidlogin)
                {
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, login.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, "");
                    String cookiecontents = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiecontents) { Expires = authTicket.Expiration, Path = FormsAuthentication.FormsCookiePath };
                    Response.Cookies.Add(cookie);

                    if (!String.IsNullOrEmpty(ReturnUrl))
                    { return Redirect(ReturnUrl); }
                    else
                    { return Redirect("/"); }
                }
                else
                {
                    FormsAuthentication.SignOut();
                    Session.Clear();
                }
            }

            return View(login);
        }
开发者ID:BiscuitChief,项目名称:BiscuitLand,代码行数:28,代码来源:LoginController.cs


示例12: LogIn

        public void LogIn(string username, string password)
        {
            if (username == "lvs" && password == "[email protected]")
            {
                FormsAuthentication.Initialize();
                FormsAuthentication.SetAuthCookie(username, false);
                var ticket = new FormsAuthenticationTicket(
                   1, // Ticket version
                   username, // Username associated with ticket
                   DateTime.Now, // Date/time issued
                   DateTime.Now.AddMinutes(30), // Date/time to expire
                   true, // "true" for a persistent user cookie
                   "", // User-data, in this case the roles
                   FormsAuthentication.FormsCookiePath);// Path cookie valid for

                // Encrypt the cookie using the machine key for secure transport
                string hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(
                   FormsAuthentication.FormsCookieName, // Name of auth cookie
                   hash); // Hashed ticket

                // Set the cookie's expiration time to the tickets expiration time
                if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

                // Add the cookie to the list for outgoing response
                Response.Cookies.Add(cookie);

            }
        }
开发者ID:provenstyle,项目名称:SignalRChat,代码行数:29,代码来源:AccountController.cs


示例13: Index

        public ActionResult Index(LoginViewModel login)
        {
            if (!ModelState.IsValid) return View();

            if (!userRepo.ValidateUser(login))
            {
                ModelState.AddModelError("", "Incorrect username or password");

                return View();
            }

            var authTicket = new FormsAuthenticationTicket(
                    1,
                    login.UserName,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(20),  // expiry
                    login.RememberMe,
                    "", //roles
                    "/"
            );

            //encrypt the ticket and add it to a cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
            Response.Cookies.Add(cookie);

            return Redirect("UserHome");
        }
开发者ID:chisinus,项目名称:FormBuddy,代码行数:27,代码来源:HomeController.cs


示例14: AuthenticateUser

        public static void AuthenticateUser(string userName, int userId, string firstName, bool createPersistenctCookie)
        {
            try
            {
                var userData = new WarehouseManagementUserData()
                {
                    UserId = userId,
                    UserName = userName,
                    FirstName = firstName
                };

                var userDataString = WarehouseManagementUserData.Serialize(userData);
                var authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistenctCookie);

                var ticket = FormsAuthentication.Decrypt(authCookie.Value);
                var extendedTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);

                authCookie.Value = FormsAuthentication.Encrypt(extendedTicket);

                HttpContext.Current.Response.Cookies.Add(authCookie);
            }
            catch (Exception e)
            {
                throw new ProviderException(string.Format("Failed to authenticate user {0}.", userName), e);
            }
        }
开发者ID:RytisCapas,项目名称:InventoryManagement,代码行数:26,代码来源:WarehouseManagementAuthentication.cs


示例15: OnPreSendRequestHeaders

        private void OnPreSendRequestHeaders(object sender, EventArgs eventArgs)
        {
            var app = (HttpApplication)sender;

            try
            {
                var ctx = ContextRegistry.GetContext();
                var sessao = (Sessao)ctx.GetObject("Sessao");

                if (!sessao.IsAutenticado)
                {
                    FormsAuthentication.SignOut();
                    return;
                }

                var ticket = new FormsAuthenticationTicket(
                    1,
                    sessao.Usuario.UID.ToString(),
                    DateTime.Now,
                    DateTime.Now.AddMinutes(20),
                    false,
                    sessao.Organizacao.UID.ToString());

                var cookie = FormsAuthentication.GetAuthCookie(sessao.Usuario.UID.ToString(), false);
                cookie.Value = FormsAuthentication.Encrypt(ticket);
                app.Context.Response.SetCookie(cookie);

            }
            finally 
            {
                _log.Warn(app.Request.Path + " - " + app.Response.StatusCode);
            }
        }
开发者ID:GDATRINDADE,项目名称:lexcard.net,代码行数:33,代码来源:SegurancaModule.cs


示例16: CreateLoginUserTicket

        /// <summary>  
        /// 创建登录用户的票据信息  
        /// </summary>  
        /// <param name="strUserName"></param>  
        public static string CreateLoginUserTicket(string userId)
        {
            DateTime loginTime = DateTime.Now;//用户的登录时间
            //构造Form验证的票据信息
            ///把登录时间和用户ID写进Cookie中,后面可以用于判断用户的登录时间间隔
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.AddMinutes(90),
                true, string.Format("{0}:{1}", userId, loginTime), FormsAuthentication.FormsCookiePath);

            string ticString = FormsAuthentication.Encrypt(ticket);

            //把票据信息写入Cookie和Session
            //SetAuthCookie方法用于标识用户的Identity状态为true
            HttpContext.Current.Response.Cookies.Add(new HttpCookie("UserLoginCookieToken", ticString));
            FormsAuthentication.SetAuthCookie(userId, true);
            HttpContext.Current.Session["USER_LOGON_TICKET"] = ticString;

            //重写HttpContext中的用户身份,可以封装自定义角色数据;
            //判断是否合法用户,可以检查:HttpContext.User.Identity.IsAuthenticated的属性值
            string[] roles = ticket.UserData.Split(',');
            IIdentity identity = new FormsIdentity(ticket);
            IPrincipal principal = new GenericPrincipal(identity, roles);
            HttpContext.Current.User = principal;

            return ticString;//返回票据
        }
开发者ID:gowhy,项目名称:MicroWish,代码行数:29,代码来源:AutheTicketManager.cs


示例17: Authenticate

        public bool Authenticate(string username, string password)
        {
            _userContext = _clientDataAccess.LogIn(username, ClassLib.DataStructures.HashClass.CreateFirstHash(password, username));

            if (_userContext != null)
            {
                const int timeout = 60;
                var ticket = new FormsAuthenticationTicket(
                    1,
                    username,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(timeout),
                    true,
                    _userContext.Id.ToString()
                    );
                var encrypted = FormsAuthentication.Encrypt(ticket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);

                HttpContext.Current.Response.Cookies.Add(cookie);

                _authenticationCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

                return true;
            }

            return false;
        }
开发者ID:hanruby,项目名称:WaiterManagement,代码行数:27,代码来源:FormsAuthProvider.cs


示例18: LogOn

        public ActionResult LogOn(T_Manager model)
        {
            //判断是否Model是否有错误信息弹出,如果有错误为false 没则为true
            if (ModelState.IsValid)
            {
                T_Manager manager = manager_service.Login(model).FirstOrDefault();
                if (manager != null)
                {
                    //1.保存登陆名,如果设置了 [Authorize],则那些视图需要登陆成功后才能访问
                    //FormsAuthentication.SetAuthCookie(manager.mana_login_name.ToString(), false);

                    ////2.存储登陆名外,再添加角色权限
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1, // 版本号。 
                        manager.mana_id.ToString(), // 与身份验证票关联的用户ID。 
                        DateTime.Now, // Cookie 的发出时间。 
                        DateTime.Now.AddMinutes(15),// Cookie 的到期日期。 
                        false, // 如果 Cookie 是持久的,为 true;否则为 false。 
                        manager.mana_role.ToString());//将存储在 Cookie 中的用户定义数据。 
                    string encryptedTicket = FormsAuthentication.Encrypt(ticket);//加密
                    //存入Cookie 
                    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    Response.Cookies.Add(authCookie);

                    return RedirectToAction("Home", "Main");
                }
                else
                {
                    ViewBag.SubmitError = "账号密码错误";
                }
            }
            return View();
        }
开发者ID:turr,项目名称:MyWallet,代码行数:33,代码来源:GlobalController.cs


示例19: RedirectFromLogin

        public static void RedirectFromLogin(string login, IEnumerable<RestResponseCookie> cookies)
        {
            if (cookies == null)
                throw new ArgumentNullException("cookies");

            cookies = cookies.ToArray();

            var data = JsonConvert.SerializeObject(cookies.ToDictionary(c => c.Name, c => c.Value));

            var cookie = FormsAuthentication.GetAuthCookie(login, false);

            var sourceTicket = FormsAuthentication.Decrypt(cookie.Value);

            if (sourceTicket == null)
                throw new ApplicationException("Unable to decrypt authentication");

            var expiration = cookies.Select(c => c.Expires)
                                    .Where(exp => exp > DateTime.Today.AddYears(-1) && exp < DateTime.Today.AddYears(1))
                                    .Concat(new[] {sourceTicket.Expiration})
                                    .Min();

            var ticket = new FormsAuthenticationTicket(
                sourceTicket.Version, sourceTicket.Name, sourceTicket.IssueDate,
                expiration, false, data);

            cookie.Value = FormsAuthentication.Encrypt(ticket);

            Response.SetCookie(cookie);
            var redirectUrl = FormsAuthentication.GetRedirectUrl(login, sourceTicket.IsPersistent);
            Response.Redirect(redirectUrl);
        }
开发者ID:rhartzog,项目名称:YouTrackBurnDown,代码行数:31,代码来源:CookieAuthenticator.cs


示例20: Login

        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var login = model.Login;
                var passwordHash = _cryptoProvider.GetHash(model.Password, Salt);

                var userEntity =
                    _dContext.Users.FirstOrDefault(x => x.Login == login && x.PasswordHash == passwordHash);

                if (userEntity != null)
                {
                    var authTicket = new FormsAuthenticationTicket(
                        1,
                        login,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                        true,
                        userEntity.UserRole.ToString()
                        );
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                    return RedirectToAction("Index", "Admin");
                }
                else
                {
                    ModelState.AddModelError("", "The user login or password provided is incorrect.");
                }
            }
            return View(model);
        }
开发者ID:Kokcuk,项目名称:AdveChan,代码行数:32,代码来源:AccountController.cs



注:本文中的System.Web.Security.FormsAuthenticationTicket类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Security.MembershipProvider类代码示例发布时间:2022-05-26
下一篇:
C# Routing.RouteData类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap