简体   繁体   中英

Validate windows user before logged in MVC application

My requirement is to get the username of windows system user and validate that username with the application database. If the user exists in the table I have to navigate him to the homepage of the application. I have tried below code but User.Identity.IsAuthenticated is always false. How can I set User.Identity.IsAuthenticated for the windows user?

[AllowAnonymous]
[Authorize]
public class AccountController : BaseController
{

    private ViewboxUserManager UserManager { get { return Request.GetOwinContext().GetUserManager<ViewboxUserManager>(); } }


    public ActionResult Login(string returnUrl)
    {
        var adUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
        string windowsUser = (adUser.IndexOf(@"\") >= 0) ? adUser.Substring(adUser.IndexOf(@"\") + 1) : adUser;

        var user = UserManager.FindByNameAsync(windowsUser);

        if (user != null)
        {
            bool isLoginPage = false;
            if (Request.Cookies["IsLogin"] != null) isLoginPage = true;
            if (isLoginPage && User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Dashboard", new { area = "" });
            }
        }

        ViewBag.ReturnUrl = returnUrl;
        ViewBag.Title = "Login";
        return View();
    }
}

I have resolved it like this:

var userIdentity = await CreateUserIdentityAsync(user).WithCurrentCulture();
                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                AuthenticationManager.SignIn(userIdentity);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM