简体   繁体   中英

Telling MVC5 that the user has logged in/out via Active Directory

I'm constructing an MVC5 site that is used in an intranet-only setting. Since employees here share PCs when working, I need to incorporate login/logoff functionality into the site. The application will authenticate against Active Directory.

I have the authentication here working. However, when the page brings the user back to the returnUrl, both User.Identity.IsAuthenticated and Request.IsAuthenticated are both false. This leads to the home page still offering the option to "Sign In" even though they already have successfully gone through that motion before.

How do I tell MVC that the user is signed on successfully?

From Web.config:

<authentication mode="Windows" />

From the Account Controller:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        using (var pc = new PrincipalContext(ContextType.Domain))
        {
            if (pc.ValidateCredentials(model.UserName, model.Password, ContextOptions.Negotiate | ContextOptions.SimpleBind))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }
    }

Update The default MVC code creates this method for a standard internet login. I am attempting to figure out how to generate a ClaimsIdentity object so I can also utilize it.

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

I'm not sure that your are doing it the correct way for ntlm authentication. Basically you can add "Sign In As Different User" button to your site and event handler to it which will return to user 401 response which in turn will fire windows login popup on client to enter credentials. Please take a look at this post.

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