c# - 每次都会出现权限屏幕

标签 c# winforms live-sdk

我想让我的 WinForms 应用程序对 Microsoft 帐户使用单点登录 (SSO) 功能。
我创建了一个LiveApp我可以使用 LiveSDK 5.4 登录我的应用程序。
但每次我单击登录按钮时,都会出现权限列表,我需要再次接受它。

这是我的代码:

private const string ClientID = "{MY_CLIENT_ID}";
private LiveAuthClient liveAuthClient;
private LiveConnectClient liveConnectClient;
string[] scopes = new string[] { "wl.offline_access", "wl.emails", "wl.signin" };

private void buttonLogin_Click(object sender, EventArgs e)
{
    liveAuthClient = new LiveAuthClient(ClientID);
    webBrowser1.Navigate(liveAuthClient.GetLoginUrl(scopes));
}

private async void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
    if (this.webBrowser1.Url.AbsoluteUri.StartsWith("https://login.live.com/oauth20_desktop.srf"))
    {
        AuthResult authResult = new AuthResult(this.webBrowser1.Url);
        if (authResult.AuthorizeCode != null)
        {
            try
            {
                LiveConnectSession session = await liveAuthClient.ExchangeAuthCodeAsync(authResult.AuthorizeCode);
                this.liveConnectClient = new LiveConnectClient(session);
                LiveOperationResult meRs = await this.liveConnectClient.GetAsync("me");
                dynamic meData = meRs.Result;
                if(string.Equals(meData.emails.account, MyAppUser.EmailAddress))
                    MessageBox.Show("Successful login: " + meData.name);
            }
            catch (LiveAuthException aex)
            {
                MessageBox.Show("Failed to retrieve access token. Error: " + aex.Message);
            }
            catch (LiveConnectException cex)
            {
                MessageBox.Show("Failed to retrieve the user's data. Error: " + cex.Message);
            }
        }
        else
        {
            MessageBox.Show(string.Format("Error received. Error: {0} Detail: {1}", authResult.ErrorCode, authResult.ErrorDescription));
        }
    }
}

我需要改变什么?我不希望用户每次登录时都接受权限。

最佳答案

您可以使用IRefreshTokenHandler来保存 token ,如下例:

public class RefreshTokenHandler : IRefreshTokenHandler
{
    private string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\oneDrive\\RefreshTokenHandler\\RefreshTokenInfo.RefreshToken-me";
    public Task<RefreshTokenInfo> RetrieveRefreshTokenAsync()
    {
        return Task.Factory.StartNew<RefreshTokenInfo>(() =>
        {
            if (File.Exists(path))
            {
                return new RefreshTokenInfo(File.ReadAllText(path));
            }
            return null;
        });
    }

    public Task SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo)
    {
        // Note: 
        // 1) In order to receive refresh token, wl.offline_access scope is needed.
        // 2) Alternatively, we can persist the refresh token.
        return Task.Factory.StartNew(() =>
        {
            if (File.Exists(path)) File.Delete(path);
            if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path));
            File.AppendAllText(path, tokenInfo.RefreshToken);
        });
    }
}

之后您将获得如下 session :

RefreshTokenHandler handler = new RefreshTokenHandler();
liveAuthClient = new LiveAuthClient(ClientID, handler);
var Session = liveAuthClient.InitializeAsync(scopes).Result.Session;
if (Session == null)
{
    webBrowser1.Navigate(liveAuthClient.GetLoginUrl(scopes));
}
else
{
    try
    {
        this.liveConnectClient = new LiveConnectClient(Session);
        LiveOperationResult meRs = await this.liveConnectClient.GetAsync("me");
        dynamic meData = meRs.Result;
        if (string.Equals(meData.emails.account, MyAppUser.EmailAddress))
            MessageBox.Show("Successful login: " + meData.name);
    }
    catch (LiveAuthException aex)
    {
        MessageBox.Show("Failed to retrieve access token. Error: " + aex.Message);
    }
    catch (LiveConnectException cex)
    {
        MessageBox.Show("Failed to retrieve the user's data. Error: " + cex.Message);
    }
}

关于c# - 每次都会出现权限屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18955426/

相关文章:

c# - Winforms 中的可视 TreeMap

ios - 错误 ITMS-9000 : “Unsupported architectures. Xcode 存档错误

c# - 在 ASP.NET session 之外使用 HttpApplicationState

c# - 我如何在 C# 中检查数据库中是否存在表(ACCESS 或 SQL)

c# - 使用 SetValue 时未创建注册表项

c# - 对用 years 填充 ComboBox 感到困惑

c# - 如何在 Windows 8 的桌面应用程序中访问 Metro 应用程序的本地存储?

.net - 我想在标题栏上显示当前的构建信息

c# - 如何在桌面应用程序中使用 OneDrive 的 api 并记住权限?