Skip to content

Instantly share code, notes, and snippets.

@GFoley83
Forked from paully21/aspnetmvc_discourse_sso.cs
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GFoley83/8d3578ce1c54b093d45c to your computer and use it in GitHub Desktop.
Save GFoley83/8d3578ce1c54b093d45c to your computer and use it in GitHub Desktop.
public ActionResult DiscourseLogin()
{
if (string.IsNullOrEmpty(Request.QueryString["sso"]) || string.IsNullOrEmpty(Request.QueryString["sig"]))
return Content("Invalid");
string ssoSecret = "YOUR SSO SECRET"; //must match sso_secret in discourse settings
string sso = Request.QueryString["sso"];
string sig = Request.QueryString["sig"];
string checksum = getHash(sso, ssoSecret);
if (checksum != sig)
return Content("Invalid");
byte[] ssoBytes = Convert.FromBase64String(sso);
string decodedSso = Encoding.UTF8.GetString(ssoBytes);
NameValueCollection nvc = HttpUtility.ParseQueryString(decodedSso);
string nonce = nvc["nonce"];
//TODO: Add your own get user information
//Ensure user is logged in by adding the [Authorize]
//Attribute to this controller method and validate the
//user has permission to access the forum
string email = "testuser@test.com";
string username = "testuser";
string name = "Test User";
string externalId = "21";
string returnPayload = "nonce=" + Server.UrlEncode(nonce) +
"&email=" + Server.UrlEncode(email) +
"&external_id=" + Server.UrlEncode(externalId) +
"&username=" + Server.UrlEncode(username) +
"&name=" + Server.UrlEncode(name);
string encodedPayload = Convert.ToBase64String(Encoding.UTF8.GetBytes(returnPayload));
string returnSig = getHash(encodedPayload, ssoSecret);
string redirectUrl = ConfigurationManager.AppSettings["DiscourseUrl"] + "/session/sso_login?sso=" + encodedPayload + "&sig=" + returnSig;
return Redirect(redirectUrl);
}
public string getHash(string payload, string ssoSecret)
{
var encoding = new System.Text.UTF8Encoding();
byte[] keyBytes = encoding.GetBytes(ssoSecret);
System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(keyBytes);
byte[] bytes = encoding.GetBytes(payload);
byte[] hash = hasher.ComputeHash(bytes);
string ret = string.Empty;
foreach (byte x in hash)
ret += String.Format("{0:x2}", x);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment