function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
David Benkoel 3David Benkoel 3 

Remove user session programmatically after an OAuth 2.0 flow


I'm implementing both "login" and "logout" features for a third-party client, usinf SF Identity as an IdP.

Login is based on an OAuth 2.0 flow, which issues an access token and a refresh token. Once this flow executed, SF also grants a session ID to the newly logged user, and sets a browser cookie accordingly (sid).

For the logout, I tried to revoke both tokens via the standard oauth2/revoke endpoint): the user session remains active (why ???).

Then I tried to use the same API, with the sid as the payload (that I'm getting through UserInfo.getSessionId()): the session still remains active.

So, how to remove a user session using Apex code?

What I need to achieve is basically what is done from the Salesforce setup, Session Management section, with the Remove button.


I tried to revoke 
SwethaSwetha (Salesforce Developers) 
HI David,
You could try querying AuthSession object and delete with below code
List<AuthSession> ASession = [select Id,SessionType,CreatedDate, IsCurrent, SessionSecurityLevel, UsersId, NumSecondsValid From AuthSession];
List<AuthSession> AList = New List<AuthSession>();
For(AuthSession a : ASession){
If(a.SessionType != 'UI')
Delete AList;


If this information helps, please mark the answer as best. Thank you
David Benkoel 3David Benkoel 3
Hi Swetha,

That's exactly what I did meanwhile, thanks!

One issue remains yet: deleting a user session automatically revokes the OAuth 2.0 access token issued earlier. But it does not revoke the refresh token.

If a user session is removed, in other words if a user gets logged out, how can he recreate an access token and a session by using a refresh token which is still alive?

This sounds not normal to me