What different ways are Machine Keys useful in asp.net?
I think the following are correct but thought there may be more.
Multiple applications can use the same cookie
Multiple servers can work with the same viewstate
MachineKey is used for:
ViewState encryption and validation
Forms Authentication (or Federated Authentication) uses this key for signing the authentication ticket
Having a Web App installed on multiple servers requires same Machine Key configured on all of them in order for Load Balancing to work.
To see all details, please refer to: MSDN How To: Configure MachineKey in ASP.NET 2.0
Machine key is also used to encrypt/decrypt the webresources.axd parameters.
Even on a single server the machine key should be configured, because any recycle of the app domain will generate a new key when it is set to auto. This causes the next postback just for pages rendered before the recycle, to cause a viewstate validation error, and also issues with the resources during that time.
Encryption - very common.
Related
We have two servers that run on the same machine under the same domain.
Both written in ASP.NET and uses the Identity framework.
I need to implement Single Sign-On (and single sign out) between them.
Actual sign-in is done in AJAX (I POST the username and password, the server authenticate the user and sets the session, then sends the redirect data URL to the client).
I found overwhelming amount of information about OWIN, the Identity framework, Claims, etc.
I found tutorials explaining how to create projects using just about any modal dialog and any Wizard there is in Visual Studio, which I tried to understand but really is useless to me, as I already have authentication system up and running.
I even found some demos claiming to implement SSO in all kinds of ways, and some Stackoverflow questions that said to simply put this and that values in the web.config and you're done, which seemed strange to me and I figured out I'm missing some basic understanding of how it works.
Still, I can't understand how SSO works in ASP.NET Identity.
Can someone please explain it to me in a simple manner, or refer me to some kind of such explanation?
Again: I have two authentication systems up and running. What code and/or configuration changes I need to make to get Single Sign-On working?
First, if you want them to share authentication, they need to be working on the same user store. In other words, you should factor out the Identity initialization code (ApplicationUser, ApplicationDbContext, ApplicationUserManager, and ApplicationSignInManager) into a class library that both applications share. Trying to mantain and share two separate databases with user data is going to be an impossible and insurmountable task.
Then, you need only ensure that both applications utilize the same machine key. The auth cookie is encrypted, and since the encryption is based on the machine key, both applications need to use the same key to encrypt/decrypt that cookie.
Since you've already stated that they will both be hosted on the same domain, that's all there is to it.
We (our IT partner really) recently changed some DNS for a web farmed site we have, so that the two production server have round-robin DNS switching between them. Prior to this switch we didn't really have problems with WebResource.axd files. Since the switch, when we hit the live public URL, we get an error:
CryptographicException
Padding is invalid and cannot be removed.
When we hit the specific servers themselves, they load fine. I've researched the issue and it seems since they're sharing assets between two servers, we need to have a consistent machineKey in the web.config for each server so they can encrypt and decrypt consistently between the two. My questions are:
Can I generate a machineKey via a tool on the server, or do I need to write code to do this?
Do I just need to add the machineKey to the web.config on each server or do you think I'll need to do anything else to make the two server work together? (Both web.config's currently do not have a machineKey)
This should answer:
How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations
Web Farm Deployment Considerations
If you deploy your application in a Web farm, you must ensure that the
configuration files on each server share the same value for
validationKey and decryptionKey, which are used for hashing and
decryption respectively. This is required because you cannot guarantee
which server will handle successive requests.
With manually generated key values, the settings should
be similar to the following example.
<machineKey
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>
If you want to isolate your application from other applications on the
same server, place the in the Web.config file for each
application on each server in the farm. Ensure that you use separate
key values for each application, but duplicate each application's keys
across all servers in the farm.
In short, to set up the machine key refer the following link:
Setting Up a Machine Key - Orchard Documentation.
Setting Up the Machine Key Using IIS Manager
If you have access to the IIS management console for the server where
Orchard is installed, it is the easiest way to set-up a machine key.
Start the management console and then select the web site. Open the
machine key configuration:
The machine key control panel has the following settings:
Uncheck "Automatically generate at runtime" for both the validation
key and the decryption key.
Click "Generate Keys" under "Actions" on the right side of the panel.
Click "Apply".
and add the following line to the web.config file in all the webservers under system.web tag if it does not exist.
<machineKey
validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>
Please make sure that you have a permanent backup of the machine keys and web.config file
If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.
Open IIS manager.
If you need to generate and save the MachineKey for all your applications select the server name in the left pane, in that case you will be modifying the root web.config file (which is placed in the .NET framework folder). If your intention is to create MachineKey for a specific web site/application then select the web site / application from the left pane. In that case you will be modifying the web.config file of your application.
Double-click the Machine Key icon in ASP.NET settings in the middle pane:
MachineKey section will be read from your configuration file and be shown in the UI. If you did not configure a specific MachineKey and it is generated automatically you will see the following options:
Now you can click Generate Keys on the right pane to generate random MachineKeys. When you click Apply, all settings will be saved in the web.config file.
Full Details can be seen # Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
I have an C# ASP.net website hosted with www.blacknight.com.
Sometimes when I login to my website I get the following error:
This happens in about 1 in ever 10 login attempts. I have contacted them and they assured me that its not hosted on a Web Farm or cluster and to check my ViewState.
Does anyone know what could be wrong here? I cant reproduce it everytime so its hard to track down.
Please see the KB article at http://support.microsoft.com/kb/2915218 for a resolution to this issue. In particular, you should set an explicit <machineKey> element in Web.config.
Appendix A of that article tells you how to generate a <machineKey> element.
Never set EnableViewStateMac=false. And you should never use a key that you got from a third-party generator. Only use one that you generated yourself.
Is it possible that IIS is recycling your application between the original page load, and the login attempt? If you don't specify a <machinekey /> in the web.config, a new machine key will be generated on application start up. And then, when you attempt to validate the viewstate that was generated on the old machine key during post back, this exception would be thrown.
I have an ASP.NET application using FormsAuthentication. Whenever I restart the application or web server, my authentication token is invalid and I have to log in again. What's going wrong?
By default, FormsAuthentication validates authentication data on every request by having the client store an encrypted copy of the data. The encryption key is stored in Machine.config. The specific key to use is in <machineKey decryptionKey="YOUR KEY HERE">.
If you do not provide a decryption key, one is automatically generated on application startup. Since it is randomly generated, it will be different each time you restart the application. On the validation phase, FormsAuthentication attempts to decrypt the authentication data and fails. Then the user is no longer logged in.
There are two ways of resolving this problem.
Providing a machineKey in Machine.config will give FormsAuthentication a consistent key to use, so validation will succeed with the encrypted cookie from previous application runs.
Using <forms protection="None" ... /> in Web.config will disable authentication data encryption and validation. This is insecure and only appropriate for development, since it will be trivial for users to impersonate each other.
The default session state mode in asp.net is in-proc (cached in-memory) unless you specify otherwise. When the application shuts down, memory is cleared and the in-proc session cache is therefore lost.
#dhasenan The machinekey config will only be an issue if the application is deployed across a web farm or the cloud. The idea of overriding the machine-level config of the Machinekey element is to ensure that multiple machines are using the exact same keys.
Therefore, the machine key shouldn't be an issue because if one is not provided at the application level, the machine key in the machine.config will be used instead, which is persisted and static, so it will not be regenerated between sessions.
I have two website consider it as website1 and website2.
In website2 there is a login page .When a user click on the login button it will call a HTTPhandler in website1 to authenticate user.On successful authentication user information will be stored in a Session variable from handler.
Then it will redirect to a page page1.aspx in website1.But the previously set session is not available in the page1.aspx .What will be the issue?
I checked the session id in first request(when calling handler in website 1 from webiste 2) and Second request( redirecting to the page1.aspx from the handler) the session id is different.
How can i retain the session data?
You need to store session data in another process shared to both web site.
You can do it intwo different ways:
Configure an SQL server
Configure SessionState service, a Windows service used to share informations.
In both cases you have to change both web.config files to support the new session mode.
I.e. to use SQL:
Prepare a database (from command prompt):
cd \Windows\Microsoft.NET\Framework\v4.0.30319
aspnet_regsql.exe -ssadd -E -S localhost\sqlexpress
Modify web config as following:
<sessionState mode="SQLServer"
sqlConnectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Test" allowCustomSqlDatabase="true"/>
You don't need to change your code.
Correct me if I an wrong, AFAIK different domains cannot share a single session. One way to handle this is to carry the data to the other site through cookie [encrypt the values for security], then copy this cookie value to the session in the other site receiving it and destroy the cookie.
And if the sites are in different servers you need to handle the "sticky session" so that servers share the session.
This situation sounds kind of similar to one I have experienced and worked on before, where one web application acts as the login page while another is the actual app where all your work is done. I can describe what I did in the hope that you find it useful.
Like you I had one web app which had the login page (so in your example this would be website2). When the login form submitted I then redirect to a fake Login.aspx page in website1 - this is where we differ I think as I'm not sure of your specific reason for using a HttpHandler.
In my case the website2 Login.aspx page is actually just the way into the web application; it has no markup, just code-behind which will authenticate the user, perform setup (e.g. set session variables) and then redirect to another page such as Homepage.aspx. This particular scenario has worked for me, so maybe your problem revolves around the use of a HttpHandler though I would not be able to tell you why.
In order to retain the same session date across two different servers running ASP.NET web applications you must configure your session state to be managed out of process. This means the actual session state data variables will be stored outside of worker process and in another process that is able to make the session data available to other machines.
To achieve this you can configure your application to use SQL Server to store session state and make it available to multiple servers in your farm. The TechNet article Configure a SQL Server to Maintain Session State (IIS 7) provides details on hor this is done in IIS 7.
If you are using IIS 6 then the steps to configure are somewhat different and I can provide further details on this if needed.
In order for this to work you do need to ensure that both servers are running applications within the same domain, e.g. myapp.com, otherwise the ASP.Net session cookie will not be passed between the two servers. ASP.Net uses the cookie to lookup the session state stored in SQL Server and will therefore not find any matching session if the cookie is not passed on requests between the two servers.
i think IRequiresSessionState will not help because context is different.
once we had the same problem but that was passing asp session varibles to .net. How ever you can do it here also.
on both website create a page setsession.aspx
now if you are on page say web1/page5.aspx and want to go to web2/page3.aspx
you redirect to web1/setsession.aspx?togo1=web2/page3.aspx
in both setsession.aspx logic in to extract sessiondata and place them in querystring
so the web1/setsession will redirect to web2/setsession.aspx?sess1=value1&sess2=value2&togo=page3.aspx
web2/setsession.aspx will check for togo querystring and if found will extract all querystring name and value will set them in session and will then redirect to togo value.
you need to differentiate togo1 and togo carefully.
Session sharing between websites is going to require hand-coding. You could hack the asp.net framework to get this working, but I feel that this is not a clean way of achieving what you set out.
If user authentication is all you are doing from website, is it possible to use alternative? Single Sign On mechanisms will help you out here.
Something like SAMLSSO could help you in this case.
You have two websites which are hosted on different servers, it means you have two different processes running on separate machines, so sessions will be definitely different. Same session can't be shared across processes because by default asp.net support in-memory session.
Here you would need to think about storing sessions information which can be shared between two processes (i.e. out of process). Ideal way to store sessions information in databases. For this you can consider Stefano Altieri code sample above.
I don't think you really want to share session information between two websites at all. From what I can gather from comments, what you're really trying to do is have a user authenticate in one website (give you a username and password which are validated) and then have that "logged in" state transferred to another website which doesn't handle authentication for itself.
What you are describing is the Delegated Authentication model.
In this model, your application hands-off authentication to other systems which it trusts to provide information about users.
There are two well-known protocols which provide this mechanism:
OpenID
This is intended to facilitate users logging in with their own identity providers (Google, Facebook, Microsoft Account). It's a very good choice if you're running a public-facing website, as most users will already have an account they can log in with.
WS-Federation
This is intended to facilitate users logging in with identity providers which are managed by known trusted parties, such as partner organisations.
From version 4.5, the .NET Framework has built-in support for WS-Federation via the Windows Identity Foundation component (and is also available for earlier versions as a separate download). This automates the task of delegating your authentication to an Identity Provider.
It also provides components for you to write your own Identity Provider, should you want to create your own, but you shouldn't have to; you can find various existing implementations to perform this job for you.
The problem you're trying to solve is a very difficult one, especially trying to make it secure enough to be reliable. The good news is that smarter people than you or I have spent years working out very clever ways of doing this. You should use what they have done and not try to cobble together something out of Session state.
In the long-run it's best to let the smarter men do the hard work for you.