ASP.NET Windows Authentication logout
Asked Answered
D

9

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

Debut answered 1/7, 2009 at 4:23 Comment(1)
It appears impersonating a user via Forms authentication is possible after all. See https://mcmap.net/q/552717/-impersonate-using-forms-authenticationPfaff
D
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.

Debut answered 9/10, 2009 at 19:11 Comment(0)
H
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.

Heyman answered 20/4, 2011 at 13:58 Comment(3)
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.Wie
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 msdn.microsoft.com/en-us/library/ms536979.aspxWie
Brilliant! I changed the code to redirect as describe in here - #12742819Exeat
O
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.

Osteopathy answered 1/7, 2009 at 5:9 Comment(1)
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.Debut
O
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

Outturn answered 10/6, 2013 at 19:27 Comment(0)
F
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:[email protected]";
    }
} 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();
}
Fatalism answered 17/6, 2011 at 16:59 Comment(0)
G
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.

Gradygrae answered 14/12, 2011 at 15:6 Comment(1)
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.Golfer
C
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");
Cacie answered 27/3, 2019 at 3:55 Comment(1)
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.Environmentalist
G
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.

Gt answered 31/8, 2023 at 16:19 Comment(0)
A
-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");
}
Acuate answered 28/4, 2020 at 17:51 Comment(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.Golfer

© 2022 - 2025 — McMap. All rights reserved.