示例#1
0
        protected void SetAuthCookie(UserModel model, ResultAutentication userAuthentication)
        {
            FormsAuthentication.SetAuthCookie(model.Email, false);
            var    authTicket      = new FormsAuthenticationTicket(1, userAuthentication.User.UserName, DateTime.Now, DateTime.Now.AddMinutes(20), false, Convert.ToString(APLICATION));
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            HttpContext.Response.Cookies.Add(authCookie);
        }
        public async Task <ActionResult> Login(UserModel model, string returnUrl)
        {
            //TODO - VERIFICAR REGRA DE returnUrl
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            ResultAutentication userAuthentication = null;

            var user = new { Email = model.Email, Password = model.Password, Aplication = APLICATION };

            // HTTP POST
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["url-api-client"]);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // HTTP POST
                HttpResponseMessage response = await client.PostAsJsonAsync("api/Authentication/Login", user);

                if (!response.IsSuccessStatusCode)
                {
                    var critica = response.Content.ReadAsAsync <ValidationError>().Result;
                    if (critica != null)
                    {
                        ViewBag.MessageError = critica.Message;
                    }
                    else
                    {
                        ViewBag.MessageError = Resources.Language.ErrorTryLogIn;
                    }
                    return(View(model));
                }

                userAuthentication = await response.Content.ReadAsAsync <ResultAutentication>();

                TOKEN = userAuthentication.Token;
            }

            //Set usuário logado
            SetAuthCookie(model, userAuthentication);

            return(RedirectToAction("Index", "Main"));
        }