Пример #1
0
        public async Task <IActionResult> SignIn([Bind("Email", "Password")] Login login, string returnUrl = null)
        {
            await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            AuthService.RemoveCookie(HttpContext, AppSettings.CookieTokenName);
            AuthService.RemoveCookie(HttpContext, AppSettings.CookieRefreshName);

            JwtToken jwtToken;

            jwtToken = await _accountManagementService.SignIn(login);

            if (jwtToken == null)
            {
                CheckUnexpectedErrors();
                ViewData["ReturnUrl"] = returnUrl;
                return(View(login));
            }

            string serializedObject = JsonConvert.SerializeObject(login, Formatting.Indented, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.Name, jwtToken.Name));
            claims.Add(new Claim(ClaimTypes.Surname, jwtToken.Surname));
            claims.Add(new Claim(ClaimTypes.Email, jwtToken.Email));

            for (int i = 0; i < jwtToken.Roles.Length; i++)
            {
                claims.Add(new Claim(ClaimTypes.Role, jwtToken.Roles[i]));
            }

            claims.Add(new Claim(ClaimTypes.Hash, AuthService.EncryptValue(serializedObject)));

            var identity  = new ClaimsIdentity(claims);
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.FromUnixTimeSeconds(DateTimeOffset.MaxValue.ToUnixTimeSeconds()),//FromUnixTimeSeconds(jwtToken.ExpirationDateSeconds),
                IsPersistent = true,
                AllowRefresh = false
            });

            // Token
            AuthService.AddToCookie(HttpContext, AppSettings.CookieTokenName, jwtToken.Jwt, new CookieOptions()
            {
                Expires = DateTimeOffset.FromUnixTimeSeconds(jwtToken.ExpirationDateSeconds)
            });

            // Refresh token
            AuthService.AddToCookie(HttpContext, AppSettings.CookieRefreshName, "", new CookieOptions()
            {
                Expires = DateTimeOffset.FromUnixTimeSeconds(DateTimeOffset.UtcNow.ToUnixTimeSeconds() + Convert.ToInt64(TimeSpan.FromMinutes(AppSettings.CookieRefreshTimeInMinutes).TotalSeconds))
            });

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return(Redirect(returnUrl));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
        }