I am sharing the way that we generate the return url, to hopefully shed some more light on this problem:
public String generateSSORedirectURL(String nonce, String email, String uid) {
//generate the return payload
HashMap<String, String> params = new HashMap<String, String>();
params.put("nonce", nonce);
params.put("external_id",uid);
params.put("email",email);
params.put("username",email);
params.put("require_activation","false");
params.put("name",email);
params.put("return_sso_url","https://discourse-site/session/sso_login");
log.info("params {}", params);
//prepare the return payload
String encodedParams = params.keySet().stream()
.map(key -> key + "=" + encodeValue(params.get(key)))
.collect(Collectors.joining("&"));
log.info("encoded parameters {}", encodedParams);
String returnPayload = Base64.getEncoder().encodeToString(encodedParams.getBytes());
log.info("return Payload {}", returnPayload);
//calculate the hmacSha256 signature for the payload
byte[] hmacSha256 = calcHmacSha256(ssoSecret.getBytes(), returnPayload.getBytes());
log.info("hmacSha256 sig {}", hmacSha256);
String hmacSha265Hex = String.format("%x", new BigInteger(1, hmacSha256));
log.info("hmacSha256, sig in Hex {}", String.format("%x", new BigInteger(1, hmacSha256)));
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("sig", hmacSha265Hex);
params2.put("sso", returnPayload);
log.info("params2 {}", params);
String encodedParams2 = params2.keySet().stream()
.map(key -> key + "=" + encodeValue(params2.get(key)))
.collect(Collectors.joining("&"));
log.info("encoded parameters {}", encodedParams2);
//build and return the query string
String queryString = forumUrl + "session/sso_login?" + encodedParams2;
log.info("queryString {}", queryString);
return queryString;
}