ASP.NET Windows Authentication logout - asp.net

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

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.

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.

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.

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

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();
}

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.

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");

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");
}

Related

Prevent SSO with Playwright

Trying to write an automated test for a website that uses federated auth with ADFS.
In my Ci/CD pipeline I will not be running in an authenticated Windows context so my Playwright tests will encounter an ADFS credentials prompt, BUT when developing the tests we are working in an authenticated context and Windows Pass-through auth will kick in (NTLM is my guess).
How can I prevent that?
With a previous set of tests that I wrote using NightwatchJS the trick I used was to send a custom UserAgent string of a browser that is not registered in ADFS as being a browser that is supported for the NTLM challenge flow. (it was Opera Mini btw)
With Playwright the same trick doesn't work apparently, and I was hoping there is something better out there.
What I tried:
context = await browser.newContext({
userAgent: 'Opera/9.80 (Android; Opera Mini/12.0.1987/37.7327; U; pl) Presto/2.12.423 Version/12.16'
})
So.....after some more digging, after asking the correct question, which in the end was:
"How to disable Windows Integrated Authentication in Chrome?"
I found this checklist for conditions and this answer on SO.
The fix was to add a startup arg to chromium to disable WIA. Here's the important bit below:
browser = await chromium.launch({
args: ['--auth-server-whitelist="_"'],
});
This will make chrome present a basic auth prompt for credentials.
However, when I combined this with the custom userAgent string that is not amongst the useragents supported by the ADFS server, I managed to reach the login page of ADFS.
Again, OperaMini worked for me:
context = await browser.newContext({
userAgent: 'Opera/9.80 (Android; Opera Mini/12.0.1987/37.7327; U; pl) Presto/2.12.423 Version/12.16'
})
What worked for me is to combine a bit of #dutzu's answer with basic authentication for Playwright. Here's an example of doing this in C# for AD/NTLM authentication.
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
// Forces authentication to be required and not automatically passed through via your windows session
Args = new[] { "--auth-server-whitelist=\"_\"" },
Headless = false
});
var context = await browser.NewContextAsync(new BrowserNewContextOptions { HttpCredentials = new HttpCredentials { Password = "....", Username = "...." } }) ;
var page = await context.NewPageAsync();
await page.GotoAsync("https://some_website_that_uses_ntlm/");
You need to send calls to the Web Application Proxy or setup an internal one. Wep Application Proxy does not support Windows Integrated Authentication.
I was also having an ADFS form that I needed to authenticate against. In my case it was enough to create a browser context with http credentials, and then it just worked by itself.
const context = await browser.newContext({
httpCredentials: {
username: 'bill',
password: 'pa55w0rd',
},
});
const page = await context.newPage();
await page.goto('https://example.com');
Ref: https://playwright.dev/docs/network#http-authentication

Keep application users logged in for 20 Hours

We have a asp.net + MSSQL Server DB web based application with approx 100 users. Its hosted on our intranet on IIS7.0. We are using Forms Authentication
We need to keep the users (anyone who is logged in ) to be logged in for 20 Hours exactly. Means no one should be kicked out ( session time out ) of the application before 20 Hours even if he is idle.
We tried many of the suggested approaches like web config changes etc but nothing is working.
Our main question is : Will we have to do some code changes to keep the user sessions alive for this ( or any duration). Can someone suggest or point us to a solution?
Whenever you make a request to the server the session timeout resets. So you can just make an ajax call to an empty HTTP handler on the server, but make sure the handler's cache is disabled, otherwise the browser will cache your handler and won't make a new request.
KeepSessionAlive.ashx.cs
public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
context.Response.Cache.SetNoStore();
context.Response.Cache.SetNoServerCaching();
}
}
.JS:
window.onload = function () {
setInterval("KeepSessionAlive()", 60000)
}
function KeepSessionAlive() {
url = "/KeepSessionAlive.ashx?";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.send();
}

WIF, ADFS 2.0, wsignoutcleanup1.0 and wreply

I have set up a WIF web application, a custom STS and an ADFS 2.0 instance as the go between. I am having a hard time understanding the sign out process for my application. Currently, when my user clicks the sign out button, I am calling this code:
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri("https://myrelyingpartyapp.com/?wa=wsignoutcleanup1.0"));
If I use this code, it works fine. All of the cookies and sessions are disposed of correctly. The only problem is that the browser just displays a little green check after the process is over. Obviously, I want to be redirected back to the login page of the STS. To accomplish this I attempted the following code:
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri("https://myrelyingpartyapp.com/?wa=wsignoutcleanup1.0&wreply=" + HttpUtility.UrlEncode("https://myrelyingpartyapp.com/Default.aspx")));
My belief was that the wreply would cause the user to be redirected back to my relying party app where they would be unauthorized and therefore be redirected back to the STS login page. Instead this causes an error in ADFS (which I cannot see because of their helpful error page.) No matter what url I use for wreply, the error is thrown. Am I using wsignoutcleanup1.0 correctly? Just for reference, here is the code in my STS where I handle sign in/sign out requests:
if (action == "wsignin1.0")
{
SignInRequestMessage signInRequestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
SecurityTokenService securityTokenService = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
SignInResponseMessage signInResponseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(signInRequestMessage, User as ClaimsPrincipal, securityTokenService);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(signInResponseMessage, Response);
}
else
{
throw new UnauthorizedAccessException();
}
}
else if (action == "wsignout1.0")
{
SignOutRequestMessage signOutRequestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(signOutRequestMessage, User as ClaimsPrincipal, signOutRequestMessage.Reply, Response);
}
All I needed for correct behavior was correct logout code. This code eventually logged my user out and did a proper cleanup:
var module = FederatedAuthentication.WSFederationAuthenticationModule;
module.SignOut(false);
var request = new SignOutRequestMessage(new Uri(module.Issuer), module.Realm);
Response.Redirect(request.WriteQueryString());
This code was put in the event handler of my logout button on my relying party app.

DotNetOpenAuth Failing to work on Live Server

I worked on a sample application integrating OpenID into ASP.NET Web Forms. It works fine when hosted locally on my machine. However, when I uploaded the application to a live server, it started giving "Login Failed".
You can try a sample here: http://samples.bhaidar.net/openidsso
Any ideas?
Here is the source code that fails to process the OpenID response:
private void HandleOpenIdProviderResponse()
{
// Define a new instance of OpenIdRelyingParty class
using (var openid = new OpenIdRelyingParty())
{
// Get authentication response from OpenId Provider Create IAuthenticationResponse instance to be used
// to retreive the response from OP
var response = openid.GetResponse();
// No authentication request was sent
if (response == null) return;
switch (response.Status)
{
// If user was authenticated
case AuthenticationStatus.Authenticated:
// This is where you would look for any OpenID extension responses included
// in the authentication assertion.
var fetchResponse = response.GetExtension<FetchResponse>();
// Store the "Queried Fields"
Session["FetchResponse"] = fetchResponse;
// Use FormsAuthentication to tell ASP.NET that the user is now logged in,
// with the OpenID Claimed Identifier as their username.
FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
break;
// User has cancelled the OpenID Dance
case AuthenticationStatus.Canceled:
this.loginCanceledLabel.Visible = true;
break;
// Authentication failed
case AuthenticationStatus.Failed:
this.loginFailedLabel.Visible = true;
break;
}
}
As Andrew suggested, check the exception. In my case, my production server's time & date were off and it wouldn't authenticate because the ticket expired.
Turn on logging on your live server and inspect them for additional diagnostics. It's most likely a firewall or permissions problem on your server that prevents outbound HTTP requests.
You may also find it useful to look at the IAuthenticationResponse.Exception property when an authentication fails for clues.

How to detect server-side whether cookies are disabled

How can I detect on the server (server-side) whether cookies in the browser are disabled? Is it possible?
Detailed explanation: I am processing an HTTP request on the server. I want to set a cookie via the Set-Cookie header. I need to know at that time whether the cookie will be set by the client browser or my request to set the cookie will be ignored.
Send a redirect response with the cookie set; when processing the (special) redirected URL test for the cookie - if it's there redirect to normal processing, otherwise redirect to an error state.
Note that this can only tell you the browser permitted the cookie to be set, but not for how long. My FF allows me to force all cookies to "session" mode, unless the site is specifically added to an exception list - such cookies will be discarded when FF shuts down regardless of the server specified expiry. And this is the mode I run FF in always.
You can use Javascript to accomplish that
Library:
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function areCookiesEnabled() {
var r = false;
createCookie("testing", "Hello", 1);
if (readCookie("testing") != null) {
r = true;
eraseCookie("testing");
}
return r;
}
Code to run:
alert(areCookiesEnabled());
Remember
This only works if Javascript is enabled!
I dont think there are direct ways to check. The best way is to store a value in the cookie and try to read them and decide whether cookies are enabled or not.
The below answer was written a long time ago. Now, for better or worse, due to laws in various countries it has become either good practice - or a legal requirement - not to require cookies except where necessary, at least until the user has had a chance to consent to such mechanisms.
It's a good idea to only do this when the user is trying to do something that initiates a session, such as logging in, or adding something to their cart. Otherwise, depending on how you handle it, you're potentially blocking access to your entire site for users - or bots - that don't support cookies.
First, the server checks the login data as normal - if the login data is wrong the user receives that feedback as normal. If it's right, then the server immediately responds with a cookie and a redirect to a page which is designed to check for that cookie - which may just be the same URL but with some flag added to the query string. If that second page doesn't receive the cookie, then the user receives a message stating that they cannot log in because cookies are disabled on their browser.
If you're following the Post-Redirect-Get pattern for your login form already, then this setting and checking of the cookie does not add any additional requests - the cookie can be set during the existing redirect, and checked by the destination that loads after the redirect.
Now for why I only do a cookie test after a user-initiated action other than on every page load. I have seen sites implement a cookie test on every single page, not realising that this is going to have effects on things like search engines trying to crawl the site. That is, if a user has cookies enabled, then the test cookie is set once, so they only have to endure a redirect on the first page they request and from then on there are no redirects. However, for any browser or other user-agent, like a search engine, that doesn't return cookies, every single page could simply result in a redirect.
Another method of checking for cookie support is with Javascript - this way, no redirect is necessarily needed - you can write a cookie and read it back virtually immediately to see if it was stored and then retrieved. The downside to this is it runs in script on the client side - ie if you still want the message about whether cookies are supported to get back to the server, then you still have to organise that - such as with an Ajax call.
For my own application, I implement some protection for 'Login CSRF' attacks, a variant of CSRF attacks, by setting a cookie containing a random token on the login screen before the user logs in, and checking that token when the user submits their login details. Read more about Login CSRF from Google. A side effect of this is that the moment they do log in, I can check for the existence of that cookie - an extra redirect is not necessary.
Try to store something into a cookie, and then read it. If you don't get what you expect, then cookies are probably disabled.
I always used this:
navigator.cookieEnabled
According to w3schools "The cookieEnabled property is supported in all major browsers.".
However, this works for me when i am using forms, where i can instruct the browser to send the additional information.
check this code , it' will help you .
<?php
session_start();
function visitor_is_enable_cookie() {
$cn = 'cookie_is_enabled';
if (isset($_COOKIE[$cn]))
return true;
elseif (isset($_SESSION[$cn]) && $_SESSION[$cn] === false)
return false;
// saving cookie ... and after it we have to redirect to get this
setcookie($cn, '1');
// redirect to get the cookie
if(!isset($_GET['nocookie']))
header("location: ".$_SERVER['REQUEST_URI'].'?nocookie') ;
// cookie isn't availble
$_SESSION[$cn] = false;
return false;
}
var_dump(visitor_is_enable_cookie());
NodeJS - Server Side - Cookie Check Redirect
Middleware - Express Session/Cookie Parser
Dependencies
var express = require('express'),
cookieParser = require('cookie-parser'),
expressSession = require('express-session')
Middleware
return (req, res, next) => {
if(req.query.cookie && req.cookies.cookies_enabled)
return res.redirect('https://yourdomain.io' + req.path)
if(typeof(req.cookies.cookies_enabled) === 'undefined' && typeof(req.query.cookie) === 'undefined') {
return res.cookie('cookies_enabled', true, {
path: '/',
domain: '.yourdomain.io',
maxAge: 900000,
httpOnly: true,
secure: process.env.NODE_ENV ? true : false
}).redirect(req.url + '?cookie=1')
}
if(typeof(req.cookies.cookies_enabled) === 'undefined') {
var target_page = 'https://yourdomain.io' + (req.url ? req.url : '')
res.send('You must enable cookies to view this site.<br/>Once enabled, click here.')
res.end()
return
}
next()
}
The question whether cookies are "enabled" is too boolean. My browser (Opera) has a per-site cookie setting. Furthermore, that setting is not yes/no. The most useful form is in fact "session-only", ignoring the servers' expiry date. If you test it directly after setting, it will be there. Tomorrow, it won't.
Also, since it's a setting you can change, even testing whether cookies do remain only tells you about the setting when you tested. I might have decided to accept that one cookie, manually. If I keep being spammed, I can (and at times, will) just turn off cookies for that site.
If you only want to check if session cookies (cookies that exist for the lifetime of the session) are enabled, set your session mode to AutoDetect in your web.config file, then the Asp.Net framework will write a cookie to the client browser called AspxAutoDetectCookieSupport. You can then look for this cookie in the Request.Cookies collection to check if session cookies are enabled on the client.
E.g. in your web.config file set:
<sessionState cookieless="AutoDetect" />
Then check if cookies are enabled on the client with:
if (Request.Cookies["AspxAutoDetectCookieSupport"] != null) { ... }
Sidenote: By default this is set to UseDeviceProfile, which will attempt to write cookies to the client so long as the client supports them, even if cookies are disabled. I find it slightly odd that this is the default option as it seems sort of pointless - sessions won't work with cookies disabled in the client browser with it set to UseDeviceProfile, and if you support cookieless mode for clients that don't support cookies, then why not use AutoDetect and support cookieless mode for clients that have them disabled...
I'm using a much more simplified version of "balexandre"'s answer above. It tries to set, and read a session cookie for the sole purpose of determining if cookies are enabled. And yes, this requires that JavaScript is enabled as well. So you may want a tag in there if you care to have one.
<script>
// Cookie detection
document.cookie = "testing=cookies_enabled; path=/";
if(document.cookie.indexOf("testing=cookies_enabled") < 0)
{
// however you want to handle if cookies are disabled
alert("Cookies disabled");
}
</script>
<noscript>
<!-- However you like handling your no JavaScript message -->
<h1>This site requires JavaScript.</h1>
</noscript>
The cookieEnabled property returns a Boolean value that specifies whether or not cookies are enabled in the browser
<script>
if (navigator.cookieEnabled) {
// Cookies are enabled
}
else {
// Cookies are disabled
}
</script>
<?php session_start();
if(SID!=null){
echo "Please enable cookie";
}
?>
Use navigator.CookieEnabled for cookies enabled(it will return true of false) and the Html tag noscript. By the way navigator.cookieEnabled is javascript so don't type it in as HTML

Resources