ASP. NET Core Login / Logout

 

public class LoginController : Controller
	{
		private readonly string defaultAction = "ListServers";
		private readonly string defaultController = "Server";
		private readonly IUserDA _userDA;
		private readonly AppSettings _appSettings;
 
		public LoginController(IUserDA userDA, IOptionsSnapshot<AppSettings> appSettings)
		{
			this._userDA = userDA;
			this._appSettings = appSettings.Value;
		}
 
		[HttpGet]
		public IActionResult Index()
		{
			if (this._userDA.IsUserLoggedIn())
				return RedirectToAction(defaultAction, defaultController);
			
			HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
			return View(new UserDTO());
		}
 
		[HttpPost]
		public IActionResult Index(UserDTO userBO)
		{
			ModelState.Remove("Role");
			var ok = false;
			var result = "";
			try
			{
				if (ModelState.IsValid)
				{
					(bool authorized, string token, string role, string error) = this._userDA.ValidateCredentials(userBO);
					if (!String.IsNullOrEmpty(token))
					{
						ok = true;
						var claims = new List<Claim>
					{
						new Claim(ClaimTypes.Name, userBO.UserId),
						new Claim(ClaimTypes.Authentication, token),
						new Claim(ClaimTypes.Role, role)
					};
 
						var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
						var principal = new ClaimsPrincipal(identity);
 
						var props = new AuthenticationProperties
						{
							IsPersistent = true,
							ExpiresUtc = DateTime.Now.AddMinutes(this._appSettings.TokenExpiresIn)
						};
 
						// This creates a cookie and passes it back to the client and the client browser sends this cookie in all the subsequent calls.
						HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props).Wait();
					}
					else if (!String.IsNullOrEmpty(error))
						result = error;
					else
						result = "Invalid Credentials";
				}
				else
					result = String.Join(',', ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage));
			}
			catch (Exception ex)
			{
				result = ex.Message;
			}
 
			return Json(new { ok, message = result });
		}
 
		public IActionResult Logout()
		{
			HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
			return RedirectToAction("Index");
		}
	}

Comments