C#-如何使用OAuth2访问令牌检索谷歌云打印机



我已经获得了打印机列表,并通过代码"使用C#的谷歌云打印"向谷歌云打印提交了打印机作业,但我不能使用我的客户的谷歌密码访问他们的打印机。

现在我正在实现oauth2身份验证,我已经获得了测试帐户的Calendar和Google Cloud Print的访问权限,但现在我不知道如何检索打印机列表,以及如何使用此授权令牌发布打印机的作业。

对于oauth2,我已经下载了这个例子,效果非常好"https://github.com/nanovazquez/google-calendar-sample".

对于拥有Google Cloud Print的权限,只需在_scopes成员处添加"https://www.googleapis.com/auth/cloudprint"即可。

using System.Web;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Calendar.v3;
using Google.Apis.Util;
namespace GoogleApiUtils
{
    public static class GoogleAuthorizationHelper
    {
        private static string _clientId = ConfigurationManager.AppSettings["ClientId"];
        private static string _clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
        private static string _redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
        private static string[] _scopes = new[] { CalendarService.Scopes.Calendar.GetStringValue(), "https://www.googleapis.com/auth/cloudprint" };
...

有人能给我一些建议吗?

我做了一个小的C#MVC项目。我检索了OAuth2访问令牌,并用它来获取谷歌云打印机的列表。我不知道是否还有其他方法可以做到这一点。我希望这能帮助到别人。

我最大的问题是如何在访问令牌过期时刷新它。这是我的解决方案:

    public async Task<ActionResult> PrintersListAsync(CancellationToken cancellationToken)
    {           
        cancellationToken.ThrowIfCancellationRequested();
        List<CloudPrinter> model = new List<CloudPrinter>();
        try
        {
             ViewBag.Message = "Your printers.";
            var result = await new AuthorizationCodeMvcApp(this, new AppAuthFlowMetadata()).AuthorizeAsync(cancellationToken);
            if (result.Credential == null)
            {
                // Open Google page for authorization
                return new RedirectResult(result.RedirectUri);
            }
            //Check if token is expired
            if (result.Credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default)) {
                //renew token
                Boolean tokenRefreshed = await result.Credential.RefreshTokenAsync(cancellationToken);
                if (!tokenRefreshed)
                {                       
                    //Refresh token failed!
                    return new RedirectResult(result.RedirectUri);
                }
            }
            //Ok, now we have rights to access to user printers
            GoogleCloudPrint cloudPrint = new GoogleCloudPrint(result.Credential, String.Empty);
            //Get printers list
            var printers = cloudPrint.Printers;
            if (printers.success)
            {
                model = printers.printers;
            }
            return View(model);
        }
        catch (Exception ex)
        {
            ViewBag.Message = "Exception: " + ex.Message;
            return View(model); 
        }           
    }

链接到C#MVC项目

如有任何改进,不胜感激。

最新更新