Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 何时/何地使用azure后端刷新Windows 10应用程序中的访问令牌_C#_Azure_Authentication_Uwp_Refresh Token - Fatal编程技术网

C# 何时/何地使用azure后端刷新Windows 10应用程序中的访问令牌

C# 何时/何地使用azure后端刷新Windows 10应用程序中的访问令牌,c#,azure,authentication,uwp,refresh-token,C#,Azure,Authentication,Uwp,Refresh Token,我正在学习使用azure后端构建Windows 10应用程序。我正在使用Micosoft帐户作为身份验证提供程序。我已经学会了如何缓存访问令牌,但我对刷新令牌有点迟疑 据我所知,访问令牌的寿命很短,过期时间较长的刷新令牌允许我获取新的访问令牌。我一直在尝试跟随阿德里安·霍尔的书: 我的问题是,我不太明白何时何地调用或如何使用“client.RefreshUserAsync();”,这本书也不太清楚 我应该什么时候打电话给refresh??我猜问题是,令牌可能会在用户中间使用应用程序过期,迫使用户

我正在学习使用azure后端构建Windows 10应用程序。我正在使用Micosoft帐户作为身份验证提供程序。我已经学会了如何缓存访问令牌,但我对刷新令牌有点迟疑

据我所知,访问令牌的寿命很短,过期时间较长的刷新令牌允许我获取新的访问令牌。我一直在尝试跟随阿德里安·霍尔的书:

我的问题是,我不太明白何时何地调用或如何使用“client.RefreshUserAsync();”,这本书也不太清楚

我应该什么时候打电话给refresh??我猜问题是,令牌可能会在用户中间使用应用程序过期,迫使用户再次登录,对吗?那么,每次我的用户做任何事情时,我都会调用refresh吗?我很困惑

现在,我的应用程序在我的主页上只有一个AuthenticateTasync方法,当用户单击登录按钮时执行。它查找缓存的令牌,如果有,它会检查过期情况,如果过期则重新验证

private async System.Threading.Tasks.Task<bool> AuthenticateAsync()
    {
        string message;
        bool success = false;

        var provider = MobileServiceAuthenticationProvider.MicrosoftAccount;

        // Use the PasswordVault to securely store and access credentials
        PasswordVault vault = new PasswordVault();
        PasswordCredential credential = null;

        try
        {
            //try to get an existing credential from the vault.
            credential = vault.FindAllByResource(provider.ToString()).FirstOrDefault();

        }
        catch (Exception)
        {
            //When there is no matching resource an error occurs, which we ignore.
        }

        if (credential != null)
        {

            // Create a user from the stored credentials.
            user = new MobileServiceUser(credential.UserName);
            credential.RetrievePassword();
            user.MobileServiceAuthenticationToken = credential.Password;

            // Set the user from the stored credentials.
            App.MobileService.CurrentUser = user;


            success = true;
            message = string.Format("Cached credentials for user - {0}", user.UserId);

            // Consider adding a check to determine if the token is 
            // expired, as shown in this post: http://aka.ms/jww5vp

            //check expiration
            if (App.MobileService.IsTokenExpired())
            {
                //remove the expired credentials
                vault.Remove(credential);

                try
                {
                    // Login with the identity provider
                    user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);

                    // Create and store the user credentials.
                    credential = new PasswordCredential(provider.ToString(),
                        user.UserId, user.MobileServiceAuthenticationToken);

                    vault.Add(credential);

                    message = string.Format("Expired credentials caused re-authentication. You are now signed in - {0}", user.UserId);
                    success = true;
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login required.";
                }
            }
        }
        else
        {
            try
            {
                // Login with the identity provider
                user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);

                // Create and store the user credentials.
                credential = new PasswordCredential(provider.ToString(),
                    user.UserId, user.MobileServiceAuthenticationToken);
                vault.Add(credential);

                message = string.Format("You are now signed in - {0}", user.UserId);
                success = true;
            }
            catch (InvalidOperationException)
            {
                message = "You must log in. Login required.";
            }
        }

        var dialog = new MessageDialog(message);
        dialog.Commands.Add(new UICommand("OK"));
        await dialog.ShowAsync();

        return success;
    }
private async System.Threading.Tasks.Task authenticatesync()
{
字符串消息;
布尔成功=假;
var provider=MobileServiceAuthenticationProvider.MicrosoftAccount;
//使用PasswordVault安全地存储和访问凭据
PasswordVault=新的PasswordVault();
PasswordCredential-credential=null;
尝试
{
//尝试从vault中获取现有凭据。
凭证=vault.FindAllByResource(provider.ToString()).FirstOrDefault();
}
捕获(例外)
{
//当没有匹配的资源时,会发生错误,我们将忽略该错误。
}
如果(凭证!=null)
{
//从存储的凭据创建用户。
用户=新的MobileServiceUser(凭证.用户名);
credential.RetrievePassword();
user.MobileServiceAuthenticationToken=凭证.Password;
//从存储的凭据设置用户。
App.MobileService.CurrentUser=用户;
成功=真实;
message=string.Format(“缓存的用户凭据-{0}”,user.UserId);
/考虑添加检查以确定令牌是否为
//已过期,如本文所示:http://aka.ms/jww5vp
//检查有效期
如果(App.MobileService.IsTokenExpired())
{
//删除过期的凭据
删除(凭证);
尝试
{
//使用身份提供者登录
user=wait App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
//创建并存储用户凭据。
凭证=新密码凭证(provider.ToString(),
user.UserId、user.MobileServiceAuthenticationToken);
添加(凭证);
message=string.Format(“过期的凭据导致重新身份验证。您现在已登录-{0}”,user.UserId);
成功=真实;
}
捕获(无效操作异常)
{
message=“您必须登录。需要登录。”;
}
}
}
其他的
{
尝试
{
//使用身份提供者登录
user=wait App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
//创建并存储用户凭据。
凭证=新密码凭证(provider.ToString(),
user.UserId、user.MobileServiceAuthenticationToken);
添加(凭证);
message=string.Format(“您现在已登录-{0}”,user.UserId);
成功=真实;
}
捕获(无效操作异常)
{
message=“您必须登录。需要登录。”;
}
}
var dialog=新建消息对话框(消息);
添加(新的UICommand(“OK”);
wait dialog.ShowAsync();
回归成功;
}

我猜问题是,令牌可能会在用户中间使用应用程序过期,迫使用户再次登录,对吗?

根据您的描述,您使用Azure mobile app作为您的UWP后端。要访问移动应用程序,我们需要使用访问令牌。正如您所知,访问令牌将过期。为了获得新的访问令牌,我们需要使用刷新令牌。如何通过刷新令牌获取访问令牌,请参阅。以下是详细的http请求信息:

// Line breaks for legibility only

POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
&grant_type=refresh_token
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=JqQX2PNo9bpM0uEihUPzyrh    // NOTE: Only required for web apps
根据以上http请求,我们只提供客户端id、刷新令牌、授权类型、资源、客户端密钥(仅限web应用)。所以我们不需要让用户再次登录

我应该什么时候打电话给refresh


如果访问令牌已过期,则在访问移动应用程序时将出现错误。此时,我们可以尝试通过catch{}逻辑中的刷新令牌来获取新的访问令牌

因此,如果我理解正确,无论我在哪里调用后端,我都应该捕获错误,刷新用户,然后再次尝试调用。您只需在收到身份验证错误时调用Azure Mobile Apps SDK中的刷新API来刷新令牌。请尝试使用新的访问令牌,看看它是否有效。