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

Hi, 

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.

Thanks

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];
System.Debug(ASession);
List<AuthSession> AList = New List<AuthSession>();
For(AuthSession a : ASession){
If(a.SessionType != 'UI')
AList.add(a);
}
System.Debug(AList.size());
Delete AList;

Related: https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_authsession.htm

https://help.salesforce.com/s/articleView?id=sf.remoteaccess_revoke_token.htm&type=5

https://developer.salesforce.com/blogs/developer-relations/2011/11/revoking-oauth-2-0-access-tokens-and-refresh-tokens

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