In C# how can I pass a Session from one sub domain to another sub domain?
For instance I am using IIS localhost and I tried to send value from
http:\\localhost\site1 to http:\\localhost\site2
using the below way
In site1
Session["test"] = "My value";
In site2
Response.Write(Convert.ToString(Session["test"]));
The above method worked fine to pass values from one page to another but I need values to be passed from one sub domain to another sub domain i.e. one IIS web application to another IIS web application.
You can't do that with the default session state providers. You will have to roll your own using the provider model (SessionStateStoreProvider) see: here
You could also NOT use the provider model and do something like this
EDIT
HACK: I guess you can do that. here
I'm doing something similar by exchanging the session ID (and the associated settings) through a common database.
I.e.
site 1 writes its session ID to a database table, together with all required associated settings like test in your above example.
site 1 calls an URL on site 2, passing the session ID of site 1 as a query string parameter.
site 2 picks up the session ID that is passed as the query string parameter.
site 2 uses the passed session ID as a lookup key in the database table to fetch the value of test ("My value" in your example)
To enhance security, I also write a timestamp to the table and let site 2 only read those rows where the session ID and the timestamp (with some tolerance) matches. In addition, site 2 deletes the record after reading it.
Of course this is not straight forward and possibly not 100% of what you want to achieve, it may be some idea to build upon, though.
A session is specific to the application. Can you post from site1 to site2 (via JQuery for example). The post will allow you to send data (hidden). Then assign the querystring in your post to a new session variable on site2.
Related
Using Identity Serve 4 with .Net Core 3.1, razor pages. Also using Cookie Authentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
Problem -
In a web application John logged-in 2 times
1st Login on Chrome
2nd Login on edge
So, if John again trying to logged-in on 3rd time on Firefox without logout from previous browsers, then I want to logout John from 1st Login on Chrome forcefully.
I can keep the track of logins in a Session table including Session Id, User Id etc.
But I don’t know how logout user from a particular session using Session Id.
Please help.
Thanks
ASP.NET Core provides an ITicketStore interface which allows you to get control of storing user sessions. Once you provide a class implementing this interface and register it, it will call your class when sessions are being created or verified which you can then store in a database however you like, including attaching arbitrary metadata like browser ID etc.
Now that you have user sessions in your database, you can separately query them and revoke as needed in other logic, including during logins. Since you now provide the session data, simply deleting the record effectively logs the user out from that session. Note that if you use any caching layer to reduce the store requests, you'd need to remove any cached copies as well.
Note that this is separate from IdentityServer and happens with ASP.NET Core itself.
This is a good tutorial that helped me implementing this in my app.
A sample of how it looks to register in Startup, where PersistentTicketStore is my implementation:
// Persistent ticket/cookie store to provide durable user sessions
services.AddSingleton<IUserSessionRepository, UserSessionRepository>();
services.AddSingleton<ITicketStore, PersistentTicketStore>();
services.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
.Configure<ITicketStore>((options, store) => options.SessionStore = store);
Use the End Session Endpoint
The end session endpoint can be used to end a session and trigger a log out
In the log in process you will need to capture the id_token received from authentication and what user it belongs and store it on some dbo.table. You can use this same table to also keep track if a user has logged in more than once.
To log out a user or end a session you will need to pass the ID you saved as a query string parameter called id_token_hint in a GET call as shown below into:
GET /connect/endsession?id_token_hint={id_token}
For reference see the documentation here https://identityserver4.readthedocs.io/en/latest/endpoints/endsession.html#end-session-endpoint
Since you're saying you can keep track of logins, perhaps you should keep track of each session and assign a number somewhere indicating when it was logged in (1 for Chrome, 2 for edge, 3 for Firefox).
Then each time a request is made, you check in your table what the lowest number is (1,2,3 etc), and if the session matches that number, you sign the user out from that session.
await
HttpContext.SignOutAsync(IdentityServerConstants.DefaultCookieAuthenticationScheme);
Since each browser will have their own cookie, you can use the above method.
After signing someone out, the next login can be assigned 4, and if 2 makes a request you log that client out.....
Also see this: https://github.com/IdentityServer/IdentityServer4/issues/736
I have implemented this.
When a user logs in, the session id (IUserSession.GetSessionIdAsync) is manually stored in our database. The previous value of this database field is used to create a logout_token which I send to my clients. You can have look at IdentityServer4.Infrastructure.BackChannelLogoutClient to figure out how to create the token and post.
All this assumes you have backchannel logout implemented ofcourse.
I'm almost sure what I'm looking for exists, but I didn't finding on Microsoft documentation nor here.
I just want to get an unique ID (a string or a number, I don't really mind) from a client in ASP.NET 4.5, on the server side. I want this ID linked to a session, so different for each system that would connect to my server (like multiple computers or same client with different browsers), but the same if a user open multiple tabs on the same browser on my server.
I already looked on:
System.Web.UI.Page.ClientID: It is the name of the control (so always "__Page").
System.Web.UI.Page.UniqueID: It returns the same.
Session.LCID: I'm not sure to what it refers to, but it is the same if I connect to my server with different browsers.
Session.SessionID: Change each time I refresh the page or open it in a new tab.
Request.AnonymousID: Is null.
So all my attempts gave me an ID that changes everytime or never. Is there any way to get something from session ?
What you are looking for is in fact the Session.SessionID, however it comes with a caveat.
From MSDN:
When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.
I suggest using REMOTE_ADDR / REMOTE_HOST values from ServerVariables collection. These would have same values even if the user is using multiple browsers and uses different sessions from the same machine. Note that REMOTE_HOST might not always have a value.
References :
https://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx
I am very confused in my implementation of sessions in asp.net web application. My logic is once user enters user name+password, I validate credentials and then create a new session with some user info[All I am after from this point onward is that this user has access to restricted resources and a user must never be able to access those resources unless he/she is authenticated]. This I validate on each request and the rest. Here is my issue though. I have many places in the website where I have html links, and I read that if I have a link such as
<a href='resource1.aspx'>resource 1</a>
This will generate a new session id, hence in reality invalidating the existing session id, which in my case will be treated as session expired and user is sent to login page. While reading up on this issue I came across an asp.net API method[
Response.ApplyAppPathModifier(url);
] which prepends the session id to each request hence resolving the new session id generation for each link. Though it resolves session breaking issue it does add the session id next to all of the urls and now session id can be seen in the source code( view source for web page). I really don't want to use cookies and want to use session for user sessions...Can some one please help me create a system which will work the way I wish it to ? if I am doing it utterly incorrect, I would really really appreciate a details discussion and if possible some example...Thanks you much in advance..
It looks like you are trying to use cookieless sessions which add a session id to all links in order to be able to track the sessions.
The other (much more common, standard and IMO secure) approach is to use normal sessions, which auto creates a session cookie (when you use the .Session object), and uses that to determin the current session. If you don't want a cookie you'll have to stick with cookieless, and the session id in the url.
We are currently developing a simple system on ASP.net which are going to be used by users simultaneously. What I want to happen is to get each users' Name (or any other useful info) from a SQL table every time they log in to the system and use this data all throughout (Note: this data should be unique per user).
Now my question is, what is the proper approach on this kind of scenario to give unique variable/session per user? And what if I want to make this variable a global one?
Sample Scenario: A doctor logs in to the system and the code behind gets his name from the table and prompts the data on the homepage - "Welcome Doctor John!" (assuming his name is doctor John. Another user logs in to the system, gets his name and prompts respectively, now the conflict arises if the first user - John, refreshes the page and this is the conflict that I want to avoid.
Any article that I could read on with regards the matter? Any help would be much appreciated.
Disclaimer: I am still a beginner when it comes to ASP.net so my apologies for such simple question.
Session is where you will keep this information. It will be unique for each user. Read more about it at: ASP.NET Session State Overview
Just remember, that Sessions are maintained on Server for each user. They are costly. So if you keep too much data in your session then you may end up claiming more resources on the server.
Consider the following example where you retrieve your UserInfo in an object from Database.
UserInfo userInfo = GetUserInfoFromDB();
To Store information in Session:
//once user is authenticated
//store session
Session["UserInfo"] = userInfo;
To Retrieve information:
UserInfo currentUserInfo = Session["UserInfo"] as UserInfo;
if(currentUserInfo != null)
{
//info found
// assign lable Text currentUserInfo.UserName etc
}
You may see: Exploring Session in ASP.NET - Code Project
Just use the Builtin Session Management. It is unique to the user.
The Session Management stores, by default, a cookie at the users browser
to identifiy them. Only a Session Id is stored at the users browser and the other information, in your case the name, is stored on the server. You can define a Session Database for example if you have multiple webservers and want a single point to store the data.
If you have a single webserver it is very easy to use out of the box.
Set a Session variable.
Session["UserName"] = yourUsernameVariable;
Retrieve a Session variable.
var userName = Session["UserName"];
Here are some tutorials.
A Beginner's Tutorial on ASP.NET State Management
Exploring Session in ASP.NET
ASP.NET Session State Overview
What are some options in regards to maintaining user data while they are logged into my mvc4 site? I am building off of the Internet Application template and right now I am using User.Identity.Name to get the logged in user's username that they used to login with. I'd like to be able to also store and access several other pieces of information about the user across every page on the site. Can I still use User.Identity somehow and apply other attributes to it? I started building a ProfileModel that I could pass to views, but then I don't believe I would be able to pass other models to those views, not sure.
I'm open to suggestions as far as persistent user data, and thank you for any help.
EDIT 1: When I say persistent, I mean while they are logged in, the data itself is already stored in an external database, so I won't be doing any writing of this information, simply pulling it from the database, then holding onto it for the duration of them being logged in.
You'll want to leverage Session for that. Consider the following code:
Session["Profile"] = profileObj;
or maybe you just want to store a string:
Session["SomeSetting"] = value;
What you need to store in Session is unclear, and effectively irrelevant, you can store anything. You can access the Session from any Controller.
Then later on you can get the value out like this:
var profile = Session["Profile"];
// if the profile variable is null then it doesn't exist in Session yet
In response to #AaronLS, Session lasts the duration of the IIS session that's created when the user first accesses the site. Do keep in mind that these sessions are reset if inactive for a period of time (I believe the default IIS timeout is 20 minutes) so you'd want to leverage the null return value to know that you need to redirect the user to the login page to login again.