[开始-我已在此处(https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthUniversalApp)提取了Google提供的示例UWP应用。
我已经成功使用自己的clientID(在此处的答案中记录了该设置:How to create a custom OAuth 2.0 redirect_uri for Google provider, for UWP app?)。重定向回应用程序的效果很好-并从示例中的OnNavigatedTo()方法启动。
然后,我有了一个UWP,它记录了传感器的温度(最终将在Raspberry Pi上运行)-但现在,我正在普通Windows 10上运行它。我已经将示例中的Oauth位复制到了我的项目中-并且还使用名称“ pw.oauth2”在Package.appxmanifest中声明了协议(与示例相同,并且与我在Google Developer Console中的内容匹配)。
[当我启动该应用程序并单击“使用Google登录”时,它会成功启动浏览器,请求授权/登录,并重定向回该应用程序。我知道这部分正在运行,因为它将应用重新带回了前台。但是,返回到我的应用程序时,不会触发OnNavigatedTo()方法。
我已经搜索并阅读了此文档-但无法在我的应用中触发该方法。我感觉好像缺少了示例应用程序中未在应用程序中配置的其他设置。任何帮助或建议,不胜感激!
这是我的XAML:
<Page
x:Class="CamIOT.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CamIOT"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<RelativePanel>
<Button x:Name="button" HorizontalAlignment="Left" Margin="18,22,0,0" VerticalAlignment="Top" Width="206" Height="46" Click="oauth_Click"
BorderThickness="0" Padding="0" Background="Transparent">
<Image Source="Assets/btn_google_sign-in.png" Stretch="UniformToFill" HorizontalAlignment="Left" Width="206"/>
</Button>
<TextBox x:Name="textBoxOutput" TextWrapping="Wrap" Text=""
IsReadOnly="True" ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="300,40,0,0" Height="731" Width="1000"/>
<ScrollViewer Margin="12,100,12,12">
<StackPanel>
<TextBlock TextWrapping="Wrap">
I2C Device Data
</TextBlock>
<TextBlock TextWrapping="Wrap" Margin="0,10,0,0">
Temperature and Humidity Data
</TextBlock>
<ScrollViewer HorizontalScrollMode="Auto" HorizontalScrollBarVisibility="Auto">
<Image Source="Assets/i2c_sample_bb.jpg" Stretch="None" Margin="2,10,2,0" />
</ScrollViewer>
<Button x:Name="StartStopButton" Content="Start" Margin="0,10,0,0" Click="{x:Bind StartStopScenario}"/>
<TextBlock x:Name="ScenarioControls" Visibility="Collapsed">
Current Temperature: <Run x:Name="CurrentTemp"/>
<LineBreak/>
Current Humidity: <Run x:Name="CurrentHumidity"/>
</TextBlock>
</StackPanel>
</ScrollViewer>
</RelativePanel>
</Grid>
</Page>
这是我的OnNavigatedTo()方法:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Debug.WriteLine("OnNavigatedTo Fired!");
if (e.Parameter is Uri)
{
// Gets URI from navigation parameters.
Uri authorizationResponse = (Uri)e.Parameter;
string queryString = authorizationResponse.Query;
output("MainPage received authorizationResponse: " + authorizationResponse);
// Parses URI params into a dictionary
// ref: http://stackoverflow.com/a/11957114/72176
Dictionary<string, string> queryStringParams =
queryString.Substring(1).Split('&')
.ToDictionary(c => c.Split('=')[0],
c => Uri.UnescapeDataString(c.Split('=')[1]));
if (queryStringParams.ContainsKey("error"))
{
output(String.Format("OAuth authorization error: {0}.", queryStringParams["error"]));
return;
}
if (!queryStringParams.ContainsKey("code")
|| !queryStringParams.ContainsKey("state"))
{
output("Malformed authorization response. " + queryString);
return;
}
// Gets the Authorization code & state
string code = queryStringParams["code"];
string incoming_state = queryStringParams["state"];
// Retrieves the expected 'state' value from local settings (saved when the request was made).
ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
string expected_state = (String)localSettings.Values["state"];
// Compares the receieved state to the expected value, to ensure that
// this app made the request which resulted in authorization
if (incoming_state != expected_state)
{
output(String.Format("Received request with invalid state ({0})", incoming_state));
return;
}
// Resets expected state value to avoid a replay attack.
localSettings.Values["state"] = null;
// Authorization Code is now ready to use!
output(Environment.NewLine + "Authorization code: " + code);
string code_verifier = (String)localSettings.Values["code_verifier"];
performCodeExchangeAsync(code, code_verifier);
}
else
{
Debug.WriteLine(e.Parameter);
}
}
关于我缺少的内容以及为什么OnNavigatedTo()在示例应用程序中运行正常的任何想法,但在我的应用程序中运行正常?
感谢您提前提供帮助!
最终由我自己解决-如果您通过问题中的链接关注Google提供的UWP示例Oauth应用,则需要在下方将此方法添加到App.xaml.cs类中-来自Google的重定向会打开您的应用。然后,它导航到您的主页,这将触发OnNavigatedTo()方法中的代码。
protected override void OnActivated(IActivatedEventArgs args)
{
// When the app was activated by a Protocol (custom URI scheme), forwards
// the URI to the MainPage through a Navigate event.
if (args.Kind == ActivationKind.Protocol)
{
// Extracts the authorization response URI from the arguments.
ProtocolActivatedEventArgs protocolArgs = (ProtocolActivatedEventArgs)args;
Uri uri = protocolArgs.Uri;
Debug.WriteLine("Authorization Response: " + uri.AbsoluteUri);
// Gets the current frame, making one if needed.
var frame = Window.Current.Content as Frame;
if (frame == null)
frame = new Frame();
// Opens the URI for "navigation" (handling) on the MainPage.
frame.Navigate(typeof(MainPage), uri);
Window.Current.Content = frame;
Window.Current.Activate();
}
}