Hello.
Regrettably, we are not familiar with the details of your custom implementation, however, it may depend on where you use this piece of code. The code you are using should be used when authenticating a user in the admin app. If you want to authenticate the user on the front-end app using Xperience API, check this: https://docs.xperience.io/managing-users/user-registration-and-authentication/configuring-single-sign-on#Configuringsinglesignon-Implementingsinglesign-onviatheXperienceAPI
Best Regards,
Kentico Support