57

How do you logout when using Windows authentication in ASP.NET like this web.config?

<authentication mode="Windows" />

I've already tried the following unsuccessfully. It redirects, but does not log out the user.

void logoutButton_Click(object sender, EventArgs e) {
    HttpContext.Current.Session.Clear();
    HttpContext.Current.Session.Abandon();
    ViewState.Clear();
    FormsAuthentication.SignOut();
    Response.Redirect("/");
}

Background Info:

I have to use Windows authentication because I need to impersonate the identity using Active Directory to gain access to local files. And I cannot impersonate using Forms authentication because the HttpContext.Current.User.Identity won't be a WindowsIdentity. Impersonate using Forms Authentication

Community
  • 1
  • 1
Robert
  • 14,999
  • 4
  • 39
  • 46
  • It appears impersonating a user via Forms authentication is possible after all. See http://stackoverflow.com/a/11873754/359765 – bgh Jul 01 '16 at 12:21

9 Answers9

42

No server-side logout button will work when using "Windows" authentication. You must use "Forms" authentication if you want a logout button, or close the user's browser.

Robert
  • 14,999
  • 4
  • 39
  • 46
24

For IE browsers only, you can use the following javascript to logout the user if using Windows Authentication. (Note: closing the browser isn't required, but recommended since the user might be using a non-IE browser).

If the user clicks "No" to close the browser, then the user will be prompted for a username/password if they attempt to access a page on the site that requires authentication.

try {
   document.execCommand("ClearAuthenticationCache");
}
catch (e) { }
window.close();

This code was taken from SharePoint's Signout.aspx page.

Garry English
  • 5,070
  • 1
  • 36
  • 23
  • Brilliant! I was hoping this would cause an exception in non-IE browsers so that in the catch block we could display an alert to non-IE users with further instructions. There's an exception in FF but not Chrome unfortunately. So, would closing the window be enough? Not sure. Quick tests suggest it might be in Chrome and FF but I know for sure that with IE (without the above script) all windows need to be closed before the authentication is cleared. – Stephen Kennedy Feb 21 '12 at 15:56
  • 1
    It's also worth pointing out that according to this link the above command clears ALL authentication data not just for the site which requested it http://msdn.microsoft.com/en-us/library/ms536979.aspx – Stephen Kennedy Feb 21 '12 at 16:05
  • Brilliant! I changed the code to redirect as describe in here - http://stackoverflow.com/questions/12742319/formsauthentication-signout-not-working-for-iis-windows-authentication-op – Jack Oct 09 '12 at 05:16
15

Windows authentication works at the IIS level by passing your Windows authentication token. Since authentication occurs at the IIS level you cannot actually log out from application code. However, there seems to be an answer to your problem here. It is the second question addressed and essentially involves using Forms Authentication and the LogonUser Windows api.

tribus
  • 1,110
  • 1
  • 9
  • 27
  • Awesome! Thanks for the link to that article. Exactly what I wanted for my other question. Please post that to my other question and I'll check you off as answered on that one. – Robert Jul 01 '09 at 05:27
6

I had a SharePoint application with Windows authentication, I needed automatic logout after 15 minutes. I mixed up some codes and here is the result. it works in IE properly.

<script type="text/javascript">
var t;
window.onload = resetTimer;
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;

function logout() {

    try {
        document.execCommand("ClearAuthenticationCache");
        window.location.href = window.location.protocol.replace(/\:/g, '') + "://" + window.location.host + "/_layouts/customlogin14.aspx";
    }
    catch (e) { }

}

function resetTimer() {
    window.clearTimeout(t);
    t = window.setTimeout(logout, 900000);
} 

put these codes in your master page, after 15 mins idle time you will see the login page. hope this help somebody

CoderDennis
  • 13,642
  • 9
  • 69
  • 105
Eric
  • 750
  • 9
  • 14
3

I have this working using JavaScript in both IE and Firefox, though it logs you out of everything you're logged into in IE. It sort of works in Safari, but Safari throws up a phishing warning. Doesn't work in Opera.

try {
    if (document.all) {
        document.execCommand("ClearAuthenticationCache");
        window.location = "/";
    } else {
        window.location = "http://logout:logout@example.com";
    }
} catch (e) {
    alert("It was not possible to clear your credentials from browser cache. Please, close your browser window to ensure that you are completely logout of system.");
    self.close();
}
Word Rearranger
  • 1,306
  • 1
  • 16
  • 25
Scott
  • 6,411
  • 6
  • 39
  • 43
1

The best answers I have seen are found in related StackOverFlow questions:

Is there a browser equivalent to IE's ClearAuthenticationCache?

and

Logging a user out when using HTTP Basic authentication

Basically you need to send a AJAX request to the server with invalid credentials and have the server accept them.

Community
  • 1
  • 1
AnthonyVO
  • 3,821
  • 1
  • 36
  • 41
  • While technically you were talking about valid options, in reality that heavily depends on browser side settings. For example, if login prompts are suppressed on browser side, the users might not have a chance to enter credentials of another Windows/AD user. – Lex Li Feb 15 '23 at 17:59
0

Had alot of trouble with this, below is the code that works, hopefully someone finds it useful.

foreach (var cookie in Request.Cookies.Keys)
{
    Response.Cookies.Delete(cookie);
}


await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);


Response.Cookies.Append("EdgeAccessCookie", "", new Microsoft.AspNetCore.Http.CookieOptions()
{
    Path = "/",
    HttpOnly = true,
    SameSite = SameSiteMode.Lax, Expires = DateTime.Now.AddDays(-1)
});


Response.Redirect("https://adfs.[sitename].com/adfs/ls?wa=wsignout1.0");
Trent Stewart
  • 841
  • 1
  • 9
  • 18
  • 3
    This is assuming ADFS through Windows Identity Foundation.... NTLM Windows Auth isn't always using ADFS. Just using basic NTLM auth, none of this is relevant. – Ryan Mann Aug 15 '19 at 18:33
0

You cannot log out programically if Windows Auth is enabled, I ended up with having a logout link on my webpage which upon click will present the message "You are logged out, but to completely log out you need to close the browser".

Another change was in my Domain Controller => Group Policy => User Config => Internet Settings => Local Intranet => Custom Level => Security => USer Authentication => "Prompt for user name and Password" option.

The user is now presented with a Windows Auth dialog box every time a new browser window is opened, hence login is triggered.

Anurag
  • 368
  • 4
  • 9
-2

I think you should use forms auth, but you can use ldap windows user account in forms like this:

using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
  • 1
    This isn't a complete answer as you didn't disclose how to properly use that code snippet. The last few sentences in the question also ruled out this option completely. – Lex Li Feb 15 '23 at 18:03