首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows 8 市集應用程式開發實戰 (58):Microsoft 帳戶整合與 Live Connect 驗證

     編輯:關於.NET

前言:身分識別是個人化體驗的基石

Windows 8 深度整合 Microsoft 帳戶(原 Windows Live ID),應用程式可在使用者同意下存取基本資料、頭像、甚至透過 Live Connect API 呼叫雲端服務(OneDrive、Outlook、行事曆等)。本文涵蓋三大主題:使用者資訊讀取、帳戶圖片/視訊管理、OAuth 驗證流程。

一、讀取使用者基本資訊

API 總覽

if (UserInformation.NameAccessAllowed) {
    string displayName = await UserInformation.GetDisplayNameAsync();
    string firstName = await UserInformation.GetFirstNameAsync();
    string lastName = await UserInformation.GetLastNameAsync();
    // 以下需 Package.appxmanifest 加入 
    // string domain = await UserInformation.GetDomainNameAsync();
    // string principal = await UserInformation.GetPrincipalNameAsync();
}

隱私權考量

所有 API 均受 NameAccessAllowed 守護,使用者可在系統設定隨時撤銷授權,應用程式需妥善處理拒絕存取的情境。

二、帳戶圖片與視訊的存取與設定

三種規範尺寸

  • 小圖:96×96(開始畫面磚貼)
  • 大圖:448×448(鎖畫面、使用者選單)
  • 視訊:MP4 格式(鎖畫面動態背景)

讀取現有圖片/視訊

StorageFile small = UserInformation.GetAccountPicture(AccountPictureKind.SmallImage) as StorageFile;
StorageFile large = UserInformation.GetAccountPicture(AccountPictureKind.LargeImage) as StorageFile;
StorageFile video = UserInformation.GetAccountPicture(AccountPictureKind.Video) as StorageFile;
// 使用 OpenReadAsync 串流載入至 Image/MediaElement

設定新圖片

FileOpenPicker picker = new FileOpenPicker { ... };
StorageFile file = await picker.PickSingleFileAsync();
if (file != null) {
    // 可分別指定小圖、大圖、視訊,null 表示保持原值
    SetAccountPictureResult result = await UserInformation.SetAccountPicturesAsync(null, file, null);
    if (result == SetAccountPictureResult.Success) { /* 成功 */ }
}

變更通知事件

UserInformation.AccountPictureChanged += (sender, e) => {
    // 重新載入三種圖片/視訊
};

三、Live Connect OAuth 2.0 驗證與資料存取

前置作業

  1. 至 Live Connect 開發人員中心 註冊應用程式,取得 Client ID / Secret
  2. 設定重新導向網域(如 https://webabcd.cnblogs.com)

核心類別:OnlineIdAuthenticator

OnlineIdAuthenticator authenticator = new OnlineIdAuthenticator();

登入流程

var scopes = new List {
    new OnlineIdServiceTicketRequest("wl.basic wl.contacts_photos wl.calendars", "DELEGATION")
};
var result = await authenticator.AuthenticateUserAsync(scopes, CredentialPromptType.PromptIfNeeded);
if (result.Tickets[0].Value != string.Empty) {
    string token = result.Tickets[0].Value; // 可用於 REST API 呼叫
    // 例如:https://apis.live.net/v5.0/me?access_token={token}
} else {
    int errorCode = result.Tickets[0].ErrorCode;
}

登出

await authenticator.SignOutUserAsync();

權限範圍 (Scopes) 常用值

Scope權限說明
wl.basic基本個人資料(姓名、性別、地區等)
wl.emails主要電子郵件
wl.contacts_photos聯絡人相片
wl.calendars行事曆讀寫
wl.photos相簿存取
wl.skydriveOneDrive 檔案存取

總結與原始碼下載

Microsoft 帳戶整合提供無縫的單一登入體驗,配合 Live Connect 豐富的 API 生態系,應用程式能輕鬆實作社交分享、檔案同步、行事曆同步等進階功能。開發者需注意隱私權設定與權限範圍的最小化原則。

完整原始碼下載: https://files.cnblogs.com/webabcd/Windows8.rar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved