Skip to content

Instantly share code, notes, and snippets.

@jaredk2g
Created July 25, 2016 21:59
Show Gist options
  • Save jaredk2g/947b6b38a842e5438fb9ca0f4cc6847f to your computer and use it in GitHub Desktop.
Save jaredk2g/947b6b38a842e5438fb9ca0f4cc6847f to your computer and use it in GitHub Desktop.
Invoiced C#.NET Single Sign-On Example
using Jose.JWT;
using System;
using System.Text;
public class SSO
{
public static void Main()
{
// Depends on this JWT library: https://github.com/dvsekhvalnov/jose-jwt
// The SSO key can be obtained from Invoiced
// in the dashboard by going to Settings > Developers
const string ssoKey = "{INVOICED_SSO_KEY}";
const string invoicedUsername = "yourcompany";
// Here you would supply the customer ID on Invoiced.
// https://invoiced.com/docs/api/#customers
int invoicedCustomerId = 1234;
// Build the SSO token using JWT
DateTimeOffset dto = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
int exp = dto.ToUnixTimeSeconds() + 86400; // link expires in 1 day
var payload = new Dictionary<string, object>()
{
{ "sub", invoicedCustomerId },
{ "iss", ".NET Backend" },
{ "exp", exp }
};
var secretKey = Encoding.ASCII.GetBytes(ssoKey);
string token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
// Now you can redirect the user to this URL to jump into
// your billing portal signed in as the given customer ID
string url = "https://" + invoicedUsername + ".invoiced.com/login/" + token;
// Will produce URLs that look like this:
// https://yourcompany.invoiced.com/login/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEyMzQsImlzcyI6IlJ1YnkgQmFja2VuZCIsImV4cCI6MTQ1NTY1MjIxMH0.7kClQ2UAVEZ7xYus7ZHGRePnzDG5mBrcgIo6rZuo-Dw
Console.WriteLine("SSO URL for customer ID {0}: {1}", invoicedCustomerId, url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment