Integrating #OpenYolo into a existing username/password login

March 6, 2018 Leave a comment


When you first develop a website, everyone starts from the premise that the user creates an account and stores it in your own database, the idea of OAuth logins from Google / Facebook – only come as an afterthought as you start getting more users.

But then you have an issue, you have existing users that are authenticated against your own database, and other users that are going to be authenticated against Google YOLO.

I had the same issue with where I just added OpenYOLO.

What I did was, when a signin happens with OpenYolo, I pass the response (email, name, token) back to the server. Which records the email address, and a random guid as the password, and returns the user account back to the client.

If the user is already registered, then it looks for a matching email address, and returns that account, without checking the password.

This now opens a serious security hole. If someone fakes the response from OpenYolo and includes an email address of another user, then they can become any user on the system.

This is where token validataion comes in, and it’s really important, since without it, you don’t know if your website is really talking to Google, or a hacker.

Where idToken is in the response from Google’s OpenYolo, now jCredential is as follows;
         "aud": "",
         "sub": "xxxx",
         "email": "",
         "email_verified": "true",
         "azp": "",
         "exp": "xxx",
         "iss": "",
         "jti": "xxx",
         "iat": "xxx",
         "nbf": "xx",
         "name": "xxx xxxx",
         "picture": "",
         "given_name": "xxx",
         "family_name": "xxx",
         "alg": "xxx",
         "kid": "xxxx"

Importantly, you can now be sure that the information is definitely from Google, and you should expect the email field to match the email field in the request. Otherwise you should fail silently,  since it’s probably a hacker.

I did find that OpenYolo doesn’t work with IE11, since it uses promises, but hey, you’ve always got your origional login system.


Categories: Uncategorized

Adding properties at #runtime to an object in C#

March 5, 2018 Leave a comment


C# is designed to be a statically typed language, i.e. when you define your type at compile time, you can’t change that type at runtime. Which is the opposite to how Javascript operates.

However, with the recent addition of dynamic types and the Expando Object, it is possible to add a property to an object as follows;

 dynamic c = new ExpandoObject();
 c.a = 1;
 c.b = 2;

However, one of the not-so good things about the ExpandoObject, is that it doesn’t take a constructor argument, that would allow you to start off with an anonymous type, and then add some properties to it. This is where Clay comes in – which is a NUGET package you can install and reference as follows;

using ClaySharp; // Install-Package Clay

Then you can define much deeper types, and add properties to them.

dynamic New = new ClayFactory();

var person = New.Person(
FirstName: George,
LastName: Washington,
Country: new {
Name = United States,
Code = US

person.Sex = Male;
Console.WriteLine(person.FirstName +   + person.LastName +  is  + person.Sex);

That’s all great. However, you may notice, if you try to serialize the object to JSON using Newtsonsoft.JSON, or System.Web.Script.Serialization then you either get an error (Newtonsoft) or an empty string.

However, there is a similar project called Dynamitey which you can install using:

 Install-Package Dynamitey

And you change the line

dynamic New = new ClayFactory();


dynamic New = Builder.New();

This nuget package doesn’t seem to be compatible with .NET Core vNext (i.e. Mac), but it does create objects that are serialisable to JSON, like the following:

string output = JsonConvert.SerializeObject(person, Formatting.Indented);


  "FirstName": "George",
  "LastName": "Washington",
  "Country": {
    "Name": "United States",
    "Code": "US"
  "Sex": "Male"


Categories: Uncategorized

Automatically sign in users to your website with Google #YOLO

March 4, 2018 1 comment


How often have you been fed-up with having to create yet another account, with a username, and password – that you are going to forget. Your users feel the same way when they visit your website, and you prompt them to enter a new username and password.

Of course systems like Oauth have existed for ages, but you have to manage server side code to exchange auth tokens, and manage token refreshes, which is just a pain. Google have come out with a system called YOLO – which makes it super easy, using client-side code only, to grab the user’s public profile (i.e. name, email and profile pic) as long as they have signed in elsewhere on the same browser.

It makes it really seamless to capture a user’s profile, without any effort from the user.

Google have a great step-by-step guide, and I’d recommend reading their instructions, rather than me replicating them here. But effectively, you set up your Oauth credentials in the Google API console, to get your client ID, then you add a script reference to :

Then use code such as the following to grab the user’s profile:

window.onGoogleYoloLoad = (googleyolo) => {
console.log(“Yolo loaded!”);
const retrievePromise = googleyolo.retrieve({
supportedAuthMethods: [”,
supportedIdTokenProviders: [
uri: “”,
clientId: “”
retrievePromise.then((credential) => {
if (credential.password) {

} else {
// A Google Account is retrieved. Since Google supports ID token responses,
// you can use the token to sign in instead of initiating the Google sign-in
// flow.
}, (error) => {
// Credentials could not be retrieved. In general, if the user does not
// need to be signed in to use the page, you can just fail silently; or,
// you can also examine the error object to handle specific error cases.

// If retrieval failed because there were no credentials available, and
// signing in might be useful or is required to proceed from this page,
// you can call `hint()` to prompt the user to select an account to sign
// in or sign up with.
if (error.type === ‘noCredentialsAvailable’) {
const hintPromise = googleyolo.hint({
supportedAuthMethods: [”
supportedIdTokenProviders: [
uri: “”,
clientId: “”
hintPromise.then((credential) => {
console.log(“hint worked”);
if (credential.idToken) {
// Send the token to your auth backend.
}, (error) => {
console.log(“hint failed”);
switch (error.type) {
case “userCanceled”:
// The user closed the hint selector. Depending on the desired UX,
// request manual sign up or do nothing.
case “noCredentialsAvailable”:
// No hint available for the session. Depending on the desired UX,
// request manual sign up or do nothing.
case “requestFailed”:
// The request failed, most likely because of a timeout.
// You can retry another time if necessary.
case “operationCanceled”:
// The operation was programmatically canceled, do nothing.
case “illegalConcurrentRequest”:
// Another operation is pending, this one was aborted.
case “initializationError”:
// Failed to initialize. Refer to error.message for debugging.
case “configurationError”:
// Configuration error. Refer to error.message for debugging.
// Unknown error, do nothing.

Categories: Uncategorized

Simplifying #webpush – a #HTTP to #VAPID service.

March 2, 2018 Leave a comment


If you don’t want, or can’t install the server side components to handle web push notifications, you can use this service to handle the push notification. As long as you can do a HTTP request, you can call this.

Send VAPID authenticated Web Push notifications with a single HTTP request

API Endpoint

Call with the following querytring variables:

  • endpoint
  • – The endpoint returned by pushManager.subscribe

  • p256dh
  • – The P256DH Key returned by pushManager.subscribe

  • auth
  • – The Auth key returned by pushManager.subscribe

  • publicKey
  • – The Public Key from VAPID

  • privateKey
  • – The Private Key from VAPID

  • payload
  • – The Json Payload

Here’s the source of the project if you want to host this yourself;


And here’s a demo in action from

Categories: Uncategorized

#WebPush Notifications using #NodeJS or C#

March 1, 2018 Leave a comment


Web push notifications allow websites to communicate with their users after the user has left the website. Think of it like collecting an email address from a user. You ask the user to provide their email address, then at some point in the future, you can send a message to your user from your server – even if that user is no longer on your website.

It has three main parts,

  • A website, which subscribes a user to notifications.
  • A server-side script that sends notifcations
  • A service worker js file, which displays notifications when they arrive.

To get started, you need to create a pair of VAPID encryption keys;

npm install web-push -g
web-push generate-vapid-keys

You should then get a response like the following


Public Key:

Private Key:


Now, lets get started on the client-side, your website.

function askPermission() {
return new Promise(function(resolve, reject) {
const permissionResult = Notification.requestPermission(function(result) {

if (permissionResult) {
permissionResult.then(resolve, reject);
.then(function(permissionResult) {
if (permissionResult !== ‘granted’) {
throw new Error(‘We weren\’t granted permission.’);

function urlBase64ToUint8Array(base64String) {
const padding = ‘=’.repeat((4 – base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, ‘+’)
.replace(/_/g, ‘/’);

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
return outputArray;

function subscribeUserToPush() {
return navigator.serviceWorker.register('service-worker-2.js')
.then(function(registration) {
const subscribeOptions = {
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(

return registration.pushManager.subscribe(subscribeOptions);
.then(function(pushSubscription) {
console.log('Received PushSubscription: ', JSON.stringify(pushSubscription));
return pushSubscription;


What this does is that it asks the user for permission to send them push notifications, and then subscribes the user to the push notifications using the VAPID public key above.

Note also, that it registers the service worker “service-worker-2.js”, which will be used later to display the notifications once recieved.

The service worker file “service-worker-2.js” should have the following content:

self.addEventListener(‘push’, function(event) {
console.log(‘[Service Worker] Push Received.’);
console.log(`[Service Worker] Push had this data: “${}”`);

const title =;
const options = {
icon: ‘images/icon.png’,
badge: ‘images/badge.png’

event.waitUntil(self.registration.showNotification(title, options));

If you now open this page, accept notifications, and then view the console window, you’ll see an endpoint url, Auth key, and p256dh key, you’ll need all these in the next step.

Now, let’s take a look on the server side. Create a new folder for your node project, and run npm init to create your package.json.

Run npm install web-push  to pull down a library which will help you in this next step.

const webpush = require(‘web-push’);
const vapidKeys = {
privateKey: ‘OnWh44RFgdpwcUPpxgFHwJVMDHdhcPKEajFIR7Epdp4’

const pushSubscription = {

webpush.sendNotification(pushSubscription, ‘Send!’);

You can see both the public and private keys from VAPID are included, also the push subscription includes the endpoint, p256dh and auth keys.

Finally, you call webpush.sendNotification(pushSubscription, ‘Send!’); where “Send!” is your payload.

If you prefer to use C# on your back-end, you need to install via NuGet “WebPush” and “Newtonsoft.Json” and use the following code

var pushEndpoint = @"";
var p256dh = @"BGbqvhUQPyC-QSrm_pQ45Als58dKuehPn-mz1PGXzSvghowZJmEroBMIMAVzuc6QB2zxo032H2NSWgzboMhHFK8=";
var auth = @"SvXCMDcjgzkGWjFNNVtMOw==";

var subject = @"";
var publicKey = @"BIzwHJzJXHkqjncpDVSZGbwbbIvoHT6LH4Z6oIpFwiZyArDPeHMuuQzWo_ncBWzidBhAvI_mh7QWrSndRnaneCE";
var privateKey = @"L4NtEgeRS0gVnvK-qJ6ovvz5LE2onltGdJy1dLhXD7I";

var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
var vapidDetails = new VapidDetails(subject, publicKey, privateKey);

var webPushClient = new WebPushClient();
	var payLoad = new
		message = "Yo mamma!",
		title = "My Website"
	string strPayload = JsonConvert.SerializeObject(payLoad);

	webPushClient.SendNotification(subscription, strPayload, vapidDetails);
catch (WebPushException exception)
	Console.WriteLine("Http STATUS code" + exception.StatusCode);
Categories: Uncategorized – view #SMS messages received online with #NodeJS

February 28, 2018 Leave a comment

burnersms is a website, where you can send a text message to a phone number, and the text and sender will appear on the webpage – after you refresh. It could be used for those services that want to use your mobile phone to send authorisation codes to, but you don’t want to share your real phone number.

That’s the idea anyway – but it really was a way so I could learn a bit about NodeJS, on a practical project.

So, here’s the architecture. The mobile messages actually come in via – which offer an API that allow you view calls and texts sent to a given number. The API returns in XML, but I’ve used xml2js to convert the XML to a JSON.

The project is hosted on a Windows server, where I installed the latest version of NodeJs, NPM and IISNode. I had to do an IISReset after the installation for it to work.

I used NPM init to create my package.json file, which keeps track of the NPM packages I installed during the development. I used the following packages;

  • request – Making life sooo much easier for HTTP requests
  • xml2js – Converting the XML returned from the API to JSON
  • underscore – A collection of handy Javascript functions just as _.filter
  • ejs – A HTML templating engine, so I can separate my NodeJS and HTML presentation
  • moment – handles date formatting, so I can display dates in a pretty format

The whole back end is as follows;

var http = require(‘http’);
const request = require(‘request’);
var parseString = require(‘xml2js’).parseString;
const _ = require(‘underscore’);
const ejs = require(‘ejs’);
var moment = require(‘moment’);

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});
request(‘;, (err, response, body) => {
if (err) { res.end(err); return; };
parseString(body, function (err, result) {
// result.ArrayOfMessages.Messages
var TextMessages = _.filter(result.ArrayOfMessages.Messages, function(msg){
return msg.MessageUrl[0] == “”;
element.prettyDate = moment(element.DateArrived[0],”YYYY-MM-DDTHH:mm:ss”).format(“MMMM Do YYYY, h:mm:ss a”);
ejs.renderFile(“burner.ejs”, { messages: TextMessages }, {}, function(err, str){

This file – which I called Burner.js; and I’ve ommitted the username/password for the API call, you can get one yourself!

It starts a server which listens on port 80, and immediately calls the API. If successful, it converts the XML to JSON. It then uses the underscore filter function to remove elements from the response that refer to phonecalls rather than text messages. Following that, it uses moment to parse the DateArrived property, which is in an ugly Year-Month-Day format to a more readable Month Day Year format.

Once all that is done, it uses EJS to load the file “Burner.ejs” from the same folder, and passes through the filtered object to the page. The resultant HTML is then output using res.write

You need to call res.end() once the operation is complete, since this will close the connection between server and client, otherwise the client may hang.

Burner.ejs, is effectively a HTML file, and I won’t include the entire HTML here, just the dynamic part:

<% messages.forEach(function(message){ %>
<%= message.prettyDate %>
<%= message.Sender[0] %>
<%= message.MessageText[0] %>
<% }); %>

It looks almost like Classic ASP … but you can see how it iterates through each message in the messages array, and puts the output between the td’s

Now, that’s almost a wrapped up, just to say that you also need a web.config document in that folder to tell IIS that burner.js is to be handled by the server, not a javascript file to be sent verbatim to the client. – and that burner.js is the default document.

<add name=”iisnode” path=”burner.js” verb=”*” modules=”iisnode” />
<add value=”burner.js” />

Categories: Uncategorized

Accessing the Google #Analytics API via C#

February 26, 2018 Leave a comment


Say you want to import Google Analytics Data into a database, for display on your own admin system, or as an alert if you stop getting traffic. – here’s some code to do so in C#,

Grab a few packages from Nuget to get started:

Google.Apis and Google.Apis.Analytics.v3

First, off you need to authenticate against Google, you can do this in a number of ways but I found OAuth easiest.

string[] scopes = new string[] {
AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data
AnalyticsService.Scope.AnalyticsEdit, // Edit and manage Google Analytics Account
AnalyticsService.Scope.AnalyticsManageUsers, // Edit and manage Google Analytics Users
AnalyticsService.Scope.AnalyticsReadonly}; // View Google Analytics Data

var clientId = “”; // From
var clientSecret = “xxxxxx”; // From

// Could use Service account, if we don’t want the web-popup.

// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
ClientId = clientId,
ClientSecret = clientSecret
new FileDataStore(“Daimto.GoogleAnalytics.Auth.Store”)).Result;

var service = new AnalyticsService(new BaseClientService.Initializer()
HttpClientInitializer = credential,
ApplicationName = “Analytics API Sample”,

I’ve left out the client ID and Client Secret, you get these from your google developer console.

The Hierarchy of objects within Google Analytics is

Account > Property > View

So, you’ll need to enumerate each Account, Property and View to drill down to individual site statistics

ManagementResource.AccountSummariesResource.ListRequest list = service.Management.AccountSummaries.List();
AccountSummaries feed = list.Execute();

foreach(AccountSummary acct in feed.Items)
ManagementResource.WebpropertiesResource.ListRequest propList = service.Management.Webproperties.List(acct.Id);
Webproperties webProperties = propList.Execute();
var allProps = webProperties.Items.ToList();


This code enumerates each account, and each property within the account. Note that each call is limited to 1,000 records or so. I’m ignoring the case that you may have more than that.

Then to enumerate the views for each property – typically there may only be one, use this loop:

foreach (var lWeb in allProps)
ManagementResource.ProfilesResource.ListRequest viewList = service.Management.Profiles.List(acct.Id, lWeb.Id);
Profiles viewProperties = viewList.Execute();
var allViews = viewProperties.Items.ToList();
foreach (var lView in allViews)
…. store lWeb.Name & lView.Id

Now, for instance, if you wanted to get the number of unique sessions in the last month, given the View ID, then you use this

var strFrom = DateTime.Now.AddMonths(-1).ToString(“yyyy-MM-dd”);
var strTo = DateTime.Now.ToString(“yyyy-MM-dd”);
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(“ga:” + strView, strFrom, strTo, “ga:sessions”);
GaData result = request.Execute();

If result.Rows is null, then you’ve had no visitors in the month, otherwise result.Rows[0][0] indicates the number of visitors.

Categories: Uncategorized