Application use windows authentication and request is : If user is not in AD but is in DB switch from windows authentication to web login screen. After that I have logic for web login screen and that's works like a charm.
My question is, is it possible to manipulate with windows authentication? What is best way to solve problem like this?
This is current logic for AD login:
public async Task<IActionResult> AdLogin(string returnUrl)
{
if (User.Identity.Name == null)
{
return Unauthorized(); //Return to login (if anonymous login is enabled, User can be null)
}
ActiveDirectoryUserDto userAdDetails = _activeDirectory.GetAdUserLDAP();
Account userDB = _accountService.GetAccountByUsername(userAdDetails.UserName);
if (userDB != null && _accountService.CanLogin(userDB))
{
returnUrl = string.IsNullOrEmpty(returnUrl) || returnUrl == "/" || returnUrl == "/Home/Index" ? userDB.DefaultUrl : returnUrl;
/*ADD CLAIMS*/
ClaimsIdentity identity = _accountService.GenerateClaimsIdentityForUser(userDB, true);
/*IDENTITY LOGIN*/
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
// Set language info in cookie
LanguageCountry userLanguageCountry = _accountService.GetLanguageCountryForUser(userDB.LanguageCountryId);
Response.Cookies.Append("CultureValues", userLanguageCountry.LanguageSuffix);
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(userLanguageCountry.LanguageCountryCode)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
// Create session
short sessionId = _accountService.CreateSession(userDB.AccountId, userDB.UserName, Request.Headers, HttpContext.Connection.RemoteIpAddress.ToString());
HttpContext.Session.SetInt32("SessionID", sessionId);
// Update account login data
_accountService.UpdateAccountLoginData(userDB);
return Redirect(returnUrl);
}
else
{
return Unauthorized();
}
}
I tried to catch username and add logic, but recently i read about how windows authentication is hard to controll.