Sharing sessions across applications using the ASP.NET Session State Service - c#

I am trying to share sessions between two web applications, both hosted on the same server. One is a .net 2.0 web forms application the other is as .net 3.5 MVC2 application.
Both apps have their session set up like this:
<sessionState
mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
/>
In the webform application I am posting the the session key to the MVC app:
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session["myvariable"] = "dan";
string sessionKey = HttpContext.Current.Session.SessionID;
//Followed by some code that posts sessionKey to the other application
}
I then recieve it in the MVC application and try use the same session like this:
[HttpPost]
public void Recieve(string sessionKey )
{
var manager = new SessionIDManager();
bool redirected;
bool IsAdded;
manager.SaveSessionID(HttpContext.ApplicationInstance.Context, Id, out redirected, out IsAdded);
var myVar = Session["myvariable"];
}
The key is being posted but the session does not seem to get loaded in the MVC app, i.e. sessionKey is null. Can what I am trying to do be done?

I did it this way:
Basically the idea is both apps use native .net sessionState stored in sqlserver. By using the same machine key and making a small tweak to a stored procedure – both apps can share any session keys and/or forms authenication.
Both apps would do something like this in their web.config:
<sessionState mode="SQLServer" sqlConnectionString="Data Source=.\SQLEXPRESS;User Id=test;Password=test;Application Name=AppName" />
<machineKey
validationKey="SOMEKEY"
validation="SHA1" decryption="AES"
/>
Session state db would need to be set up on a database server, that both apps can see.
Docs for doing this:
http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx
Command that would need to be run:
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin>aspnet_regsql.exe -E -ssadd --sstype p -S .\SQLEXPRESS
Stored procedure (TempGetAppID) tweak to:
#appId int OUTPUT
AS
-- start change
-- Use the application name specified in the connection for the appname if specified
-- This allows us to share session between sites just by making sure they have the
-- the same application name in the connection string.
DECLARE #connStrAppName nvarchar(50)
SET #connStrAppName = APP_NAME()
-- .NET SQLClient Data Provider is the default application name for .NET apps
IF (#connStrAppName <> '.NET SQLClient Data Provider')
SET #appName = #connStrAppName
-- end change
SET #appName = LOWER(#appName)

The problem is that session keys are scoped to the applications, so two applications having the same session key in fact have separate sessions.
You can do one of two things:
Put both applications as a virtual directory under a common IIS Application. I don't think this is a good idea, but it will work.
Roll your own session data solution for the data you want to share. Possibly using the backend database as the common storage, if you have one that is.
Based on Justin's comment, just to clarify option 2 is not refering to the SQL state managemet for out of process sessions. I mean for you to actually manually manage the shared data for the two sessions, possibly using a database.

You can use a common Machine key to generate same Session ID inside both applications for a given user. Additionally, you should also plan on storing sessions of both applications in a common store such as ASP.NET State Service or a distributed cache.
You can use NCache distributed cache which takes provides session sharing feature between different applications. You specify same Application ID tag for both apps inside session state settings which allows you to share session object provided you have same Session ID generated for both applications.

Related

WordPress External DB Authentication

I have 2 different websites. One is the Wordpress site and the other a oldish asp.net site.
I want to log in on the wordpress site OR the ASP.NET site and be logged in on both sites. Also, I want to have a link to the ASP.NET site from the wordpress site.
I.E. I'll log in on the Wordpress site using ASP.Net user account. (Only admin accounts should see these buttons) Once logged in, I'd click on the Manage Users link that will take me to another page (Asp.net, this could be the same domain or another location), And here I'll be able to make CRUD changes to the Users.
My php knowledge is very limited >.< ...
I've looked at these Wordpress plugins but both seem outdated and unable to run. I am also un-sure whether they would do what I want.
https://wordpress.org/plugins/external-db-auth-reloaded/
https://wordpress.org/plugins/external-database-access-using-wp-user/
Not sure, if this is helpful.. but you can access SQL Server Database with PHP.
Loading the Driver
You can download the SQL Server Driver for PHP at the Microsoft Download Center. Included in the download are two .dll files: php_sqlsrv.dll and php_sqlsrv_ts.dll.
Configuring the Driver
The SQL Server Driver for PHP has three configuration options:
LogSubsystems:
Use this option to turn the logging of subsystems on or off. The default setting is SQLSRV_LOG_SYSTEM_OFF (logging is turned off by default).
LogSeverity:
Use this option to specify what to log after logging has been turned on. The default setting is SQLSRV_LOG_SEVERITY_ERROR (only errors are logged by default after logging has been turned on).
WarningsReturnAsErrors:
By default, the SQL Server Driver for PHP treats warnings generated by sqlsrv functions as errors. Use the WarningsReturnAsErrors option to change this behavior. The default setting for this option is true.
Creating a Connection
The sqlsrv_connect function is used to establish a connection to the server.
$serverName = "(local)";
$connectionOptions = array("Database"=>"DBNAME");
/* Connect using Windows Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if( $conn === false )
{ die( FormatErrors( sqlsrv_errors() ) ); }
By default, the sqlsrv_connect function uses Windows Authentication to establish a connection.
The sqlsrv_connect function accepts two parameters: $serverName and $connectionOptions (optional).
$serverName – This required parameter is used to specify the name of the server to which you want to connect. In the code above, a connection is established to the local server. This parameter can also be use to specify a SQL Server instance or a port number.
For example:
$serverName = "myServer\instanceName";
-or-
$serverName = "myServer, 1521";
$connectionOptions - This optional parameter is an array of key-value pairs that set options on the connection. In the code above, the database is set to DBNAME for the connection. Other options include ConnectionPooling, Encrypt, UID, and PWD.
Note: The UID and PWD options must be set in the $connectionOptions parameter to log into the server with SQL Server Authentication.
Go through below link for more details:
Accessing SQL Server Databases with PHP

How to maintain state between ASP.NET MVC4 Applications in Same Domain?

I am new to MVC and I have been given a task to maintain state between applications that are in same domain - cookie would be one option ,Is there any alternate option other than cookie storage ?
you can do that by setting the domain name in web.config
<httpCookies domain=".domain.com"/>
There are several
1) Running a state server
2) Using sql server to store state
a) doing this in the web.config
3) Using some sort of Database server (mssql/nosql/oracle/...) (this is my preference. Because you do not need to rely on Microsoft to correctly save state in 1 or more db)
a)saving a guid to the cookie and then saving the important state data you need to sql server

In asp.net, To access login username and id in entire application. Where can I store Login user name and id in application.?

I am developing an application in asp.net using vs2010.
In application, Admin can create different user accounts using Microsoft member registration wizard.
Users can Login with created credential using Microsoft login control.
Now,I have to access this Logedin user's UserID and UserName in entire application's different forms.
Currently I am accessing this details by writing code in all forms by
MembershipUser newUser = Membership.GetUser();
Guid newUserId = (Guid)newUser.ProviderUserKey;
So, where can i store this login user's UserID and UserName in a common place. So I can access this details from common place?
Please Help me.
Thanks,
Well - that depends fully on where you persist the data for your application.
If you use a database for storage, then logically the data should belong in there, in a user table, with a connectionstring to the database in your application's configuration.
If not using databases, then you properly need some file based storage, for example XML or something you invent yourself and then have a parser which serialize/deserialize the data from files.
In both instances, you'll need to consider security and hashing/salting and make sure the data is kept secure.
I tend to use a static helper class, which stores (and loads) data in HttpContext.Items for the duration of any request. So you would just need to call GetUser once per request. If even that is too much for you, you can use a Session, for example - but don't forget that sessions only live for so long, so be prepared to reload the data if it's lost due to session timeout.
The static class has to be somewhere accessible from the whole application - in a web site project, this means the App_Code folder.

Session Sharing Between 2 Website

I am doing session sharing between two website on same server using sqlserver session mode but it is worked on virtual directory not worked on server while uploaded the site on the server.
Both website using same database and same server.Can anybody tell me that what is i missed.
You might need to add the connection settings for session state to your live machines web.config.
<configuration>
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString="Integrated Security=SSPI;data
source=SampleSqlServer;" />
</system.web>
</configuration>
You need custom session state implementation that will allow to share session between 2 different sites.
Default SQL session state indexes record with {session key (i.e. from cookies) + application ID} - as result even the same session ID on the same server will get separate information for different sites. There is no supported way to configure it to ignore application ID part.

How to maintain same session in two different sites

let suppose i have two domains
1. abc.com
2. xyz.com
now the thing i want to do that i have a index page on both sites and there is a image on both index page , but when i click next in abc.com and image changes on abc.com at the same time i made a session variable in sql server . Now leave abc.com and come to xyz.com
the index page of xyz.com automatically gets refresh by ajax function after 2 second , now when page get refresh it will make a request to server and pick the next image name from session which we stored using abc.com and by getting the we will show the latest image on xyz.com .... Note . both sites are using the same server
can i do this ? . If yes then how ?
You can share sessions between sites using SQL server as the session manager, I did it following these instructions, works well.
these steps are taken from: Share ASP.net session between domains
ASP.NET APPLICATION : CSASPNETShareSessionBetweenSubDomains Project
Overview
Summary:
Session can be set to different modes (InProc, SqlServer, and
StateServer). When using SqlServer/SateServer mode, Session will store
in a specific SQL Server/Sate Server. If two ASP.NET Web Applications
specify the same SQL Server as Session Server, all Sessions store in
the same database. All in all, if using SQL Server Session, it is
possible to share Session between different ASP.NET Applications.
Since ASP.NET stores Session Id to cookie to specify current Session,
so in order to share Session, it is necessary to share Session Id in
the cookie.
The CSASPNETShareSessionBetweenSubDomains sample demonstrates how to
configure a SessionState Server and then create a SharedSessionModule
module to achieve sharing Session between sub domain ASP.NET Web
Applications.
Two ASP.NET Web Applications need to run in the same Root Domain (can
use different ports). Steps:
Configure SQL Server to Store ASP.NET Session State.
Run "C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe
-S localhost\sqlexpress -E -ssadd" to add Session State support to Sql Server Express 1.
If you haven't added Session State to SQL Server, when you configure
a web site to use SQL Server Mode Session State,
System.Data.SqlClient.SqlException will be thrown saying "Invalid
object name 'tempdb.dbo.ASPStateTempSessions'."
Configure ASP.NET Web Applications to Use SQL Server to Store Session and Use specific decryptionKey and validationKey.
Add this settings to web.config file to use SQL Server Session
State:
Add this settings to web.config to use specific decryptionKey and
validationKey:
If you host the applications in IIS, please run the Application Pool
under an account who can log into the database. Otherwise
System.Data.SqlClient.SqlException will be thrown saying "Cannot
open database 'ASPState' requested by the login. The login failed."
Write SharedSessionModule Module to Achieve The Logic of Sharing Session
a. Implement Init() method to set Application Id read from
web.config.
b. Implement PostRequestHandlerExecute Event to store Session Id to
cookie with
the same domain and root path.
Configure ASP.NET Web Applications to Use SharedSessionModule Module.
Add this config to web.config to use SharedSessionModule Module:
If you run the applications in your own domains except localhost,
please don't forget to change the value of RootDomain after
publishing.
Run and Test
a. Add a new Web Page. b. Add two Buttons (used to Refresh the page and Set Session) and one Label for displaying
Session value. c. On Page_PreRender() method, read Session and display it in Label. On Button Click
Event, Set Value to Session. d. Create a new Web Site with the same config as Web Site 1, but set different value
to Session e. Now open two sites in two tabs. Now if you set Session Value in site1,
you can retrieve the same value in site2. So they use the same Session.
1 Remove Session State from Sql Server. Run
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe -S
localhost\sqlexpress -E -ssremove" to remove Session State support
from Sql Server.

Categories

Resources