Getting an authorization code

Once an application is registered, an authorization code is required. Obtaining the authorization code gives the end user the opportunity to grant the application access to a GitHub account. If the user is not currently logged in to GitHub, it will also prompt him/her to log on.

A URL must be created that will prompt for authorization:

$authorize = 'https://github.com/login/oauth/authorize?client_id={0}&scope={1}' -f 
    $clientId, 
    'user:email'

The 'user:email' scope describes the rights the application would like to have. The web API guide contains a list of possible scopes: https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/.

GitHub does not support Internet Explorer

WPF and Windows Forms both include browser controls that can be used. However, both are based on Internet Explorer, which is not supported by GitHub. An alternative is required.

Before creating the web request, an appropriate browser control must be found. The WebView control uses the Microsoft Edge browser and is available from https://www.nuget.org/https://www.nuget.org/packages/Microsoft.Toolkit.Win32.UI.Controls/.

The following script will download and extract the package to the current directory:

$params = @{
Uri = 'https://www.nuget.org/api/v2/package/Microsoft.Toolkit.Win32.UI.Controls/4.0.2'
OutFile =
'Microsoft.Toolkit.Win32.UI.Controls.zip'
}
Invoke-WebRequest @params
Expand-Archive Microsoft.Toolkit.Win32.UI.Controls.zip

The downloaded assembly may be used to implement a small browser to handle the OAuth callback process:

using assembly PresentationFramework
using assembly .Microsoft.Toolkit.Win32.UI.Controlslib et462Microsoft.Toolkit.Win32.UI.Controls.dll

$window = [System.Windows.Window]@{
Height = 650
Width = 450
}
$browser = [Microsoft.Toolkit.Win32.UI.Controls.WPF.WebView]@{
Height = 650
Width = 450
}
# Add an event handler to close the window when

# interaction with GitHub is complete.
$browser.add_NavigationCompleted( {
param ( $sender, $eventargs )

if ($eventArgs.Uri -notmatch 'GitHub') {
$Global:authorizationCode = $eventArgs.Uri -replace '^.+code='

$sender.Parent.Close()
} else {
$Global:authorizationCode = $null
}
} )
$browser.Navigate($authorize)
$window.Content = $browser
$null = $window.ShowDialog()

The window will close as soon as it leaves the GitHub pages, when the request is redirected to the callback URL for the application.

If the application has already been authorized and the user is logged in, the window will close without prompting for user interaction.

The authroizationCode global variable should contain code that can be used to request an access token.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.208.72