How to generate nonce from client-side Javascript

I am using <script type="text/discourse-plugin" version="0.8.9"> in my instance’s <head> and it provides me access to the api object. What I can’t figure out however, is how to generate a nonce with it.

I’m detecting whether the visitor is logged into discourse or not, and whether they have a special cookie from the rest of my (non-discourse) site which indicates they’re logged in. If these 2 conditions are met, I do some magic to auto-log them into discourse. So far I’ve got it all working, except I have no nonce with which to create the signature that discourse needs when the user is redirected back.
With no nonce I get the error:

Verbose SSO log: Nonce has already expired

How can I use the api object to ensure a nonce gets generated for my auto-logins?

Can’t you just redirect the user to the magic URL that triggers SSO?
I’m not sure what the URL is and cannot check right now, it’s something like /session/sso.

1 Like

I’d definitely follow our official SSO guide first Official Single-Sign-On for Discourse (sso)

2 Likes

In case anyone else finds this, I followed @fefrei’s advice

  1. Identify that the user has logged into your site
  2. Identify that the user is not currently logged into discourse
  3. Send the user to discourse’s /session/sso page which will trigger the sso with the nonce
  4. The SSO endpoint that gets the call from discourse recognizes it needs to do things automatically
  5. Log the user in and provide the necessary information back to discourse to complete the flow

Its not pretty (causes the screen to flash) but it works. Thanks :+1:

3 Likes