asp.net identity expire bearer token after 20 min - asp.net

i have a web service, users can login to service and give bearer token.
in local everything is good, but in server (shared host, windows 2012, iis 8.5) after 20 min, token has been expired !!!
my AccessTokenExpireTimeSpan is :
AccessTokenExpireTimeSpan = TimeSpan.FromDays(900),
also in my first request, i give a delay about 5 sec. what is problem ?

I asume that you in production have multiple servers. And ASP.NET Identity is using the server's machine key to generate the token bearer. So after 20 minutes you have been "redirected" to another server with another machine key.
One solution is to override the machine key of the servers. With setting the machine key in the web.config. So all servers has the same machine key.
<machineKey validationKey="534766AC57A2A2F6A71E6F0757A6DFF55526F7D30A467A5CDE102D0B50E0B58D613C12E27E7E778D137058E" decryptionKey="7059303602C4B0B3459A20F9CB631" decryption="Auto" validation="SHA1"/>
How to generate and set machine keys:
https://technet.microsoft.com/sv-se/library/cc755177%28v=ws.10%29.aspx
http://docs.orchardproject.net/Documentation/Setting-up-a-machine-key
Solution 2 - If don't have access to IIS
If you dont' want to modify the machineKey on the IIS or doesn't have access to it you can ovveride ASP.NET Identity token provider easily by ovveriding the default settings in the startup.cs file.
An example of that can you find here: https://github.com/eashi/Samples/blob/master/OAuthSample/OAuthSample/App_Start/Startup.Auth.cs

Related

Asp.net core 3.1 webapi iis 8 not able to connect to sql server

I have asp.net core 3.1 web api. When I run the project locally in Visual studio, it works fine. But when I publish it to IIS and run it, I get the error.
500 Internal Server Error","error": "A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)"}
Or Login failed for user domain_name\machine_name.
connection string looks like this
"ConnectionStrings": {
"ABCDB": "Server=xxx-test,80;Database=abc;Integrated Security=true;MultipleActiveResultSets=true;"
},
I have the hosting bundle installed for .net core 3.
my app runs under ApplicationPoolIdentity which is added to the database and has the permissions. My application pool is set to No Managed Code with ApplicationPoolIdentity.
The endpoints for the api which are not connecting to the database work just fine on published version but anything that is connecting to the database gives the error.
I referred to couple of links but hard luck.
https://www.loganfranken.com/blog/1345/why-your-web-application-cant-connect-to-sql-server/
IIS fails to pass windows credentials through to SQL Server for ASP.NET Core app
Why asp.net core app uses different user than AppPool identity for Windows Authentication when connecting to SQL Server?
Any help is appreciated.
Edit: The only things that works for me running the appPool under custom account(my credentialis) but does not work under appPoolIdentity on IIS
It seem that your environment needs a reset.
1- Manually check your app folder under IIS to see if any cached files or similar ones could be deleted.
2- Ideally, install it in a new folder under IIS
3- Reset the IIS
4- Make a hard refresh of the web browser
your connection string should be like this:
"ABCDB": "Data Source=xxx-test;Initial Catalog=abc;Integrated Security=SSPI;Persist Security Info=True;"
and add application pool name of your published application of security/users folder of your DB:
IIS APPPOOL\<apppool name>
Or add a new user account to you DB with user name and password. In this case you will also have to change the connection string.
I was having the same issue.
Other .NET Core 3.1 web apps are running just fine with the same authentication method (anonymous authentication) on the same IIS instance on the same server using the same connection string to the same MS SQL DB.
With this one particular .NET Core 3.1 web app, IIS is causing the app to try to authenticate to MSSQL DB with the username {DOMAIN}\{Computer Name}
The issue for me was that the connection string for the one app with the issue had "Trusted_Connection=True".
I knew that I would get this authentication interception from IIS with Integrated_Security but did not realize that Integrated_Security is synonymous with Trusted_Connection.
So the fix is to remove Trusted_Connection = True or Integrated_Security = True from the DB connection string in the app. If you need either of these two for your code to work (but are providing a username and password in the DB connection string), you should probably re-evaluate your code. Otherwise, the behavior OP and I observed should be what you want to happen and this isn't a problem.

Is my machine key auto-generated or isolated?

I'm attempting to share .ASPXAUTH cookies between an ASP.NET MVC 4 application (in IIS 7.5) and a service using HttpListener on the same host.
The browser presents the cookies to both correctly, but my service receives System.Web.HttpException: Unable to validate data. at FormsAuthentication.Decrypt, which I would expect if the two applications were using different machine keys.
So: how do I find out if my machine is configured to use different machine keys?
the default setting of IIS is autogenerate machine-key and isolate per application
you can change this setting globaly in your machine.config or localy (per application) in your web.config
for details please see
http://technet.microsoft.com/en-us/library/cc772287(v=ws.10).aspx
http://technet.microsoft.com/en-us/library/cc754909(v=ws.10).aspx
You can see the current setting for machine-key in IIS manager. For details, see http://blogs.msdn.com/b/amb/archive/2012/07/31/easiest-way-to-generate-machinekey.aspx

Decrypting ASP.NET Auth Cookie Value without FormsAuthentication.Decrypt Method

I try to read / decrypt the value of an auth cookie from forms authentication that is written in AES but without setting the MachineKey in the web.config because I cannot modify this config myself.
Therefore I can't use FormsAuthentication.Decrypt because this uses the machine key internally.
You didn't specify the ASP.NET version but in 2.0 and I think still in 4.0, you can override the machineKey in your web.config.
Check out the section "Web Farm Deployment Considerations".
http://msdn.microsoft.com/en-us/library/ff649308.aspx#paght000007_webfarmdeploymentconsiderations
You can generate a machine key online with this tool: http://aspnetresources.com/tools/machineKey

WMI access denied error when query remote computer from ASP.NET

I have an ASP.NET application that executes a WMI call to a remote system. The application Web.config contains <identity impersonate="true"> and <authentication mode="Windows"> options which, as I understand, should force the application code to be executed on behalf of the application user.
The problem is that I get "Access is denied" error, despite the fact I can successfully execute the my WMI request from PowerShell console on the same host under the same user to the remote server in question.
// this doesn't work
ManagementScope scope = new ManagementScope();
scope.Path.NamespacePath = "root\\virtualization";
scope.Path.Server = "vs01";
scope.Connect(); // <-- here comes exception
# this works just fine
Get-WmiObject -Namespace 'root\virtualization' -Class Msvm_ComputerSystem -ComputerName vs01
Dumping HttpContext.Current.User.Identity.Name, System.Security.Principal.WindowsIdentity.GetCurrent().Name, System.Threading.Thread.CurrentPrincipal.Identity.Name properties suggest that impersonation works as expected.
Ideas? Could the issue be some kind of .NET or IIS security?
You need to have a domain administrator enable Delegation for your web server machine. This is a security feature of Kerberos. By default an intermediate server (in this case your web server) is not allowed to pass the impersonation context of a client to the remote server unless it has been given Delegation permission. If you don't do this the remote target server will see the request coming in as Anonymous User... which if its properly secured will be denied access.
Note its a common policy to only allow an intermediate server to delegate to specific target servers (called constrained delegation), so if your web app needs to be able to call WMI on any server in your network you may have problem. Talk to your domain admin.

<machineKey decryptionKey="AutoGenerate"... being ignored by IIS. Won't invalidate previous session's cookies

(See question below for more context):
Are there any situations in which
<machineKey
validationKey="AutoGenerate,IsolateApps"
decryptionKey="AutoGenerate,IsolateApps"/>
in web.config would fail to AutoGenerate a new machineKey on App Pool recycle? This is the behavior I'm seeing...
I'm using standard ASP.NET FormsAuthentication in an MVC app. If I log a user in using FormsAuthentication.GetAuthCookie and don't use a persistent cookie (relying on the browser's session to remember my authorized state), I would expect recycling the IIS App Pool to invalidate the session's knowledge of this cookie...and thus logout all users who don't have persistent cookies.
This DOES happen on one of my IIS installs (XP), but on a different IIS configuration (Server 2K3) the FormsAuthentication cookie (under the standard name ".ASPXAUTH") remains valid and continues to authorize the user.
Does anyone know why this is happening or what configuration controls this behavior?
Obviously recycling the app pool has no control over whether or not the browser still sends the .ASPXAUTH cookie (as long as I haven't closed my browser and the cookie hasn't expired).
In the case of the IIS install that properly denies authentication after a recycle, I can see the incoming cookie in Request.Cookies during the Application_BeginRequest event...but once control moves to the next event available in Global.asax.cs (Application_AuthenticateRequest), the cookie has been removed from the Request.Cookies collection.
Why does this not happen for both IIS/ASP.NET configurations?
In case this isn't clear, a simpler way of forming the question is:
Why does HttpContext.Current.Request.Cookies[".ASPXAUTH"] change from {System.Web.HttpCookie} to null when I step, in a single request, from Application_BeginRequest to Application_AuthenticateRequest?
More debugging information:
If I attach the following code to Global.asax.cs's FormsAuthentication_OnAuthenticate event...
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
var val = cookie.Value;
try
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(val);
}
catch (Exception)
{
}
}
...then during a request before I recycle the IIS App Pool, no exception will be caught. After recycling the IIS App Pool, when the exact same .ASPXAUTH cookie is sent from the browser, a Cryptographic exception is caught ("Padding is invalid and cannot be removed.")
Why is this?
Our application is stateless (no session required), yet we had a situation where an app pool recycle caused invalidation of all machinekey-encrypted cookies on a server environment (above described issue). This was caused because the machinekey changes with every recycle, which should not be the case.
The AutoGenerate modifier specifies that ASP.NET generates a random key and stores it in the Local Security Authority (LSA)
https://msdn.microsoft.com/en-us/library/w8h3skw9%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
"Local Security Authority (LSA)" means the user assigned to app pool, see below for more details as this turned out to be the problem.
The issue lied in the fact that we are using a dedicated user account for running the application pool, and simply creating the user and then assigning it to the app pool did not seem to trigger the creation of the registry section where the machine key is then stored. You can verify this yourself by checking registry
HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion/ProfileList (for getting the SID of the user you just created; if the user is not there, then this is already a bad sign)
HKU/[UserSIDFromBefore]/Software/Microsoft/ASP.NET/... (a machine key should be stored there)
The solution was to logon as that user once on the computer (normal Windows logon screen) so that the relevant registry sections are created. There might be quicker or more subtle ways to establish the registry sections though.
Internet Information Services (IIS) 7.0 (Windows Vista, Windows Server 2008) introduced application pool identity, a new isolation mechanism that helps provide increased security for servers that run ASP.NET applications. However, sites that are running under the application pool identity do not have access to the HKCU registry. This is where the ASP.NET runtime stores its auto-generated keys. The result is that ASP.NET cannot persist the auto-generated key when the application pool is reset. Therefore, every time w3wp.exe is reset, a new temporary key is generated.
Note This is not an issue in IIS 7.5 (Windows 7, Windows Server 2008 R2) and later versions. On these versions of IIS, ASP.NET can persist its auto-generated keys in a different location that survives application pool resets.
https://support.microsoft.com/en-us/help/2915218/resolving-view-state-message-authentication-code-mac-errors
Forms Authentication cookies have nothing to do with Session state.

Resources