使用 .NET 框架的 OAuth 身份验证请求示例

Example of OAuth authenticated request using .NET framework

下面的 Node.JS 代码将 0-legged OAuth 身份验证请求发送到 API:

'use strict';
var OAuth = require('OAuth');
var express = require('express');
var app = express();

var oauth = new OAuth.OAuth(
  'http://example.com/oauth/request_token',
  'http://example.com/oauth/access_token',
  'mykey',
  'none',
  '1.0',
  null,
  'HMAC-SHA1'
);

app.get('/', function (req, res) {
  oauth.get(
    'http://example.com/api',
    'token123',
    'tokensecret123',
    function (error, data, response){
      data = JSON.parse(data);
      res.json(data);
    });
});

我需要将此代码转换为 C# 或 VB.NET。 .Net 中的任何 OAuth 身份验证请求示例也会有所帮助。

我使用库 RestSharp 来完成它,它有助于处理 REST API。

下面的代码发送请求以从 OAuth 获取令牌:

var restClient = new RestClient();
restClient.BaseUrl = new Uri("theApiBaseUrl");

string encodedCredentials = Convert.ToBase64String(Encoding.Default.GetBytes($"yourAppId:yourSecret"));

// change the request below per the API requirement
RestRequest request = new RestRequest("theApiUrlForAuthentication", Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", $"Basic {encodedCredentials}");
request.AddQueryParameter("grant_type", "client_credentials");
request.AddQueryParameter("scope", "api");

IRestResponse response = restClient.Execute(request);

// the token should be in the JSON string response.Content
// now you'll want to deserialize the JSON to get the token
var jsonWithToken = MyFunctionToGetToken(response.Content);

现在您有了令牌,可以对 API:

进行 身份验证调用
var restClient = new RestClient();
restClient.BaseUrl = new Uri("theApiBaseUrl");

RestRequest request = new RestRequest("theApiEndpoint", Method.GET);
request.AddHeader("Accept", "application/hal+json");
request.AddHeader("profile", "https://api.slimpay.net/alps/v1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {token}");

RestClient.Execute(request);

每个 API 都是不同的,因此您肯定需要修改我的代码(添加或删除 headers、对凭据进行编码,...)以便它适合您。

感谢@Guillaume Sasdy 引导我使用 RestSharp。这是一个有效的解决方案,其工作方式与我问题中的 node.js 代码相同。 由于 API 我正在访问的是使用 0-legged OAuth,访问令牌和访问密钥是预先知道的,这让事情变得更容易。

const string consumerKey = "mykey";
const string consumerSecret = "none";
var baseUrl = "https://example.com";
var client = new RestClient(baseUrl);

var request = new RestRequest("/api");
client.Authenticator = OAuth1Authenticator.ForProtectedResource(
    consumerKey, consumerSecret, "token123", "tokensecret123"
);

var response = client.Execute(request);