ASP Session changes on each Angularjs http requset - c#

The website use Angularjs as frontend to call API(Asp.net in IIS).
Each request passed Global.asax Start_Session generate new session ID.
It supposed to use the same session to the same user.
I am trying to send GET request with this URL:
$http({method: 'GET', url: 'http://localhost:59893/initSite.aspx'})
I read this qusetion but the answer doesn't help in my case:
ASP.NET: Session.SessionID changes between requests.

I'm not sure about ASP but with PHP I have found a similar problem with API requests. You can't rely on ASP/PHP to remember the session ID's on each request from different clients, you need to post a session ID with each request to the API where that session ID is checked against a list of logged in users in a Database.
This would be the proper way of handling logged in users with a remote API.
Check this similar answer: Auto Logout when user leaves the application without doing logout action

If you want your session Id to be same for every request for that particular session...store something in the session variable(anything dummy)...then it will give the same session id..
It happens if you don't have anything stored in your session variable..you will always get a new session id for the same session itself.
Do something like below
Session["any_name"]="anything";

Related

How to Logout user from a particular session Identity Server 4, .Net Core?

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.

ASP.NET : Why can I read session cookies even if no cookie exists?

It appears that I am able to read the SessionID at any time, even if no cookie currently exists!
Dim SessionID As String = Request.Cookies("ASP.NET_SessionId").Value
This code will always return a value, presumably the ID held by IIS server side.
The cookie appears to be generated only when a request to store session information is made.
Why is this?
and ...
If I am using session state server will the SessionID ever differ from the cookie SessionID and which take priority if one of the ID's is lost or reset?
EDIT
If the app_pool is reset. A new session ID must be created will this cause the session cookie to be updated also? As this could create potential conflicts for users already logged in.
When a user accesses a website powered by ASP.NET IIS generates a SessionID to uniquely idetinfy the users session.
If the website is using cookies:
<sessionState mode="StateServer" cookieless="UseCookies"/>
A cookie named ASP.NET_SessionId will be generated only when a request to store session information is made by the webpage. If no session information is stored a cookie will not be created but the user will still have an active SessionID.
The SessionID is read from IIS when no cookie is present.
The SessionID on the server always takes precedence and will update the session cookie when a new request to store information in the cookie is made.
Every time that an user access the website and a session is opened ASP.Net by default creates a SessionID unless you specify the cookieless option:
If you are using a session state server the SessionID should be the same across all web servers otherwise you wouldn't be able to find the same user.
If the ID is lost or reset the state server will simply create a new one and write a new cookie with the new SessionID and the old one will be deleted after the expiration time.

Can't determine if my asp.net session implementation is correct

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.

Session lost after first Twitter OAuth request

Using ASP.NET MVC, sessions are stored in SQL database (never had a problem with them, and didn't use web farm). Using also Twitterizer2 library. Using Firefox.
First request, no browser instances is opened. Browser instance is started.
We have simple form "Publish on twitter" and submit button Share.
When Share is clicked we store message in Session and redirect to Twitter's OAuth authentication (on POST submit).
We authenticate OK and return to our Action and before posting to Twitter we check if message is stored in Session (and it isn't! - it is lost immediately after Twitter redirection)
When we try another messsage Share it is now working (Session).
We solved it using a Cookie but we don't have a clue while we lost Session (first time) after returning from Twitter.
Any deas?
I'd like to ask how did you maintained the session without cookie the first time?
I think the problem can be of the cookie set process. I also experienced similar problem before a couple of weeks.
The problem was that when I make request for REQUEST token, this request is internal HTTP request (not via user browser). As a response to this request I get REQUEST token and then set it in the user session.
$token = getRequestToken();
$_SESSION['token'] = $token;
However, if the user just came to my site for first time without a session, he does not have a session cookie to sent me. Internally at the web site I have created a session for him, and stored the token inside it, but then instead of sending him response with cookie headers included, so that he "accepts" my session, I make redirect to the provider authorize endpoint. This way, the user does not get the session cookie, and when he is returned back, he is like a new user for my site.
This is the flow of the process that happened to me:
create user session in the database
setcookie(usersession) // add headers to the eventual response
get request token
set the token in the session
redirect the user (user does not receive the session cookie)
user goes to authorization point
user returns, but he is a new user for me
I'd be interested to know if you had similar problem :)
Best regards
check the request and callback domain are the same
i.e. you are making request for oauth from localhost and callback to 127.0.0.1

How do I get a session by SessionID in C#

I'm working on an ASP.NET MVC app and I'm trying to use the 'Uploadify' JQuery plugin. One issue I'm running into is that there is apparently a well known bug in regards to sending up cookie information with Flash (which uploadify utilizes). So I've tried sending the auth token and the session id with my request when uploading a file using uploadify. This is great in that I can figure out if someone is authorized, but I can't seem to get the session and thus do not have access to session variables. If I have the SessionID, is there a way to get the Session in C#?
Session["myVar"] = "1234";
<%= this.Session.SessionID %>
HttpContext.Session.SessionID
Note that you can get the session ID, but you need to store things in the temp data or it will keep giving you new IDs.
This post has the answer

Categories