使用Restsharp和OAUTH的浏览器获取用户身份验证

时间:2013-09-18 08:50:42

标签: oauth restsharp khan-academy

Khan Academy的API要求用户使用他/她的网络浏览器进行身份验证。 这是Khan Academy's authentication manual

当尝试获取请求令牌时,请求失败,因为用户自己没有批准它。

这是我的代码:

string _server_url = "http://www.khanacademy.org";
string _consumer_key = "key";
string _consumer_secret = "secret";

//Request token
RestClient client = new RestClient();
client.BaseUrl = _server_url;
client.Authenticator = OAuth1Authenticator.ForRequestToken(_consumer_key, _consumer_secret);
RestRequest request = new RestRequest("api/auth/request_token", Method.GET);

var response = client.Execute(request);

var qs = HttpUtility.ParseQueryString(response.Content);
var oauth_token = qs["oauth_token"];
var oauth_token_secret = qs["oauth_token_secret"];

oauth_tokenoauth_token_secret都返回为null。

使用RestSharp时,有没有办法启动浏览器并要求用户进行身份验证?

1 个答案:

答案 0 :(得分:0)

最终我在WinForms中使用了一个WebBrowser对象来解决这个问题。这是我的代码:

    public Authenticate()
    {
        InitializeComponent();
        //Request token
        Client.BaseUrl = Server_url;
        Client.Authenticator = OAuth1Authenticator.ForRequestToken(Consumer_key, Consumer_secret);
        RestRequest request = new RestRequest("api/auth/request_token", Method.GET);


        //request response
        var response = Client.Execute(request);

        //pull out the google url out of the response (which is a HTML page)
        int index = response.Content.IndexOf("/api/auth/request_token_callback/google/") + "/api/auth/request_token_callback/google/".Length;
        string key = response.Content.Substring(index, 10);
        if (response.StatusDescription.Equals("OK"))
        {
            var url = response.ResponseUri.AbsoluteUri;
            webBrowser.Navigate(new Uri(url));
        }
        else
            throw new Exception();
    }

当用户通过Google / Facebook / Email完成身份验证后,我可以使用webBrowser.Url提取他的oauth_token和oauth_token_secret:

            string source = webBrowser.Url.ToString();
            var qs = HttpUtility.ParseQueryString(source);
            var oauth_token_secret = HttpUtility.ParseQueryString(source).Get(0);

            var oauth_token = qs["oauth_token"];
            Client.BaseUrl = Server_url;
            Client.Authenticator = OAuth1Authenticator.ForAccessToken(Consumer_key, Consumer_secret, oauth_token, oauth_token_secret);

顺便说一下,HttpUtility.ParseQueryString(source)存在一个错误。 see this post for a solution(这也在这里实施)