Automatically attempting to log a user in
- Last updated on May 12, 2023 at 12:37 AM
If you wish to attempt to automatically log a user in to your Hosted Knowledge Base when they visit a protected article, you can do so by adding the following JavaScript to your Knowledge Base Customize settings.
You will need SSO setup for this to work.
The main thing to note here is to update the "referrer" to be the same domain as where your SSO will take place. This help to prevent the user from getting stuck in a redirect loop.
The catch is though, that if you were to have a user in your product and you want to link to a private article, the initial redirect won't work if they are coming from the same domain that you set as the "referrer". In those cases, simply add ?autologin=true
to the end of the Knowledge Base link that you send the user to.
// attempt to auto login const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const autologin = urlParams.get('autologin'); const referrer = document.referrer; if ( autologin === 'true' || referrer !== 'https://yoursite.com' // prevents a redirect loop ) { const body = document.querySelector('body'); if (body.classList.contains('logged-out')) { const h1Tag = document.querySelector('h1'); if (!h1Tag || h1Tag.textContent === '401: Not Authorized') { const suggestedAction = document.querySelector('.kb-error__suggestion'); if (suggestedAction) { suggestedAction.innerHTML += '<br /><br /><strong>You will be auto redirected to login</strong>'; } const loginLink = document.querySelector('a[href="/sso/login"]'); if (loginLink) { loginLink.click(); } else { window.location.href = '/sso/login'; } } } }