Close browser window with specific url (opened by different browser) - asp.net

I am doing an application where when the user click on social login it opens a new window. Let's say my application is running on Chrome and my default browser was set to Edge; the URL is getting opened in Edge. After successful token generation it is redirecting to the application without closing the browser window/tab.
I am using azure AD authentication as follows
IPublicClientApplication app = PublicClientApplicationBuilder
.Create(azMapping.ClientId)
.WithAuthority(authority)
.WithRedirectUri("http://localhost:44342/Default.aspx")
.Build();
result = app.AcquireTokenInteractive(scopes)
.WithSystemWebViewOptions(new SystemWebViewOptions())
.ExecuteAsync(CancellationToken.None)
.GetAwaiter().GetResult();
The authority URL opens in the default browser. Is there a way to open the URL on the application running or can we close once we got back the response?

You can use the destinationpageurl property
The DestinationPageUrl property specifies the page that is displayed when a login attempt is successful.
Or
You can use the JavaScript to achieve this window.location.href returns the href (URL) of the current page
Response.Redirect should work if you just want to navigate to the same window page.
refer here for Open url in same window
You can have a look to how to handle it see here

Related

Tabs opened via Hyperlinks in Excel/Word not recognizing session cookies

I have an ASP.Net application with authentication using Cookie session variables. Once the user logs in, they can open new browser tabs for the same application and these are logged in automatically as the session cookie is present.
Clicking on a hyperlink on another web page pointing to a specific page within the application also works fine - there is no login required as the user is already logged in.
However, when a hyperlink to the application is in a Word/Excel document, this link does not open the page directly and gets bounced to the Login page instead. If I copy/paste the Url from Word/Excel and paste it in the Url bar on the browser, it works fine.
Any explanation to this behaviour? Does the browser open a isolated session when a link is clicked in Word/Excel?
Edit: It also seems Word/Excel perform their own check before opening a browser tab. If I use a non-existent link, it doesn't open the tab.
We ran into this at my place of work a while back, and found that like you mentioned, MS Office applications indeed do some mysterious stuff behind the scenes. Details on what it actually does are in this article: https://learn.microsoft.com/en-us/office/troubleshoot/office-suite-issues/click-hyperlink-to-sso-website
Toward the bottom of that article, they suggest a workaround involving a meta refresh, which is what worked for us. In our case, we added a method to our request pipeline that checks for a Microsoft product in the User-Agent header. If found, it sends a meta refresh that triggers the browser to use an existing session rather than trying to start a new session (which is why you're being redirected to a logon page). Here's more or less the code:
private static string MSUserAgentsRegex = #"[^\w](Word|Excel|PowerPoint|ms-office)([^\w]|\z)";
protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
{
if (!Request.IsAuthenticated)
{
if (System.Text.RegularExpressions.Regex.IsMatch(Request.UserAgent, MSUserAgentsRegex))
{
Response.Write("<html><head><meta http-equiv='refresh' content='0'/></head><body></body></html>");
Response.End();
}
}
}

Include custom content in ASP.NET Windows Authentication 401 response

We have an internal system where users can authenticate using Windows authentication but we want to include some custom content in the 401 repsonse that takes the user to a custom username/password authentication page if the cancel off the Windows authentication dialog.
When an unauthenticated user accesses a page, Windows authentication responds with a 401 Unauthorized response, with the headers
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
This prompts the browser to show a dialog asking for Windows credentials. If the user enters their credentials, there is another handshake request-response, and then the user is authenticated and the requested page is shown.
If the user cancels the dialog, the browser displays the content of the original 401 Unauthorized reponse.
We use Application_EndRequest in the Global.asax to return some custom content here which takes the user to our custom login system.
/// <summary>
/// If we are about to send the NTLM authenticate headers, include this content. Then, if the user cancels off the
/// windows auth dialog, they will be presented with this page and redirected to the username / password login screen
/// </summary>
void Application_EndRequest(object sender, EventArgs e)
{
Logger.DebugFormat("in Application_EndRequest. Response.StatusCode: {0}", Response.StatusCode);
if (Response.StatusCode == 401)
{
Response.ContentType = "text/html";
var redirectUrl = string.Format("https://mycompany.com/SSO/Login?encryptedSessionRequestId={1}",
HttpUtility.UrlEncode(Request.QueryString["encryptedSessionRequestId"]));
var text = File.ReadAllText(Server.MapPath("~/UnauthorizedError.html"));
text = text.Replace("[USERNAME_PASSWORD_LOGON_REDIRECT]", redirectUrl);
Response.Write(text);
Logger.Debug("Done writing response");
Response.End();
}
}
UnauthorizedError.html contains the following script which forwards the user on
<script language="javascript" type="text/javascript">
window.location = "[USERNAME_PASSWORD_LOGON_REDIRECT]";
</script>
When running locally in (Win7/IIS7.5), this works great, we use Response.Write() to send our content and the user is able to see it when they cancel the dialog.
But when accessing the site remotely, e.g. when it running in our development environment, although we can see from the logs that Application_EndRequest is being called and our content written to the response, it is overridden at some point and all that reaches the browser is the authentication headers and the text You do not have permission to view this directory or page.
1) How can we prevent this content being overwritten?
2) Where in the pipeline might this be happening?
3) Does anyone have any suggestions of another way to implement this behaviour, e.g. with an HTTP module?
Thanks!
I wasted a lot to solve this problem but there isn't direct solution.
It because win auth works on iis not site level and you can't control how to auth current request.
There is several hacky ways to use redirection on different login pages depending on ip.
I know this is an old post but I would like to share a solution to this problem.
When altering the response message for remote requests (read: non-localhost) you will need to add the following to your config file:
<system.webServer>
<httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
If you do not allow the response to "pass through" remote clients will get the default "You do not have permission to view this directory or page".
I got this info from: https://stackoverflow.com/a/17324195/3310441

Using the facebook c# sdk in asp.net without a canvas application

Im trying to use the sdk without a canvas application, so have followed steps 1-7 in the quickstart guide up to adding the facebookSettings property in the Web.config.
I have added an image to my page and an onclick event that contains the below code. but when I click the button, it just takes me to the home page (CancelUrlPath).
Changing the Authorizer to a CanvasAuthorizer results in FB loading the login screen, but I get an error 404 not found on the call (even after inserting the handlers into the config)..
fbApp = new FacebookApp();
authorizer = new Authorizer(fbApp) {Perms = requiredAppPermissions};
authorizer.ReturnUrlPath = "http://localhost/User/UserRegister.aspx";
authorizer.CancelUrlPath = "http://localhost/";
if (authorizer.Authorize(this.Context))
{
Response.Write("hello");//never gets here
}
Can anyone help please?
Note: I've set the canvas and site url to http://localhost/ on the FB app settings.
If you are just building a simple connect website you really don't want to use the server side authentication tools to authenticate your user. Just use the Javascript SDK to athenticate the user. If you need to do anything on the server side, the FacebookApp class will automatically pick up the user's session from the values stored in the cookies.
See the Facebook documentation for more details: http://developers.facebook.com/docs/guides/web/#registration

After a few window.open calls my ASP.NET session times out

I have an ASP.NET application that uses StateServer session mode with cookieless set to false. In a few places, there is a link that pops up a window to another application (which happens to reside on the same domain, but in a different virtual directory). The following steps give me grief...
Launch popup
Close popup
Launch popup to same app as before with a couple different parameters
Close popup
Next request = session timeout on the "parent" window.
Using cookieless sessions fixes the problem, so somehow my cookie is getting whiped out by the browser. Aside from using cookieless sessions, how can this be resolved? For what it's worth, I am developing/testing with IE8.
EDIT
It seems the problem only occurs when the popup resides on the same domain. If I popup a page elsewhere, there is no problem.
Is it possible the other app (on the same domain) is setting its own cookie, overwriting that of your primary app? Can you use fiddler (or similar tool) to see which cookies are being set by which apps?
Check all instances of your
Session.Clear();
Session.Abandon();
If you aren't using those at all, then its likely the case that your browser windows are set to NOT share sessions between. So the new instance gets a NEW session cookie (since its the same cookie name as the prior one, it could possibly kill the existing session cookie)- as in a play on:
http://geekswithblogs.net/ranganh/archive/2009/04/17/asp.net-session-state-shared-between-ie-tabs-and-ie8.aspx
Ideally track down in which page the Set-Cookie header is coming across. Look then at the request going INTO that response and see if your current ASP.NET_SESSIONID cookie is sent over. (fiddler is indeed the best tool for this)
Anyway - its a start to try.
edit Apparently it's not your cookie name, so...
Perhaps you should have an AJAX call on your master page that pings a service (or generic handler) on your web app to keep the session alive.
JavaScript
window.setInterval(function() {
$.get('ping.ashx?nocache=' + (new Date()).getTime(), function() {
return true;
})
}, 30000);
In the Generic Handler, make sure to add the IRequiresSessionState marker interface.
Perhaps your session cookie names are the same.
In your web.config (for one of the applications) change the session cookie name.
<sessionState
mode="StateServer"
timeout="20"
cookieName="DifferentASP.NET_SessionId"

Logoff button IIS6 ASP.NET Basic Authentication

I have a requirement for an explicit logout button for users in a ASP.NET web app. I am using IIS6 with Basic Authentication (SSL). I can redirect to another web page but the browser keeps the session alive. I have googled around and found a way to do it by enabling an active x control to communicate with IIS and kill the session. I am in a restricted environment that does not allow forms authentication and active x controls are not forbidden as well. Has anyone else had this requirement and how have you handled it?
Okay that is what I was afraid of. I have seen similar answers on the net and I was hoping someone would have a way of doing it. Thanks for your time though. I guess I can use javascript to prevent the back button like the history.back()
I was struggling with this myself for a few days.
Using the IE specific 'document.execCommand('ClearAuthenticationCache');' is not for everyone a good option:
1) it flushes all credentials, meaning that the user will for example also get logged out from his gmail or any other website where he's currently authenticated
2) it's IE only ;)
I tried using Session.Abandon() and then redirecting to my Default.aspx. This alone is not sufficient.
You need to explicitly tell the browser that the request which was made is not authorized. You can do this by using something like:
response.StatusCode = 401;
response.Status = "401 Unauthorized";
response.AddHeader("WWW-Authenticate", "BASIC Realm=my application name");
resp.End();
This will result in the following: the user clicks the logout button ==> he will get the basic login window. HOWEVER: if he presses escape (the login dialog disappears) and hits refresh, the browser automagically sends the credentials again, causing the user to get logged in, although he might think he's logged out.
The trick to solve this is to always spit out a unique 'realm'. Then the browser does NOT resend the credentials in the case described above. I chose to spit out the current date and time.
response.StatusCode = 401;
response.Status = "401 Unauthorized";
string realm = "my application name";
response.AddHeader("WWW-Authenticate", string.Format(#"BASIC Realm={0} ({1})", realm, DateTimeUtils.ConvertToUIDateTime(DateTime.Now)));
resp.End();
Another thing that you need to do is tell the browser not to cache the page:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.MinValue);
Response.Cache.SetNoStore();
With all these things in place it works (for me) in IE, but until now I still wasn't able to prevent firefox from logging in the user when the user first presses escape (hides the basic login dialog) and then refresh (F5) or the browsers back button.
The Session.Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.
Have you tried calling Session.Abandon in response to the button click?
Edit:
It would seem this is a classic back button issue.
There is very little you can do about the back button. Imagine the user has just opened the current page in a new window then clicked the logOut button, that page appears to log out but it will not immediately affect the content of the other window.
Only when they attempt to navigate somewhere in that window will it become apparent that their session is gone.
Many browsers implement the back button in a similar (although not identical) way. Going back to the previous page is not necessarily a navigation for a HTML/HTTP point of view.
This is a solution for this problem that works in IE6 and higher.
<asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="logout();">LinkButton</asp:LinkButton>
<script>
function logout()
{
document.execCommand("ClearAuthenticationCache",false);
}
</script>
Found this from
http://msdn.microsoft.com/en-us/library/bb250510%28VS.85%29.aspx
Web Team in Short
Your Credentials, Please
Q: Jerry B. writes, "After the user has validated and processed his request, I now want to invalidate him. Assuming this machine is in an open environment where anyone could walk up and us it, I want to throw a new challenge each time a user accesses a particular module on the Web."
A: This is a frequently requested feature of the Internet Explorer team and the good people over there have given us a way to do it in Internet Explorer 6.0 SP1. All you need to do is call the execCommand method on the document, passing in ClearAuthenticationCache as the command parameter, like this:
document.execCommand("ClearAuthenticationCache");
This command flushes all credentials in the cache, such that if the user requests a resource that needs authentication, the prompt for authentication occurs again.
I put this on my logout link button and it works in IE6 sp1 and higher:
OnClientClick="document.execCommand('ClearAuthenticationCache');"

Resources