WinRT:WebAuthenticationBroker For OAuth认证
发布日期:2021-05-09 06:29:35 浏览次数:15 分类:博客文章

本文共 1475 字,大约阅读时间需要 4 分钟。

之前开发过QQ互联的OAuth 的.NET/Mono/Windows Phone SDK,具体可以 。到了Windows 8的Metro 程序如何使用QQ互联的API呢,今天做了一些实验性的代码验证。使用OAuth的最大挑战就是获得AccessToken,在OAuth的一个App AccessToken从本质上来说就是用户的验证登陆和用户的权限授权,获取到用户的accessToken后,就可以使用AccessToken 对REST API发送请求了。

微软在Metro/WinRT里头已经完整的包括上述OAuth验证的库,叫做WebAuthenticationBroker,他为我们完成大量的工作,例如下面的图,在WP7上使用一个WebBrower来玩吃的,Metro里头为们提供了无边框的浏览器窗口。

这个框框看起来不太好看,期望QQ互联能够检测到这里从Windows8的Metro UI发起的请求,展现更加Metro的UI。

我们来看下代码,不由得感叹这代码太漂亮了,在WebAuthenticationBroker上await,它返回一个对象,指示用户是否取消,发生了错误,还是成功了。

                System.Uri StartUri = new Uri(TencentURL);

                System.Uri EndUri = new Uri(this.TencentCallbackUrl.Text);

                DebugPrint("Navigating to: " + FacebookURL);

                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(

                                                        WebAuthenticationOptions.None,
                                                        StartUri,
                                                        EndUri);
                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    OutputToken(WebAuthenticationResult.ResponseData.ToString());
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else
                {
                    OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
                }
            }

这代码非常的简洁,一个很酷的机制,我们没有以任何方式附加到UI代码,它只是注入到自身的一个UI上。它的原理请看MSDN文档 ,相应的代码示例参考,微软在这些例子里实现几个国外的例子: Facebook,twitter,Windows Live,Google ,Flickr服务,其中没有本地化的服务例子,今天我就在这些例子的基础上初步验证了QQ互联的API,同样的应该也适用于人人,新浪,阿里,百度等的开放平台。

上一篇:使用MiniProfiler调试ASP.NET MVC网站性能
下一篇:2012 ASP.NET/IIS MVP

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月18日 11时00分57秒