简体   繁体   English

告诉MVC5用户已通过Active Directory登录/注销

[英]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. 我正在构建仅在Intranet设置中使用的MVC5站点。 Since employees here share PCs when working, I need to incorporate login/logoff functionality into the site. 由于这里的员工在工作时共享PC,因此我需要将登录/注销功能合并到站点中。 The application will authenticate against Active Directory. 该应用程序将根据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. 但是,当页面使用户返回returnUrl时, User.Identity.IsAuthenticatedRequest.IsAuthenticated都为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? 如何告知MVC用户已成功登录?

From Web.config: 从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. 更新默认的MVC代码为标准的Internet登录创建此方法。 I am attempting to figure out how to generate a ClaimsIdentity object so I can also utilize it. 我试图弄清楚如何生成ClaimsIdentity对象,以便也可以利用它。

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. 我不确定您使用的是ntlm身份验证的正确方法。 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. 基本上,您可以向站点添加“以其他用户身份登录”按钮,并向其添加事件处理程序,该按钮将返回到用户401响应,进而触发客户端上的Windows登录弹出窗口以输入凭据。 Please take a look at this post. 请看看这篇文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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