[源码下载]

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

作者:webabcd

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

  • 数据账号的添加和管
  • OAuth 2.0 验证

示例
1、演示数据账号的添加和管理
UserAndAccount/DataAccount.xaml

<Page
x:Class="Windows10.UserAndAccount.DataAccount"
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"> <TextBlock Name="lblMsg" Margin="5" /> <Button Name="buttonAdd" Content="新增一个数据账号" Margin="5" Click="buttonAdd_Click" /> </StackPanel>
</Grid>
</Page>

UserAndAccount/DataAccount.xaml.cs

/*
* 演示数据账号的添加和管理
*
* UserDataAccountManager - 数据账号管理器
* ShowAddAccountAsync() - 弹出账号添加界面
* ShowAccountSettingsAsync() - 弹出账号管理界面
* RequestStoreAsync() - 返回当前用户的数据账号存储区域
* GetForUser() - 返回指定用户的数据账号存储区域(通过返回的 UserDataAccountManagerForUser 对象的 RequestStoreAsync() 方法)
*
* UserDataAccountStore - 数据账号存储区域
* FindAccountsAsync() - 返回所有的数据账号
* GetAccountAsync() - 返回指定的数据账号
*
* UserDataAccount - 数据账号
* UserDisplayName - 用户名
* Id - 数据账号在本地设备上的唯一标识
* SaveAsync() - 保存
* DeleteAsync() - 删除
* ... 还有很多其他属性和方法
*
*
* 注:根据使用的功能需要在 Package.appxmanifest 做相关配置
* 1、用到 Windows.System.User 的话需要配置 <Capability Name="userAccountInformation" />
* 2、还可能需要 <Capability Name="appointments" />, <Capability Name="contacts" />
*/ using System;
using System.Linq;
using System.Collections.Generic;
using Windows.ApplicationModel.UserDataAccounts;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation; namespace Windows10.UserAndAccount
{
public sealed partial class DataAccount : Page
{
public DataAccount()
{
this.InitializeComponent();
} protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e); // 获取当前用户下的全部数据账号
UserDataAccountStore store = await UserDataAccountManager.RequestStoreAsync(UserDataAccountStoreAccessType.AllAccountsReadOnly);
IReadOnlyList<UserDataAccount> accounts = await store.FindAccountsAsync();
lblMsg.Text += string.Join(",", accounts.Select(p => p.UserDisplayName));
lblMsg.Text += Environment.NewLine;
} private async void buttonAdd_Click(object sender, RoutedEventArgs e)
{
// 弹出账号添加界面,如果添加成功会返回新建的数据账号的在本地设备上的唯一标识
string userDataAccountId = await UserDataAccountManager.ShowAddAccountAsync(UserDataAccountContentKinds.Email | UserDataAccountContentKinds.Appointment | UserDataAccountContentKinds.Contact); if (string.IsNullOrEmpty(userDataAccountId))
{
lblMsg.Text += "用户取消了或添加账号失败";
lblMsg.Text += Environment.NewLine;
}
else
{
UserDataAccountStore store = await UserDataAccountManager.RequestStoreAsync(UserDataAccountStoreAccessType.AllAccountsReadOnly);
if (store != null)
{
// 通过数据账号在本地设备上的唯一标识来获取 UserDataAccount 对象
UserDataAccount account = await store.GetAccountAsync(userDataAccountId);
lblMsg.Text += "新增的数据账号:" + account.UserDisplayName;
}
}
}
}
}

2、演示如何开发一个基于 OAuth 2.0 验证的客户端 
UserAndAccount/OAuth20.xaml

<Page
x:Class="Windows10.UserAndAccount.OAuth20"
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="buttonWeibo" Content="登录新浪微博,并返回登录用户好友最新发布的微博" Margin="5" Click="buttonWeibo_Click" /> <TextBlock Name="lblMsg" TextWrapping="Wrap" Margin="5" /> </StackPanel>
</Grid>
</Page>

UserAndAccount/OAuth20.xaml.cs

/*
* 演示如何开发一个基于 OAuth 2.0 验证的客户端
* 关于 OAuth 2.0 协议请参见:http://tools.ietf.org/html/draft-ietf-oauth-v2-20
*
* WebAuthenticationBroker - 用于 OAuth 2.0 验证的第一步,可以将第三方 UI 无缝整合进 app
* AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri, Uri callbackUri) - 请求 authorization code,返回一个 WebAuthenticationResult 类型的数据
*
* WebAuthenticationResult - 请求 authorization code(OAuth 2.0 验证的第一步)的结果
* ResponseData - 响应的数据
* ResponseStatus - 响应的状态
*
*
* 注:本例以微博开放平台为例
*/ using System;
using System.Net.Http;
using System.Text.RegularExpressions;
using Windows.Data.Json;
using Windows.Security.Authentication.Web;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace Windows10.UserAndAccount
{
public sealed partial class OAuth20 : Page
{
public OAuth20()
{
this.InitializeComponent();
} private async void buttonWeibo_Click(object sender, RoutedEventArgs e)
{
try
{
var appKey = "";
var appSecret = "652ec0b02f814d514fc288f3eab2efda";
var callbackUrl = "http://webabcd.cnblogs.com"; // 在新浪微博开放平台设置的回调页 var requestAuthorizationCode_url =
string.Format("https://api.weibo.com/oauth2/authorize?client_id={0}&response_type=code&redirect_uri={1}",
appKey,
callbackUrl); // 第一步:request authorization code
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
new Uri(requestAuthorizationCode_url),
new Uri(callbackUrl)); // 第一步的结果
lblMsg.Text = WebAuthenticationResult.ResponseStatus.ToString() + Environment.NewLine; if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
// 从第一步返回的数据中获取 authorization code
var authorizationCode = QueryString(WebAuthenticationResult.ResponseData, "code");
lblMsg.Text += "authorizationCode: " + authorizationCode + Environment.NewLine; var requestAccessToken_url =
string.Format("https://api.weibo.com/oauth2/access_token?client_id={0}&client_secret={1}&grant_type=authorization_code&redirect_uri={2}&code={3}",
appKey,
appSecret,
callbackUrl,
authorizationCode); // 第二步:request access token
HttpClient client = new HttpClient();
var response = await client.PostAsync(new Uri(requestAccessToken_url), null); // 第二步的结果:获取其中的 access token
var jsonString = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonString);
var accessToken = jsonObject["access_token"].GetString();
lblMsg.Text += "accessToken: " + accessToken + Environment.NewLine; var requestProtectedResource_url =
string.Format("https://api.weibo.com/2/statuses/friends_timeline.json?access_token={0}",
accessToken); // 第三步:request protected resource,获取需要的数据(本例为获取登录用户好友最新发布的微博)
var result = await client.GetStringAsync(new Uri(requestProtectedResource_url)); // 由于本 app 没有提交微博开放平台审核,所以如果使用的账号没有添加到微博开放平台的测试账号中的话,是会出现异常的
lblMsg.Text += "result: " + result;
}
}
catch (Exception ex)
{
lblMsg.Text += Environment.NewLine;
lblMsg.Text += ex.ToString();
}
} /// <summary>
/// 模拟 QueryString 的实现
/// </summary>
/// <param name="queryString">query 字符串</param>
/// <param name="key">key</param>
private string QueryString(string queryString, string key)
{
return Regex.Match(queryString, string.Format(@"(?<=(\&|\?|^)({0})\=).*?(?=\&|$)", key), RegexOptions.IgnoreCase).Value;
}
}
} /*
* OAuth 2.0 的 Protocol Flow
+--------+ +---------------+
| |--(A)- Authorization Request ->| Resource |
| | | Owner |
| |<-(B)-- Authorization Grant ---| |
| | +---------------+
| |
| | +---------------+
| |--(C)-- Authorization Grant -->| Authorization |
| Client | | Server |
| |<-(D)----- Access Token -------| |
| | +---------------+
| |
| | +---------------+
| |--(E)----- Access Token ------>| Resource |
| | | Server |
| |<-(F)--- Protected Resource ---| |
+--------+ +---------------+
*/

OK
[源码下载]

背水一战 Windows 10 (83) - 用户和账号: 数据账号的添加和管理, OAuth 2.0 验证的更多相关文章

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

    [源码下载] 背水一战 Windows 10 (84) - 用户和账号: 微软账号的登录和注销 作者:webabcd 介绍背水一战 Windows 10 之 用户和账号 微软账号的登录和注销 示例演示 ...

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

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

  3. 背水一战 Windows 10 (89) - 文件系统: 读写文本数据, 读写二进制数据, 读写流数据

    [源码下载] 背水一战 Windows 10 (89) - 文件系统: 读写文本数据, 读写二进制数据, 读写流数据 作者:webabcd 介绍背水一战 Windows 10 之 文件系统 读写文本数 ...

  4. 背水一战 Windows 10 (20) - 绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换

    [源码下载] 背水一战 Windows 10 (20) - 绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换 作者:webabcd 介 ...

  5. 背水一战 Windows 10 (101) - 应用间通信: 通过协议打开指定的 app 并传递数据以及获取返回数据, 将本 app 沙盒内的文件共享给其他 app 使用

    [源码下载] 背水一战 Windows 10 (101) - 应用间通信: 通过协议打开指定的 app 并传递数据以及获取返回数据, 将本 app 沙盒内的文件共享给其他 app 使用 作者:weba ...

  6. 背水一战 Windows 10 (51) - 控件(集合类): ItemsControl - 项模板选择器, 数据分组

    [源码下载] 背水一战 Windows 10 (51) - 控件(集合类): ItemsControl - 项模板选择器, 数据分组 作者:webabcd 介绍背水一战 Windows 10 之 控件 ...

  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 (114) - 后台任务: 后台任务的 Demo(与 app 不同进程), 后台任务的 Demo(与 app 相同进程)

    [源码下载] 背水一战 Windows 10 (114) - 后台任务: 后台任务的 Demo(与 app 不同进程), 后台任务的 Demo(与 app 相同进程) 作者:webabcd 介绍背水一 ...

随机推荐

  1. android toolbar效果4

    两个标题的,右边一个按钮 activity_main.xml: <android.support.v7.widget.Toolbar style="style/toolbarStyle ...

  2. BUILDING WITH BOOTSTRAP

    BUILDING WITH BOOTSTRAP Bootstrap Generalizations You just built an impressive webpage using the Boo ...

  3. Garbage Disposal(模拟垃圾装垃圾口袋)

    Garbage Disposal Description Enough is enough. Too many times it happened that Vasya forgot to dispo ...

  4. Setting up Scatter for Web Applications

    [Setting up Scatter for Web Applications] If you are still using scatter-js please move over to scat ...

  5. java引用

    java1.2之后将引用分为强引用(Strong Reference).软引用(Soft Reference).弱引用(Weak Reference).虚引用(Phantom Reference)4种 ...

  6. Python设计模式 - 创建型 - 单例模式(Singleton) - 十种

    对于很多开发人员来说,单例模式算是比较简单常用.也是最早接触的设计模式了,仔细研究起来单例模式似乎又不像看起来那么简单.我们知道单例模式适用于提供全局唯一访问点,频繁需要创建及销毁对象等场合,的确方便 ...

  7. Linux上web服务器搭建

    安装php依赖包: yum -y install gcc gcc++ libxml2 libxml2-devel yum install gcc make gd-devel libjpeg-devel ...

  8. 封装的mybatis连接类

    package com.kevin.utils;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSe ...

  9. 36 【kubernetes】coredns

    CoreDNS是k8s中,master节点和从节点及其pods之间通信的接口. 但是上个博客中遇到一个问题dns一直处于crush的状态. https://www.cnblogs.com/helww/ ...

  10. 199. Binary Tree Right Side View 从右侧看的节点数

    [抄题]: Given a binary tree, imagine yourself standing on the right side of it, return the values of t ...