Are you using SAML for your single sign on? If you are, there is the SAML module in the Marketplace that does this for you.
https://docs.mendix.com/appstore/modules/saml
If you aren’t using SAML, you could still look at the code for this module as it works in the way you describe. You could base your own code off of this.