Compare commits

...
1 Commits
Author SHA1 Message Date
amacocianandGitHub c7eb5debcb Refresh access token (#100) 2022-09-20 11:46:36 +00:00
10 changed files with 171 additions and 24 deletions
@@ -39,5 +39,7 @@ namespace Daybreak.Configuration
public bool AutoCheckUpdate { get; set; } = true;
[JsonProperty("ProtectedGraphAccessToken")]
public string ProtectedGraphAccessToken { get; set; }
[JsonProperty("ProtectedGraphRefreshToken")]
public string ProtectedGraphRefreshToken { get; set; }
}
}
+5 -2
View File
@@ -10,11 +10,14 @@
<Viewbox>
<Grid>
<Line Stroke="{Binding ElementName=_this, Path=Foreground, Mode=OneWay}"
X1="15" X2="26" Y1="11" Y2="0"></Line>
X1="15" X2="26" Y1="11" Y2="0"
StrokeThickness="2"></Line>
<Ellipse Stroke="{Binding ElementName=_this, Path=Foreground, Mode=OneWay}"
Width="4" Height="4"
Width="4" Height="4"
StrokeThickness="2"
Margin="8,13,13,8"></Ellipse>
<Path Stroke="{Binding ElementName=_this, Path=Foreground, Mode=OneWay}"
StrokeThickness="2"
Data="m15.025,0l-12.7,11.3c-3.1,3.1 -3.1,8.2 0,11.3s8.2,3.1 11.3,0l12.4,-11.6"></Path>
</Grid>
</Viewbox>
+10 -10
View File
@@ -18,6 +18,16 @@
Width="40"></local:GoldenArrowGlyph>
</buttons:MenuButton.InnerContent>
</buttons:MenuButton>
<buttons:MenuButton Title="Manage builds"
Foreground="White"
HighlightColor="White"
Height="30"
Clicked="ManageBuildsButton_Clicked">
<buttons:MenuButton.InnerContent>
<local:FireballGlyph Foreground="White"
Width="40"></local:FireballGlyph>
</buttons:MenuButton.InnerContent>
</buttons:MenuButton>
<buttons:MenuButton Title="Account settings"
Foreground="White"
HighlightColor="White"
@@ -59,16 +69,6 @@
Width="40"></local:ExperimentGlyph>
</buttons:MenuButton.InnerContent>
</buttons:MenuButton>
<buttons:MenuButton Title="Manage builds"
Foreground="White"
HighlightColor="White"
Height="30"
Clicked="ManageBuildsButton_Clicked">
<buttons:MenuButton.InnerContent>
<local:FireballGlyph Foreground="White"
Width="40"></local:FireballGlyph>
</buttons:MenuButton.InnerContent>
</buttons:MenuButton>
<buttons:MenuButton Title="Manage client version"
Foreground="White"
HighlightColor="White"
+2 -1
View File
@@ -2,6 +2,7 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<RootNamespace>Daybreak</RootNamespace>
<TargetFramework>net6.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
@@ -10,7 +11,7 @@
<LangVersion>preview</LangVersion>
<ApplicationIcon>Daybreak.ico</ApplicationIcon>
<IncludePackageReferencesDuringMarkupCompilation>true</IncludePackageReferencesDuringMarkupCompilation>
<Version>0.9.7</Version>
<Version>0.9.7.1</Version>
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<UserSecretsId>cfb2a489-db80-448d-a969-80270f314c46</UserSecretsId>
</PropertyGroup>
+107 -9
View File
@@ -9,6 +9,7 @@ using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Core.Extensions;
using System.Extensions;
@@ -26,8 +27,8 @@ namespace Daybreak.Services.Graph;
public sealed class GraphClient : IGraphClient
{
private const string Scopes = "Files.Read Files.Read.All Files.ReadWrite Files.ReadWrite.All User.Read";
private const string RedirectUri = "http://localhost";
private const string Scopes = "Files.Read Files.Read.All Files.ReadWrite Files.ReadWrite.All User.Read offline_access";
private const string RedirectUri = "http://localhost:42111";
private const string QueryStateKey = "state";
private const string QueryCodeKey = "code";
@@ -35,9 +36,11 @@ public sealed class GraphClient : IGraphClient
private const string RedirectUriPlaceholder = "[RedirectUri]";
private const string ScopesPlaceholder = "[Scopes]";
private const string StatePlaceholder = "[State]";
private const string RefreshTokenPlaceholder = "[RefreshToken]";
private const string ProfileEndpoint = "me";
private const string GraphBaseUrl = "https://graph.microsoft.com/v1.0/";
private const string TokenUrlPlaceholder = $"https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
private const string RefreshTokenUrlPlaceholder = $"https://login.microsoftonline.com/consumers/oauth2/v2.0/token?client_id={ClientIdPlaceholder}&refresh_token={RefreshTokenPlaceholder}";
private const string AuthorizationUrlPlaceholder = $"https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id={ClientIdPlaceholder}&response_type=code&redirect_uri={RedirectUriPlaceholder}&response_mode=query&scope={ScopesPlaceholder}&state={StatePlaceholder}";
private const string SyncFileUri = $"me/drive/root:/Daybreak/Builds/daybreak.json{ContentSuffix}";
private const string ContentSuffix = ":/content";
@@ -85,13 +88,22 @@ public sealed class GraphClient : IGraphClient
return maybeAccessToken.Switch(
onSuccess: token =>
{
var accessToken = AccessToken.FromTokenResponse(token);
this.SaveAccessToken(accessToken);
this.SaveTokenResponse(token);
return true;
},
onFailure: exception => exception);
}
public Task<Result<bool, Exception>> LogOut()
{
this.ResetAccessToken();
this.ResetRefreshToken();
this.ResetAuthorization();
//TODO: Currently revoking only one refresh token is not supported. Follow up when MS Graph implements refresh token revocation.
return Task.FromResult(Result<bool, Exception>.Success(true));
}
public async Task<Result<User, Exception>> GetUserProfile<TViewType>()
where TViewType : UserControl
{
@@ -104,8 +116,15 @@ public sealed class GraphClient : IGraphClient
if (DateTime.Now > accessToken.ExpirationDate)
{
this.viewManager.ShowView<GraphAuthorizationView>(new ViewRedirectContext { CallingView = typeof(TViewType) });
return new InvalidOperationException("Client authorization expired");
var maybeToken = await this.RefreshAccessToken();
if (maybeToken.ExtractValue() is not TokenResponse tokenResponse)
{
this.viewManager.ShowView<GraphAuthorizationView>(new ViewRedirectContext { CallingView = typeof(TViewType) });
return new InvalidOperationException("Client authorization expired");
}
(var newAccessToken, _) = this.SaveTokenResponse(tokenResponse);
accessToken = newAccessToken;
}
this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Token);
@@ -227,6 +246,30 @@ public sealed class GraphClient : IGraphClient
public void ResetAuthorization()
{
this.ResetAccessToken();
this.ResetRefreshToken();
}
private async Task<Optional<TokenResponse>> RefreshAccessToken()
{
var maybeRefreshToken = this.LoadRefreshToken();
if (maybeRefreshToken.ExtractValue() is not RefreshToken refreshToken)
{
return Optional.None<TokenResponse>();
}
using var httpContent = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "client_id", ApplicationId },
{ "refresh_token", refreshToken.Token },
{ "grant_type", "refresh_token" }
});
using var response = await this.httpClient.PostAsync(TokenUrlPlaceholder, httpContent);
if (response.IsSuccessStatusCode is false)
{
return Optional.None<TokenResponse>();
}
return JsonConvert.DeserializeObject<TokenResponse>(await response.Content.ReadAsStringAsync());
}
private async Task<bool> PutBuild(BuildEntry buildEntry)
@@ -320,7 +363,19 @@ public sealed class GraphClient : IGraphClient
.Replace(' ', '+'))
.Replace(StatePlaceholder, state);
while (chromiumBrowserWrapper.Address.StartsWith(RedirectUri) is false)
NameValueCollection query = null;
bool finished = false;
chromiumBrowserWrapper.WebBrowser.CoreWebView2.SourceChanged += (_, sourceArgs) =>
{
if (chromiumBrowserWrapper.Address.StartsWith(RedirectUri))
{
query = HttpUtility.ParseQueryString(chromiumBrowserWrapper.Address.Split('?').Skip(1).FirstOrDefault());
finished = true;
chromiumBrowserWrapper.WebBrowser.CoreWebView2.NavigateToString(string.Empty);
}
};
while (finished is false)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -330,8 +385,7 @@ public sealed class GraphClient : IGraphClient
await Task.Delay(1000, cancellationToken).ConfigureAwait(true);
}
var query = HttpUtility.ParseQueryString(chromiumBrowserWrapper.Address.Split('?').Skip(1).FirstOrDefault());
if (query.GetValues(QueryStateKey) is string[] states is false)
if (query?.GetValues(QueryStateKey) is string[] states is false)
{
throw new InvalidOperationException("Response doesn't have state key in response");
}
@@ -388,6 +442,16 @@ public sealed class GraphClient : IGraphClient
return JsonConvert.DeserializeObject<TokenResponse>(await response.Content.ReadAsStringAsync());
}
private (AccessToken, RefreshToken) SaveTokenResponse(TokenResponse token)
{
var accessToken = AccessToken.FromTokenResponse(token);
var refreshToken = RefreshToken.FromTokenResponse(token);
this.SaveAccessToken(accessToken);
this.SaveRefreshToken(refreshToken);
return (accessToken, refreshToken);
}
private void ResetAccessToken()
{
this.liveUpdateableOptions.Value.ProtectedGraphAccessToken = null;
@@ -401,6 +465,19 @@ public sealed class GraphClient : IGraphClient
this.liveUpdateableOptions.UpdateOption();
}
private void SaveRefreshToken(RefreshToken refreshToken)
{
var codeBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(refreshToken));
this.liveUpdateableOptions.Value.ProtectedGraphRefreshToken = Convert.ToBase64String(ProtectedData.Protect(codeBytes, Entropy, DataProtectionScope.CurrentUser));
this.liveUpdateableOptions.UpdateOption();
}
private void ResetRefreshToken()
{
this.liveUpdateableOptions.Value.ProtectedGraphRefreshToken = null;
this.liveUpdateableOptions.UpdateOption();
}
private Optional<AccessToken> LoadAccessToken()
{
var protectedCode = this.liveUpdateableOptions.Value.ProtectedGraphAccessToken;
@@ -422,6 +499,27 @@ public sealed class GraphClient : IGraphClient
}
}
private Optional<RefreshToken> LoadRefreshToken()
{
var protectedCode = this.liveUpdateableOptions.Value.ProtectedGraphRefreshToken;
if (protectedCode.IsNullOrWhiteSpace())
{
return Optional.None<RefreshToken>();
}
var codeBytes = ProtectedData.Unprotect(Convert.FromBase64String(protectedCode), Entropy, DataProtectionScope.CurrentUser);
try
{
return JsonConvert.DeserializeObject<RefreshToken>(Encoding.UTF8.GetString(codeBytes));
}
catch (Exception e)
{
this.logger.LogError(e, "Failed to load refresh token. Resetting refresh token");
this.ResetAccessToken();
return Optional.None<RefreshToken>();
}
}
private static string GetNewState()
{
return Guid.NewGuid().ToString();
+1
View File
@@ -14,6 +14,7 @@ public interface IGraphClient
Task<Result<User, Exception>> GetUserProfile<TViewType>()
where TViewType : UserControl;
Task<Result<bool, Exception>> PerformAuthorizationFlow(ChromiumBrowserWrapper chromiumBrowserWrapper, CancellationToken cancellationToken = default);
Task<Result<bool, Exception>> LogOut();
Task<Result<bool, Exception>> UploadBuilds();
Task<Result<bool, Exception>> DownloadBuilds();
Task<Result<bool, Exception>> UploadBuild(string buildName);
@@ -0,0 +1,14 @@
namespace Daybreak.Services.Graph.Models;
public sealed class RefreshToken
{
public string Token { get; set; }
public static RefreshToken FromTokenResponse(TokenResponse tokenResponse)
{
return new RefreshToken
{
Token = tokenResponse.RefreshToken,
};
}
}
@@ -25,6 +25,15 @@
<controls:BackButton Foreground="White" Height="30" Width="30" Grid.Column="0" HorizontalAlignment="Left" Margin="5"
Clicked="BackButton_Clicked" VerticalAlignment="Top"
IsEnabled="{Binding ElementName=_this, Path=ButtonsEnabled, Mode=OneWay}"></controls:BackButton>
<controls:OpaqueButton Text="Log Out"
Foreground="White"
Background="DarkGray"
HorizontalAlignment="Right"
Padding="5"
Margin="5"
Clicked="LogOutButton_Clicked"
Width="80"
IsEnabled="{Binding ElementName=_this, Path=ButtonsEnabled, Mode=OneWay}"/>
<WrapPanel HorizontalAlignment="Center">
<TextBlock
Text="Build templates synchronization"
@@ -42,7 +51,6 @@
Visibility="{Binding ElementName=_this, Path=Synchronized, Mode=OneWay, Converter={StaticResource InverseBooleanToVisibilityConverter}}"/>
</Grid>
</WrapPanel>
<WrapPanel HorizontalAlignment="Center"
Grid.Row="1">
<TextBlock Text="Logged in as: "
@@ -166,4 +166,25 @@ public partial class BuildsSynchronizationView : UserControl
this.ButtonsEnabled = true;
this.ShowLoading = false;
}
private async void LogOutButton_Clicked(object sender, EventArgs e)
{
this.ButtonsEnabled = false;
this.ShowLoading = true;
var result = await this.graphClient.LogOut();
result.Do(
onSuccess: logOutSuccess =>
{
if (logOutSuccess)
{
this.viewManager.ShowView<BuildsListView>();
}
},
onFailure: failure =>
{
this.logger.LogError(failure, "Failed to log out");
});
this.ButtonsEnabled = true;
this.ShowLoading = false;
}
}
@@ -2,7 +2,6 @@
using Daybreak.Services.Graph.Models;
using Daybreak.Services.ViewManagement;
using Microsoft.Extensions.Logging;
using System;
using System.Core.Extensions;
using System.Threading;
using System.Windows;