Skip to content

Instantly share code, notes, and snippets.

@rgregg
Last active September 27, 2021 23:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rgregg/6f7332e998e76a16bbac to your computer and use it in GitHub Desktop.
Save rgregg/6f7332e998e76a16bbac to your computer and use it in GitHub Desktop.
Easy OAuth form for Microsoft Account authentication
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OneDriveSamples
{
public partial class FormMicrosoftAccountAuth : Form
{
public const string OAuthDesktopEndPoint = "https://login.live.com/oauth20_desktop.srf";
#region Properties
public string StartUrl { get; private set; }
public string EndUrl { get; private set; }
public AuthResult AuthResult { get; private set; }
public OAuthFlow AuthFlow { get; private set; }
#endregion
#region Constructor
public FormMicrosoftAccountAuth(string startUrl, string endUrl, OAuthFlow flow = OAuthFlow.AuthorizationCodeGrant)
{
InitializeComponent();
this.StartUrl = startUrl;
this.EndUrl = endUrl;
this.FormClosing += FormMicrosoftAccountAuth_FormClosing;
}
#endregion
#region Private Methods
private void FormMicrosoftAccountAuth_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void FormMicrosoftAccountAuth_Load(object sender, EventArgs e)
{
this.webBrowser.CanGoBackChanged += webBrowser_CanGoBackChanged;
this.webBrowser.CanGoForwardChanged += webBrowser_CanGoBackChanged;
FixUpNavigationButtons();
this.webBrowser.Navigated += webBrowser_Navigated;
System.Diagnostics.Debug.WriteLine("Navigating to start URL: " + this.StartUrl);
this.webBrowser.Navigate(this.StartUrl);
}
void webBrowser_CanGoBackChanged(object sender, EventArgs e)
{
FixUpNavigationButtons();
}
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Navigated to: " + webBrowser.Url.AbsoluteUri.ToString());
this.Text = webBrowser.DocumentTitle;
if (this.webBrowser.Url.AbsoluteUri.StartsWith(EndUrl))
{
this.AuthResult = new AuthResult(this.webBrowser.Url, this.AuthFlow);
CloseWindow();
}
}
private void CloseWindow()
{
const int interval = 100;
var t = new System.Threading.Timer(new System.Threading.TimerCallback((state) =>
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.BeginInvoke(new MethodInvoker(() => this.Close()));
}), null, interval, System.Threading.Timeout.Infinite);
}
private void FixUpNavigationButtons()
{
toolStripBackButton.Enabled = webBrowser.CanGoBack;
toolStripForwardButton.Enabled = webBrowser.CanGoForward;
}
#endregion
public Task<DialogResult> ShowDialogAsync(IWin32Window owner = null)
{
TaskCompletionSource<DialogResult> tcs = new TaskCompletionSource<DialogResult>();
this.FormClosed += (s, e) =>
{
tcs.SetResult(this.DialogResult);
};
if (owner == null)
this.Show();
else
this.Show(owner);
return tcs.Task;
}
#region Static Methods
private static string GenerateScopeString(string[] scopes)
{
StringBuilder sb = new StringBuilder();
foreach(var scope in scopes)
{
if (sb.Length > 0)
sb.Append(" ");
sb.Append(scope);
}
return sb.ToString();
}
private static string BuildUriWithParameters(string baseUri, Dictionary<string, string> queryStringParameters)
{
var sb = new StringBuilder();
sb.Append(baseUri);
sb.Append("?");
foreach (var param in queryStringParameters)
{
if (sb[sb.Length - 1] != '?')
sb.Append("&");
sb.Append(param.Key);
sb.Append("=");
sb.Append(Uri.EscapeDataString(param.Value));
}
return sb.ToString();
}
public static async Task<string> GetAuthenticationToken(string clientId, string[] scopes, OAuthFlow flow, IWin32Window owner = null)
{
const string msaAuthUrl = "https://login.live.com/oauth20_authorize.srf";
const string msaDesktopUrl = "https://login.live.com/oauth20_desktop.srf";
string startUrl, completeUrl;
Dictionary<string, string> urlParam = new Dictionary<string,string>();
urlParam.Add("client_id", clientId);
urlParam.Add("scope", GenerateScopeString(scopes));
urlParam.Add("redirect_uri", msaDesktopUrl);
switch (flow)
{
case OAuthFlow.ImplicitGrant:
urlParam.Add("response_type", "token");
break;
case OAuthFlow.AuthorizationCodeGrant:
urlParam.Add("response_type", "code");
break;
default:
throw new NotSupportedException("flow value not supported");
}
startUrl = BuildUriWithParameters(msaAuthUrl, urlParam);
completeUrl = msaDesktopUrl;
FormMicrosoftAccountAuth authForm = new FormMicrosoftAccountAuth(startUrl, completeUrl, flow);
DialogResult result = await authForm.ShowDialogAsync(owner);
if (DialogResult.OK == result)
{
return OnAuthComplete(authForm.AuthResult);
}
return null;
}
private static string OnAuthComplete(OneDriveSamples.AuthResult authResult)
{
switch (authResult.AuthFlow)
{
case OAuthFlow.ImplicitGrant:
return authResult.AccessToken;
case OAuthFlow.AuthorizationCodeGrant:
return authResult.AuthorizeCode;
default:
throw new ArgumentOutOfRangeException("Unsupported AuthFlow value");
}
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
webBrowser.GoBack();
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
webBrowser.GoForward();
}
#endregion
public static async Task<string> GetUserId(string authToken)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
string requestUrl = "https://apis.live.net/v5.0/me?access_token=" + System.Uri.EscapeUriString(authToken);
HttpWebRequest request = HttpWebRequest.CreateHttp(requestUrl);
WebResponse wr = await request.GetResponseAsync();
HttpWebResponse response = wr as HttpWebResponse;
if (null == response) return null;
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object> dict = (Dictionary<string, object>)serializer.DeserializeObject(await reader.ReadToEndAsync());
string userId = dict["id"] as string;
return userId;
}
}
public enum OAuthFlow
{
ImplicitGrant,
AuthorizationCodeGrant
}
public class AuthResult
{
public AuthResult(Uri resultUri, OAuthFlow flow)
{
this.AuthFlow = flow;
string[] queryParams = null;
switch (flow)
{
case OAuthFlow.ImplicitGrant:
int accessTokenIndex = resultUri.AbsoluteUri.IndexOf("#access_token");
if (accessTokenIndex > 0)
{
queryParams = resultUri.AbsoluteUri.Substring(accessTokenIndex + 1).Split('&');
}
else
{
queryParams = resultUri.Query.TrimStart('?').Split('&');
}
break;
case OAuthFlow.AuthorizationCodeGrant:
queryParams = resultUri.Query.TrimStart('?').Split('&');
break;
default:
throw new NotSupportedException("flow value not supported");
}
foreach (string param in queryParams)
{
string[] kvp = param.Split('=');
switch (kvp[0])
{
case "code":
this.AuthorizeCode = kvp[1];
break;
case "access_token":
this.AccessToken = kvp[1];
break;
case "authorization_token":
case "authentication_token":
this.AuthenticationToken = kvp[1];
break;
case "error":
this.ErrorCode = kvp[1];
break;
case "error_description":
this.ErrorDescription = Uri.UnescapeDataString(kvp[1]);
break;
case "token_type":
this.TokenType = kvp[1];
break;
case "expires_in":
this.AccessTokenExpiresIn = new TimeSpan(0, 0, int.Parse(kvp[1]));
break;
case "scope":
this.Scopes = kvp[1].Split(new string[] {"%20"}, StringSplitOptions.RemoveEmptyEntries);
break;
case "user_id":
this.UserId = kvp[1];
break;
}
}
}
public OAuthFlow AuthFlow { get; private set; }
public string AuthorizeCode { get; private set; }
public string ErrorCode { get; private set; }
public string ErrorDescription { get; private set; }
public string AccessToken { get; private set; }
public string AuthenticationToken { get; private set; }
public string TokenType { get; private set; }
public TimeSpan AccessTokenExpiresIn { get; private set; }
public string[] Scopes { get; private set; }
public string UserId { get; private set; }
}
}
namespace OneDriveSamples
{
partial class FormMicrosoftAccountAuth
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMicrosoftAccountAuth));
this.webBrowser = new System.Windows.Forms.WebBrowser();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripBackButton = new System.Windows.Forms.ToolStripButton();
this.toolStripForwardButton = new System.Windows.Forms.ToolStripButton();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// webBrowser
//
this.webBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
this.webBrowser.Location = new System.Drawing.Point(0, 32);
this.webBrowser.Margin = new System.Windows.Forms.Padding(2);
this.webBrowser.MinimumSize = new System.Drawing.Size(15, 16);
this.webBrowser.Name = "webBrowser";
this.webBrowser.Size = new System.Drawing.Size(813, 714);
this.webBrowser.TabIndex = 0;
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripBackButton,
this.toolStripForwardButton});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(813, 32);
this.toolStrip1.TabIndex = 1;
this.toolStrip1.Text = "toolStrip1";
//
// toolStripBackButton
//
this.toolStripBackButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripBackButton.Image = ((System.Drawing.Image)(resources.GetObject("toolStripBackButton.Image")));
this.toolStripBackButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripBackButton.Name = "toolStripBackButton";
this.toolStripBackButton.Size = new System.Drawing.Size(69, 29);
this.toolStripBackButton.Text = "< Back";
this.toolStripBackButton.Click += new System.EventHandler(this.toolStripButton1_Click);
//
// toolStripForwardButton
//
this.toolStripForwardButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripForwardButton.Image = ((System.Drawing.Image)(resources.GetObject("toolStripForwardButton.Image")));
this.toolStripForwardButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripForwardButton.Name = "toolStripForwardButton";
this.toolStripForwardButton.Size = new System.Drawing.Size(28, 29);
this.toolStripForwardButton.Text = ">";
this.toolStripForwardButton.Click += new System.EventHandler(this.toolStripButton2_Click);
//
// FormMicrosoftAccountAuth
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(813, 746);
this.Controls.Add(this.webBrowser);
this.Controls.Add(this.toolStrip1);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "FormMicrosoftAccountAuth";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "FormMicrosoftAccountAuth";
this.Load += new System.EventHandler(this.FormMicrosoftAccountAuth_Load);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.WebBrowser webBrowser;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton toolStripBackButton;
private System.Windows.Forms.ToolStripButton toolStripForwardButton;
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="toolStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="toolStripBackButton.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
YQUAAAAJcEhZcwAAFiUAABYlAUlSJPAAAAIDSURBVDhPpZLrS5NhGMb3j4SWh0oRQVExD4gonkDpg4hG
YKxG6WBogkMZKgPNCEVJFBGdGETEvgwyO9DJE5syZw3PIlPEE9pgBCLZ5XvdMB8Ew8gXbl54nuf63dd9
0OGSnwCahxbPRNPAPMw9Xpg6ZmF46kZZ0xSKzJPIrhpDWsVnpBhGkKx3nAX8Pv7z1zg8OoY/cITdn4fw
bf/C0kYAN3Ma/w3gWfZL5kzTKBxjWyK2DftwI9tyMYCZKXbNHaD91bLYJrDXsYbrWfUKwJrPE9M2M1Oc
VzOOpHI7Jr376Hi9ogHqFIANO0/MmmmbmSmm9a8ze+I4MrNWAdjtoJgWcx+PSzg166yZZ8xM8XvXDix9
c4jIqFYAjoriBV9AhEPv1mH/sonogha0afbZMMZz+yreTGyhpusHwtNNCsA5U1zS4BLxzJIfg299qO32
Ir7UJtZfftyATqeT+8o2D8JSjQrAJblrncYL7ZJ2+bfaFnC/1S1NjL3diRat7qrO7wLRP3HjWsojBeCo
mDEo5mNjuweFGvjWg2EBhCbpkW78htSHHwRyNdmgAFzPEee2iFkzayy2OLXzT4gr6UdUnlXrullsxxQ+
kx0g8BTA3aZlButjSTyjODq/WcQcW/B/Je4OQhLvKQDnzN1mp0nnkvAhR8VuMzNrpm1mpjgkoVwB/v8D
TgDQASA1MVpwzwAAAABJRU5ErkJggg==
</value>
</data>
<data name="toolStripForwardButton.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
YQUAAAAJcEhZcwAAFiUAABYlAUlSJPAAAAIDSURBVDhPpZLrS5NhGMb3j4SWh0oRQVExD4gonkDpg4hG
YKxG6WBogkMZKgPNCEVJFBGdGETEvgwyO9DJE5syZw3PIlPEE9pgBCLZ5XvdMB8Ew8gXbl54nuf63dd9
0OGSnwCahxbPRNPAPMw9Xpg6ZmF46kZZ0xSKzJPIrhpDWsVnpBhGkKx3nAX8Pv7z1zg8OoY/cITdn4fw
bf/C0kYAN3Ma/w3gWfZL5kzTKBxjWyK2DftwI9tyMYCZKXbNHaD91bLYJrDXsYbrWfUKwJrPE9M2M1Oc
VzOOpHI7Jr376Hi9ogHqFIANO0/MmmmbmSmm9a8ze+I4MrNWAdjtoJgWcx+PSzg166yZZ8xM8XvXDix9
c4jIqFYAjoriBV9AhEPv1mH/sonogha0afbZMMZz+yreTGyhpusHwtNNCsA5U1zS4BLxzJIfg299qO32
Ir7UJtZfftyATqeT+8o2D8JSjQrAJblrncYL7ZJ2+bfaFnC/1S1NjL3diRat7qrO7wLRP3HjWsojBeCo
mDEo5mNjuweFGvjWg2EBhCbpkW78htSHHwRyNdmgAFzPEee2iFkzayy2OLXzT4gr6UdUnlXrullsxxQ+
kx0g8BTA3aZlButjSTyjODq/WcQcW/B/Je4OQhLvKQDnzN1mp0nnkvAhR8VuMzNrpm1mpjgkoVwB/v8D
TgDQASA1MVpwzwAAAABJRU5ErkJggg==
</value>
</data>
</root>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment