How can I clear browser cache (memory / disk cache) after logout? - javascript

I use asp net core mvc + js. One type of my pages have cache.
[ResponseCache(Location = ResponseCacheLocation.Client, Duration = 60)]
public async Task<IActionResult> StaticContent(string path)
{
// code
}
I have a problem when user logout on this page. User sees his account after logout because page was cache. If refresh page cache clear and user does not see account.
I try location.reload(); on js when logout click but reload work earlier than logout work on server. I try change Vary header but I change Vary only page which I redirect after logout
How can I clear cache after logout? Any ideas?

As the King King says, if you enable the client cache , there is no way to tell the client side in the server-side. The only way is just tell the CX to clear the cache. Since once the browser obeys the cache rules you send here, the only opportunity you will have to retract your cache rules is the next time the browser requests the page.
Normally, the dynamic pages should not attempt to set client-side caching if you want them to stay dynamic.

I find answer on microsoft site https://learn.microsoft.com/en-us/aspnet/core/performance/caching/response?view=aspnetcore-5.0#responsecache-attribute
They say don`t cache content which using user info.
I cache individual parts of page without account info.
I use
<cache expires-after="" />
Thanks all

In your logout post, you can clear a session that may solve your problem.
HttpContext.Session.Clear(); //this will clear all session
HttpContext.Session.Remove("sessionName"); //this will clear a specific session

Related

How to build "Selectable Keep Login" function by Cookie/JWT

I'm using Node(axios,pinia)+Vue3 as frontEnd,and node(express,bcrypt,jsonwebtoken)+MongoDB as BackEnd to build a SPA web.
I use JWT for login authentication and save at localstorage.
Now it only can keep login.
Hoping have Selectable "Keep Login" function like some forum usually have.
(After closing browser/shotdown will need to login again.)
I don't use sessionStorage for this website user often open new tab.Some cross tab problem bother me and I thought cookie might got better solution.
I can imagine only "Always login"/"temp login" can be done likes. But with selectable I can't thought a simple way to apply it.
Like now I'm thought still use LocalStorage(LS) for Vue to run,but also have Session Cookie(as Cookie)(Not sure the name but the cookiewill be deleted when all webs closed).
Keep login need no change for me.If set to temp login, then the setting will be save to JWT,all front/back could know.
Use cache as signal for closing browser,if (temp login)&&(no cookie){clear LS}.
However I wonder the localStorage can be extract so the func will not safty enough? Then a school computer will be disaster
I'm new to cookie/session,and want to know any better way for safty/efficent. I will prevent XSS.
It would be wonderful to have your experienct/Idea!
Poor language and consult at here first,If any describe not clear/too detail please tell me,I will try to edit it, thanks!
The use of JWT is below:
BackEnd use bcrypt verify user password and response a JWT(with userID for db to find,also save to user login record DB) and other basic user info.
Some response data like JWT,basic userinfo will be save in localstorage to let Vue decide display login/admin/different page.
When user send a request(some login-action), JWT will also be send as BearToken to bo verified by backEnd that JWT was record in that user login record.
So JWT is the only security key,the user's login record should have same JWT.
Because it save in localstorage,user must logout!(Despite I can set some limit time.)

Workaround for banking authentication redirect to prevent session loss / need for session restorage

My question is kind of a follow-up to this somewhat old post, which is why I though of asking here, instead of just asking via comment there.
My question is straightforward: I have an online platform with very tight session restrictions (samesite, httponly, short lifetimes, etc.), and while a user is logged into the platform, they may execute payments. These payments may redirect them to an intermediary foreign domain and then back to mine for authentication. Without a workaround (that I've coded and it works) for the session restorage, the session gets lost and the process breaks.
Even though I have a working workaround; I wondered if it is not possible to open the redirect page in a new tab via js (because the redirect has to work in js at the current stage anyway), confirm the payment, then, when the payment gets confirmed, close the banking tab and do the according refreshes on the platform tab. Is this possible via js ? The problem I see with the linked solution is:
btn.onclick = () => {
const win = window.open(
'http://www.stackoverflow.com',
'Secure Payment');
const timer = setInterval(() => {
if (win.closed) {
clearInterval(timer);
alert('"Secure Payment" window closed!');
}
}, 500);
}
How can I know when the client finished the authentication in the other tab, + prevent the redirect that will automatically triggered in that case, to the redirect target post-authentication that you normally provide when requesting the payment? Is there a way to track all of this in js? Because I don't see any...?

Redirect to specific page after refreshing (oidc.js)

I am using .NET Core (+IdentityServer) backend along with the SPA React application.
Whenever I change the page inside my SPA application the url updates. (for example: / to /users).
The issue:
Whenever I refresh the page with F5 or want to go to the specific component connected to route using url only I get the following action inside my browser:
Basic state when pressing enter in the url: localhost:3000/users
After pressing enter: http://localhost:3000/signin-oidc#id_token=...
When the user is logged in the page redirects to the main url: localhost:3000/
So, basically I am always redirected from the current url to the main one.
How can I make the application redirect back to the localhost:3000/users on the refresh or url change using oidc-client in react?
What is the best practice to allow user to be able to refresh the page (or go to the specific url) keeping in mind that the user is already authorized?
If I understand you right and you are using the oidc-client-js library to implement Open Id Connect then my NodeJS Code Sample may be useful to you, and the Authenticator class in particular.
RESTORING THE PRE-REDIRECT LOCATION / DEEP LINKING
This is managed via code like this, which is also useful if the user has bookmarked a location within your app and needs to login first:
// Store the state when redirecting the page
await this._userManager.signinRedirect({
state: location.hash,
});
// Restore it afterwards - and remove tokens from the URL
const user = await this._userManager.signinRedirectCallback();
history.replaceState({}, document.title, user.state.hash);
RELOADING THE PAGE OR OPENING A NEW TAB
This is best managed via silent token renewal using the Authorization Server session cookie, so that there is no top level redirect.
await this._userManager.signinSilent();
RUNNING MY SAMPLE AGAINST YOUR SYSTEM
It may help you to have something to compare against, by running the sample against your own system, by changing the details in the SPA and API config files to point to Identity Server.

How to destroy Vaadin 8 session on browser close or tab close?

How to destroy session on browser close/tab close in Vaadin? We can use javascript to handle this. I tried below code: Page.getCurrent().getJavaScript().execute("window.onbeforeunload = function (e) { var e = e || window.event; closeMyApplication(); return; };");
Problem with above script is, it will fire onbeforeunload event on page refresh also. Also, how to handle this situation in mobile devices(touch devices)?
I recommend to set closeIdleSessions to true and short heart beat interval, which should force Vaadin internal session clean up mechanism to destroy sessions faster after web browser has been closed.
If that is not helping, there is also helper add-on https://vaadin.com/directory/component/cleanupservlet-add-on
Copying from
https://vaadin.com/docs/v8/framework/application/application-lifecycle.html
Session Expiration
A session is kept alive by server requests caused by user interaction with the application as well as the heartbeat monitoring of the UIs. Once all UIs have expired, the session still remains. It is cleaned up from the server when the session timeout configured in the web application expires.
If there are active UIs in an application, their heartbeat keeps the session alive indefinitely. You may want to have the sessions timeout if the user is inactive long enough, which is the original purpose of the session timeout setting. If the closeIdleSessions parameter of the servlet is set to true in the web.xml, as described in "Using a web.xml Deployment Descriptor", the session and all of its UIs are closed when the timeout specified by the session-timeout parameter of the servlet expires after the last non-heartbeat request. Once the session is gone, the browser will show an Out Of Sync error on the next server request. To avoid the ugly message, you may want to set a redirect URL for the UIs, as described in "Customizing System Messages".
The related configuration parameters are described in "Other Servlet Configuration Parameters".
You can handle session expiration on the server-side with a SessionDestroyListener, as described in User Session.

OAuth 2.0 way of grant permissions in JS and use serverside, (no session)

I have created several apps by using FB.login() in the middle of the steps on a page, and rely on C# gaining access to the same session and thereby access (and save) the user info correctly.
JS:
FB.login(function (response) { if (response.session) {// user has authed} });
C#:
public FacebookSession CurrentSession { get { return (new CanvasAuthorizer()).Session; } }
In two days Facebook will remove the session support, which breaks this functionality. As I understand I am now required to have a page-reload before serverside can detect the granted permissions. (https://developers.facebook.com/docs/authentication/). It seems I have to either redirect the user to the login-box and then setup a callback, or still use javascript but reload the page once the user grants permissions.
This is really sad, since the apps works very well by showing the user the app-interface, before asking any permissions and reloading the page. Does anyone know how to get the JS coupled to the serverside once again?
make sure you are on v5.2.1 which supports the new cookie format and in js set oauth:true when calling login.
Your existing code will continue to work without any server side (c#) changes.

Categories