[源码下载]

背水一战 Windows 10 (84) - 用户和账号: 微软账号的登录和注销

作者:webabcd

介绍
背水一战 Windows 10 之 用户和账号

  • 微软账号的登录和注销

示例
演示如何将微软账号的登录和注销集成到 app 中
UserAndAccount/MicrosoftAccount.xaml

<Page
x:Class="Windows10.UserAndAccount.MicrosoftAccount"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows10.UserAndAccount"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="10 0 10 10"> <Button Name="button" Content="登录/注销" Margin="5" Click="button_Click" /> <TextBlock Name="lblMsg" Margin="5" /> <Ellipse Width="48" Height="48" HorizontalAlignment="Left" Margin="5">
<Ellipse.Fill>
<ImageBrush x:Name="imagePicture" />
</Ellipse.Fill>
</Ellipse> </StackPanel>
</Grid>
</Page>

UserAndAccount/MicrosoftAccount.xaml.cs

/*
* 演示如何将微软账号的登录和注销集成到 app 中
*
* AccountsSettingsPane - 账号配置界面
* Show() - 弹出界面
* GetForCurrentView() - 获取当前的 AccountsSettingsPane 实例
* AccountCommandsRequested - 弹出界面时触发的事件(事件参数为:AccountsSettingsPaneCommandsRequestedEventArgs)
*
* AccountsSettingsPaneCommandsRequestedEventArgs
* GetDeferral() - 获取异步操作对象
* HeaderText - 弹出界面上需要显示的标题文字
* Commands - 返回一个 SettingsCommand 列表,用于在界面上添加自定义按钮
*
*
*
* 流程简述:
*
* 登录第一步,将指定的 web 账号提供商添加到账号登录界面中
* WebAccountProvider - web 账号提供商(本例以微软账号为例)
* WebAuthenticationCoreManager - 用于获取指定的 WebAccountProvider
* WebAccountProviderCommand - 用于将指定的 WebAccountProvider 添加到账号登录界面中
*
* 登录第二步,用户在账号登录界面中登录后
* WebTokenRequest - 通过指定的 WebAccountProvider 获取这个 web 请求对象
* WebTokenRequestResult - 通过 WebAuthenticationCoreManager 和指定的 WebTokenRequest 获取这个 web 请求结果
*
* 注销第一步,将指定的 web 账号添加到账号管理界面中
* WebAccount - 通过 WebAuthenticationCoreManager 和指定的 WebAccountProvider 和指定的 userId 获取这个 web 账号对象
* WebAccountCommand - 用于将指定的 WebAccount 添加到账号管理界面中
*
* 注销第二步,用户在账号管理界面中选择注销后
* WebAccount - 可以调用这个对象的注销方法
*
*
*
* 注:
* 本例测试时会报 ProviderError 错误,因为“you must register your app under the Microsoft Store with a Microsoft developer account”
* 给自己一个提醒,如果需要看效果的话,请参见自己写的“打字通”app 中的 MicrosoftAccount.xaml
*/ using System;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Security.Authentication.Web.Core;
using Windows.Security.Credentials;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation; namespace Windows10.UserAndAccount
{
public sealed partial class MicrosoftAccount : Page
{
const string MicrosoftAccountProviderId = "https://login.microsoft.com";
const string ConsumerAuthority = "consumers";
const string AccountScopeRequested = "wl.basic";
const string AccountClientId = "none"; private string _userId = null; public MicrosoftAccount()
{
this.InitializeComponent();
} protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e); // 弹出账号配置界面时触发的事件
AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested;
} protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e); AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested;
} private void button_Click(object sender, RoutedEventArgs e)
{
// 弹出账号配置界面
AccountsSettingsPane.Show();
} private async void OnAccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e)
{
AccountsSettingsPaneEventDeferral deferral = e.GetDeferral(); if (_userId == null)
{
// 弹出账号配置界面用于账号登录
await ShowLoginUI(e);
// 弹出界面上需要显示的标题文字
e.HeaderText = "请登录";
}
else
{
// 弹出账号配置界面用于账号管理(本例用于演示注销)
await ShowLogoutUI(e);
// 弹出界面上需要显示的标题文字
e.HeaderText = "请注销";
} // 在弹出界面上添加自定义按钮
e.Commands.Add(new SettingsCommand("help", "帮助", HelpInvoked));
e.Commands.Add(new SettingsCommand("about", "关于", AboutInvoked)); deferral.Complete();
} private void HelpInvoked(IUICommand command)
{
lblMsg.Text = "用户点击了“帮助”按钮";
} private void AboutInvoked(IUICommand command)
{
lblMsg.Text = "用户点击了“关于”按钮";
} // 将指定的 web 账号提供商添加到账号登录界面中
private async Task ShowLoginUI(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);
WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
e.WebAccountProviderCommands.Add(providerCommand);
} // 用户在账号登录界面中登录后
private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
{
try
{
WebTokenRequest webTokenRequest = new WebTokenRequest(command.WebAccountProvider, AccountScopeRequested, AccountClientId); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
{
var response = webTokenRequestResult.ResponseData[];
if (response != null)
{
// 拿到 userId,实际开发中一般会将此信息保存到本地
string userId = response.WebAccount.Id;
_userId = userId;
lblMsg.Text = "登录成功,userId:" + userId;
lblMsg.Text += Environment.NewLine; /*
* 微软账号的登录过程到此就完成了
* 如果想通过 response.WebAccount.UserName 这种方式来获取账号的用户名或其他信息的话,那是获取不到的
* 需要带着 response.Token 去请求 apis.live.net 来获取相关信息,说明如下
*/ // 登录成功后,要通过拿到的 token 像下面这样获取用户信息
var restApi = new Uri(@"https://apis.live.net/v5.0/me?access_token=" + response.Token); using (var client = new HttpClient())
{
var infoResult = await client.GetAsync(restApi);
string content = await infoResult.Content.ReadAsStringAsync();
/* 获取到的内容类似如下
{
"id": "abcd1234abcd1234",
"name": "王磊",
"first_name": "磊",
"last_name": "王",
"link": "https://profile.live.com/",
"gender": null,
"locale": "zh_CN",
"updated_time": "2017-04-27T02:24:58+0000"
}
*/
var jsonObject = JsonObject.Parse(content);
string name = jsonObject["name"].GetString() ?? "";
string locale = jsonObject["locale"].GetString() ?? "";
lblMsg.Text += $"name:{name}, locale:{locale}"; // 通过如下方式拿到用户图片
string profileId = jsonObject["id"].GetString() ?? "";
string pictureUrl = $"https://apis.live.net/v5.0/{profileId}/picture" ?? "";
imagePicture.ImageSource = new BitmapImage(new Uri(pictureUrl));
}
}
}
else
{
lblMsg.Text = "登录失败:" + webTokenRequestResult.ResponseStatus.ToString();
}
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
} // 将指定的 web 账号添加到账号管理界面中
private async Task ShowLogoutUI(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority); WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, _userId); if (account != null)
{
// 最后一个参数用于指定当用户选择了账号后,会出现哪些功能按钮(我这里测试只有 SupportedWebAccountActions.Remove 是有效的)
WebAccountCommand command = new WebAccountCommand(account, WebAccountCommandInvoked, SupportedWebAccountActions.Remove);
e.WebAccountCommands.Add(command);
}
else
{
_userId = null;
}
} // 用户在账号管理界面中选择了某项功能
private async void WebAccountCommandInvoked(WebAccountCommand command, WebAccountInvokedArgs args)
{
// 用户选择的是注销
if (args.Action == WebAccountAction.Remove)
{
await command.WebAccount.SignOutAsync(); _userId = null; lblMsg.Text = "注销成功";
imagePicture.ImageSource = null;
}
}
}
}

OK
[源码下载]

背水一战 Windows 10 (84) - 用户和账号: 微软账号的登录和注销的更多相关文章

  1. 背水一战 Windows 10 (83) - 用户和账号: 数据账号的添加和管理, OAuth 2.0 验证

    [源码下载] 背水一战 Windows 10 (83) - 用户和账号: 数据账号的添加和管理, OAuth 2.0 验证 作者:webabcd 介绍背水一战 Windows 10 之 用户和账号 数 ...

  2. 背水一战 Windows 10 (82) - 用户和账号: 获取用户的信息, 获取用户的同意

    [源码下载] 背水一战 Windows 10 (82) - 用户和账号: 获取用户的信息, 获取用户的同意 作者:webabcd 介绍背水一战 Windows 10 之 用户和账号 获取用户的信息 获 ...

  3. 背水一战 Windows 10 (29) - 控件(文本类): RichTextBlock, RichTextBlockOverflow, RichEditBox

    [源码下载] 背水一战 Windows 10 (29) - 控件(文本类): RichTextBlock, RichTextBlockOverflow, RichEditBox 作者:webabcd ...

  4. 背水一战 Windows 10 (28) - 控件(文本类): TextBox, PasswordBox

    [源码下载] 背水一战 Windows 10 (28) - 控件(文本类): TextBox, PasswordBox 作者:webabcd 介绍背水一战 Windows 10 之 控件(文本类) T ...

  5. 背水一战 Windows 10 (27) - 控件(文本类): TextBlock

    [源码下载] 背水一战 Windows 10 (27) - 控件(文本类): TextBlock 作者:webabcd 介绍背水一战 Windows 10 之 控件(文本类) TextBlock 示例 ...

  6. 背水一战 Windows 10 (42) - 控件(导航类): Frame 动画

    [源码下载] 背水一战 Windows 10 (42) - 控件(导航类): Frame 动画 作者:webabcd 介绍背水一战 Windows 10 之 控件(导航类) Frame 动画 示例An ...

  7. 背水一战 Windows 10 (37) - 控件(弹出类): MessageDialog, ContentDialog

    [源码下载] 背水一战 Windows 10 (37) - 控件(弹出类): MessageDialog, ContentDialog 作者:webabcd 介绍背水一战 Windows 10 之 控 ...

  8. 背水一战 Windows 10 (36) - 控件(弹出类): ToolTip, Popup, PopupMenu

    [源码下载] 背水一战 Windows 10 (36) - 控件(弹出类): ToolTip, Popup, PopupMenu 作者:webabcd 介绍背水一战 Windows 10 之 控件(弹 ...

  9. 背水一战 Windows 10 (34) - 控件(进度类): RangeBase, Slider, ProgressBar, ProgressRing

    [源码下载] 背水一战 Windows 10 (34) - 控件(进度类): RangeBase, Slider, ProgressBar, ProgressRing 作者:webabcd 介绍背水一 ...

随机推荐

  1. 0初识Linux

    今天三八妇女节,Linux就该这么学,开课第一天.信心满满,激动,期待,要努力了.(博客为预习写的,今天又做了更新.)   Linux第一印象就是黑色背景屏幕,上面还有好多代码,敲的一手好的命令操控着 ...

  2. service mysqld start,Failed to start mysqld.service: Access denied

    service mysqld start 然后报: ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===Authentic ...

  3. 客户端验证、tcp协议中多个客户端的同时在线

    一.客户端验证 当在一个局域网内需要验证是否为合法的客户端连接时,我们需要写代码进行验证. Server端 import os import hmac import socket def auth(c ...

  4. $nextTick 的作用

    文档:深入响应式原理 Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新. $nextTick 是在下次 DOM 更新循环结束之后执行延迟回调,在修改数据 ...

  5. Win7上安装scapy

    1.环境 操作环境:win7 python版本:python3.5 依赖模块:Npcap(推荐)或WinPcap 下载scapy 2.安装步骤 操作环境,python及依赖模块安装省略(一直点击下一步 ...

  6. C语言变量声明内存分配

    转载: C语言变量声明内存分配   一个由c/C++编译的程序占用的内存分为以下几个部分 1.栈区(stack)— 程序运行时由编译器自动分配,存放函数的参数值,局部变量的值等.其操作方式类似于数据结 ...

  7. 微信小程序——微信卡券的领取和查看

    这里大致介绍下微信卡券的一些常见问题,不再介绍具体技术了,相关接口详见微信卡券. 1. 会员卡跟卡券一样么? 这个是一样的,至少在前端是一样处理的,最多也就是卡券设置展示不同.对于微信卡券领取和查看的 ...

  8. c#: WebBrowser控制台输出

    还是处理视频下载所相关的问题. 有些网站,它的页面代码是由页面加载后js动态生成,那么其原始的html便不能用.页面渲染后的代码,是我们需要的 c#中,我用WebBrowser这个控件处理.设置项目类 ...

  9. 利用travis自动化构建与部署(文档项目)

    背景 保持网站上文档的最新性有比较重要的意义, travis ci 提供了免费的解决方案,本文基于 latex 构建+ aliyun oss 部署对此作了尝试. 项目链接为 https://travi ...

  10. Linux的php-fpm优化心得-php-fpm进程占用内存大和不释放内存问题(转)

    原文地址:https://wzfou.com/php-fpm/ 最近发现博客的内存老是隔三差五地被“吃掉”了,登录到后台后偶尔会出卡顿的情况,一开始怀疑是Swap不够导致的,于是给VPS主机增加了几个 ...