Logout of MVC4 application - c#

I'm continuing someone else's development AND I don't know much about current practices for authentication in MVC applications.
The only things that are set about authentication are in the application's IIS configuration:
.NET Authrization Rules = Allow, All Users
Authentication:
Anonymous Authentication: Enabled
ASP .NET Impersonation: Disabled
Windows Authentication: Enabled
With this configuration, on the server, the browser asks me for a login/password. I enter my network login.
Then I can get identify the user with Request.RequestContext.HttpContext.User.Identity...
On local computer where I login using the same login/password: no user is logged in the application (Request.RequestContext.HttpContext.User.Identity.Name == ""). If I disable Anonymous Authentication, the browser simply keeps re-asking for loginpassword infinitely.
My first problem is that I would like to be able to log out on server.
From scarse info I got here and there I have already tried:
FormsAuthentication.SignOut(); --> does nothing
WebMatrix.WebData.WebSecurity.Logout(); --> Exception, tries to access a database (I got this from one of the VS2012 templates but I didn't think it would apply to my context).
if(this.Request.RequestContext.HttpContext.Session != null)
this.Request.RequestContext.HttpContext.Session.Clear(); --> Session is null, so this does nothing.
So, how can I log out in order to relog as a different user ?
(I would also like to be able to identify the user on local computer, but I think that should be asked in another topic.)

Removed FormsAuth logout method as the question is for Windows Auth... doh!
Update:
To get the logged in user name try the IPrincipal Controller.User:
User.Identity.Name
Doh my bad your using Windows Authentication...
In which case it's the browser that is caching the credentials not the server / IIS so clearing the session won't achieve anything.
Taken from here:
"The user credentials are being cached by the client browser, not by IIS. To
force the client user to enter credentials again, you would need to send an
appropriate 401 status message in response to the next client request.
However, doing this would run counter to very legitimate user expectations
of how Windows authentication is supposed to work, so you may want to
reconsider. When Windows user credentials have already been accepted by a
server (either via a login dialog or automatic submission under IE
configuration for the target site or zone), a 401 is only expected if a
requested resource cannot be accessed under the previously supplied
credentials. When you send a 401 after any credentials have been previously
accepted, the user should expect that they need to use different credentials
from their initial login. If you're expecting the same credentials, then
user confusion should be anticipated.
All in all, if you really want to force a new login, perhaps a different
authentication mode might be more appropriate."
For an IE only workaround see this SO post.

Related

Windows Authentication for Blazor Server app - login popup

I am building a Blazor Server app using .NET 6.0.11 and deploying using Http.Sys . The server and clients are all on the same Windows domain. I'd like to authorize users based on their domain login, instead of building a username/password database and infrastructure specific to this app.
The code in Program.cs to enable Windows Authentication, based on code from the official documentation:
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
builder.Services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);
builder.WebHost.UseHttpSys(options =>
{
options.Authentication.Schemes =
AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
options.Authentication.AllowAnonymous = false;
});
}
// ...
app.UseAuthentication();
app.UseAuthorization();
I view the authentication state using the first code sample from ASP.NET Core Blazor authentication and authorization.
If I launch the application on http://localhost:55555 then the page loads instantly and it shows my domain and username successfully.
However, if I launch the application as http://mycomputername.our.domain:55555, and access it via Chrome or Edge on the same machine, then a popup appears asking for username and password:
Note: I had to run a netsh http add urlacl url=.... one time only; the command was suggested by an exception message generated on first run after changing the launch URL.
Entering my domain login username and password is accepted, and the previous code sample does show my username successfully. I also noticed the following behaviour:
setting AllowAnonymous = true; means it will not prompt at all for the username/password; the page just proceeds with the user not authenticated.
If the username/password is not entered correctly (for a user on the domain) then HTTP error 401 is generated instantly, it never tries to execute the Blazor default error page for example.
I hope the authentication is being done between the client and the domain controller, not sending the user's password over the HTTP connection!
I am presuming the above behaviour will be the same for other domain uses on different machines accessing this server, although have not tested that yet.
My questions:
is it possible to skip the username/password popup , and just get the domain user that is already logged in on the client machine and doing the access?
(If not) would deploying to IIS instead of Http.Sys change anything?
There seem to be Blazor-based solutions discussed on this SO thread , but I can't see how to use them because the popup always appears as soon as any page is attempted , before any page is rendered; and if login fails, HTTP 401 error is generated with none of the Blazor pages being executed.
Footnote: I was using HTTP.sys instead of Kestrel due to documentation indicating that Kestrel did not support Windows Authentication; however it is working using Kestrel for me now, along with the information from the Accepted answer -- not sure what the story is there.
This is a client-side issue.
If I launch the application on http://localhost:55555 then the page loads instantly and it shows my domain and username successfully.
However, if I launch the application as http://mycomputername.our.domain:55555, and access it via Chrome or Edge on the same machine, then a popup appears asking for username and password:
That's because the browser recognizes localhost as a (somewhat trustworthy) server within your intranet, but considers mycomputername.our.domain to be a (potentially hostile) Internet service. For security reasons, Chrome and Edge only use your Windows credentials with servers within your own intranet by default.
To determine which group an URL belongs to, Chrome, Internet Explorer and Edge use Windows's own "Intranet zone" settings. To add your URL,
search for "Internet options" in the Windows Start Menu, then
navigate to Security/Local intranet/Sites/Advanced.
If you want to test with a non-Chromium based browser, here's how to configure Firefox. Firefox manages its own list of URLs where Windows authentication is allowed:
How to configure Firefox for NTLM SSO (Single-Sign-On)?
I hope the authentication is being done between the client and the domain controller, not sending the user's password over the HTTP connection!
If the client and the server agree to use Kerberos, sure: The client communicates with the domain controller to authenticate and to get a service ticket and then uses that ticket to access your service.
If they don't agree, they will use NTLM. In this case, authentication happens between the client and your server. However, NTLM won't send your password in plain text either, but rather uses it as part of a challenge-response mechanism.
is it possible to skip the username/password popup , and just get the
domain user that is already logged in on the client machine and doing
the access?
IMHO, this is not possible with "windows authentication", because the popup dialog that you see is a special browser feature to enable the windows authentication.This one created in order to support internal application with domain authentication. I don't know of any way to access that browser behavior.
(If not) would deploying to IIS instead of Http.Sys change anything?
Haven't done a deployment with Http.Sys, but according to the documentation it says that Http.Sys supports windows authentication. The deployment would be different since for Http.Sys you need to write the configuration in code, unlike the IIS.

ASP.Net MVC how does back-end know if user signed in

I created a ASP.Net C# MVC app with "Individual User Account" for Authentication + localDB. I started the app in visual studio with IIS express on localhost, signed up an user and logged in with that user.
I am trying to understand how back-end know a user has logged in in the following scenario:
start the iis express & app in visual studio
log in
stop the iis express & app in visual studio
start again the iis express & app in visual studio
user still logged in (WHY???)
I checked the user tables in db, and could not find any fields indicate a logged in user. I am thinking stop & restart iis express should clear everything in the back-end as well.
So how does the back-end know there was an user logged in in the step 5 above??
I found the following cookie in the http request
Cookie: _ga=GA1.1.1546797954.1551225891; __RequestVerificationToken=PSFeb9iP4aZr3wxxb8nJNKtki_1XPTzGO1Hzaf0W3iDsSCnV_qCfMsC9TY980X51c2rANZA-zureu6UHKEssAHza58AdmQUdZVL98VGYlRc1; .AspNet.ApplicationCookie=VUPznoprBRK2z13u03ArrC9HLHeGGUyTSvu9rYpSnZju_Rz4X2V5n9faw0EhnmuFjVN1AIva7HZSAhUBeSZ5jQHSej6XaAExy0hkwF_9vC190LfWBPP-oH3Zp0jj0ZmZ7L3sLlLqux4HV5CZSA-jqhDF4IXAFKyisFFV136PlxrJTmb9OXRrmo9rigCiIy0z_oixDlg1eHVI3T6ptVgn1Qhohtr1mTqoBJsF7gi7CHymSBlyFJ5MgYxfPcWNhJnj3H-WWK1ijkfzxsm0R13m2_6IbIiK1y5uzQBkklb8oMuz0mD27GlwMzteQBP3VLOXn77BreOPefJ8_2AekYjFGjgBIGGpngxLVzDneT4rC-BDiVKdWO_FRuail4ivVAN2ZJtdjK0uEPqnln5rmOlT0MLAhYzHMkk-HTvtW-Xo-Kexinlh58uxz0E7bncY5I6troc19E0fBLMnfXThtaL7ur6CN4pqUyq4yALJCTHszG3RPLQoJja0u1g34i-mKunZ
In web development there is very basic concept called cookie.The cookie is responsible too store user information in browser. When you sign-in in membership system ,it adds a special header called Set-Cookie to response which afterward get's stored in browser cache.The information send through header contains information about loged in user's identity. With subsequent requests browser send the same cookie to the server and the membership system parses that info to identify the user which makes request and if the information is valid you are logged in and system identifies you.
EDIT :
The detail of operations taking place is not unique and depends on which library you use for authentication but if you use asp.net default authentication system then you can go and see how things get done in the source code.For ASP.NET CORE check https://github.com/aspnet/AspNetIdentity and for ASP.NET MVC check : https://github.com/aspnet/Identity
Following is how authentication works in ASP.NET MVC
Enter Username and password in login form and click on "Login" button
On click of Login button Server side code checks whether entered Username and Password exists in database
If entered Username and Password exists in database then server side code creates cookie and stores them in the browser(not in the database)
On every page request IIS checks whether authentication cookie exists or not.
If cookie exists then user is logged In and if cookie doesn't exist the user is not logged in
Since authentication cookie is stored in browser and not in IIS. Stopping and Starting IIS has no effect on User log in status.
To answer your specific question: So how does the back-end know there was an user logged in in the step 5 above??
Ans: On ever page request from IIS. Along with other information, authentication cookie stored in browser is sent to back-end/IIS. back-end/IIS then checks whether or not authentication cookie is valid. If cookie is valid back-end/IIS knows user is logged in. If cookie is invalid back-end/IIS knows user is not logged in.
To understand this process further. I would recommend reading about cookies first and then read about authentication in ASP.NET.
Hope this helps!

Integrated Windows Authentication - Logout

I am attempting to use Integrated Windows Authentication on IIS for an MVC web app. The original hope was that the user would be logged in automatically using the current Windows user credentials. I am running into the issue where the user is always prompted to enter user name and password. I have decided that we can live with this. However, I have also noticed that the user can enter any valid domain credentials...it's not limited to the currently logged in machine. But if this is the case, I need to provide a logout button, so the user can be switched if necessary.
Everything I can find on this issue, logging out in Windows Authentication, says you cannot do it because it pulls the credentials from the machine login. But it's obviously not doing that in my case, because I can enter any valid credentials and log in successfully. So a user could be logged onto the machine as user X, and then, when prompted, log into the web app as user Y. Am I to understand that, under Windows Authentication, there's no way to address this?
Are you sure you selected Windows Authentication While creating the Project? Confirm that and if yes, proceed to check your web.config that application authentication is set to windows.

ASP.NET processing unauthenticated file request in site with Windows Authentication: How?

I have a curious problem with a legacy ASP.NET web application using Windows Authentication. A particular page is crashing, and an inspection of the page and the site logs indicates the page is crashing because the request is not properly authenticated - no Windows identity is being requested by IIS or supplied by IE 11.
The page has a curious path; it took a few minutes to decode how it was originally assembled. The initial request is not for a specific page, but is merely a folder-only URL that is routed to Default.aspx. The handler checks the query string and redirects to specific pages accordingly.
The initial request to the site is authenticated, as evidenced by the IIS site logs. The page to which the request is redirected (Response.Redirect) does not authenticate. The absence of the Windows authentication challenge leaves the site with no automatic identity to the targeted page, leading to the page crash (code depending on the identity fails). The sequence goes this way:
Original URL: /sitename/folder/?parameter1=value&parameter2=value
IIS issues the authentication challenge, and the authenticated user is shown in the logs - eg, domain\user
The request is then handled by folder/Default.aspx (default page as defined in IIS)
Default.aspx.cs inspects the query string, and routes the request to (eg) OtherPage.aspx via Response.Redirect.
OtherPage.aspx is requested, and the request is logged - with no authentication, and no challenge
OtherPage.aspx.cs crashes (no user credential)
I am trying to theorize how or why ASP.NET is even permitting the unauthenticated file request. I have tried to reproduce the behavior in a test environment, and have been unable to do so. I have suspected that "Automatic logon in Intranet zone" might have been disabled, or that stored local credentials may be present but somehow causing a conflict, but neither of those scenarios panned out. The former did result in a failed authentication attempt and a proper 401 response from the server (the target page was not fired in a test environment).
Further research into this question has led to a solution if not a 100% dissection of the cause.
The users experiencing the problem were accessing the target site via a link in an email message. The link, for some unknown reason, inhibited the credential exchange between IE and IIS until the site URL was placed in the "Local Intranet" sites list of IE. This allowed the "Automatic logon in Intranet sites only" option to apply which, in turn, allowed the authentication to work.
The reason this is not a "100% dissection" is because these users were accessing the site previously, wherein authentication worked when the site was accessed conventionally. Exactly how the email message link inhibited the authentication exchange is not known. At the moment, I theorize that some security setting inhibits authentication when originating from an email link unless the specific site URL is explicitly qualified as a trusted or Intranet site.
Thanks for your consideration.

How does HttpContext.Current.User.Identity.Name work? and how secure is it?

I am using HttpContext.Current.User.Identity.Name to get the user name of the logged in user. I would like to know how this is working (using NTLM v2 / Kerberos) and how secure is it? Can the user try to mimic he is someone else?
Basically, from a security point of view, is there something I should be worried about, or how should I improve it?
If you are authenticating using Windows authentication (which, given your mention of NTLM/Kerberos it appears you are) then what happens is (roughly) as follows
IE sends a request with no authentication header to your web server.
IIS refuses the request with a 401 response code and tells the browser the authentication scheme it wants (in this case Negotiate, which tries Kerberos first, and then falls back to NTLM)
The kerb handshake takes place over multiple connections, and the ticket is validated against AD
IIS passes the ticket down to ASP.NET which, in the process of building the Request object populates the principal on the thread assigned to the request with the identity details from the ticket.
When you access HttpContext.User you see the principal for the current thread.
It's secure. It's basically the same authentication type used when you connect to a Windows server via file shares or anything else that is using kerberos. It's actually IIS and Windows itself doing the vast majority of the work, ASP.NET is just giving you a nice way to query the results.

Categories