首页 > 解决方案 > DotNetOpenAuth OAuth2

问题描述

因此,我已经迈出了进入 OAuth2 的第一步,并设法使用RestSharp从私有 API 获取访问令牌。由于这只是整个过程中的一小步,我想知道是否有一个框架可以简化流程并管理令牌。

我在很多博客中都阅读过有关DotNetOpenAuth的内容,并且我已经花了一些时间阅读文档,但由于某种原因,我不明白如何使用它来实现客户端和某种“令牌管理器/处理程序”。

任何人都可以为我提供一个小样本或至少命名这些类对于 OAuth2 客户端和“令牌管理器/处理程序”是必不可少的吗?

谢谢!


编辑

这是一个“令牌”类,它基本上只存储在请求访问令牌时从授权服务器收到的数据:

public class Token
{
        public Token()
        {
            Issued = DateTime.Now;
        }

        [JsonProperty("access_token")]
        public string AccessToken
        {
            get;
            set;
        }

        [JsonProperty("token_type")]
        public string TokenType
        {
            get;
            set;
        }
// ...
}

应用设置.json

{
    "Authentication": {
    "tokenurl": "https://tokenurl.com/give/me/token",
    "Credentials": {
      "client-id": "clientid",
      "client-secret": "clientsecret",
      "grant-type": "client_credentials",
      "scope": "scope"
    }
}

这是我请求访问令牌的地方:

Dictionary<string, string> authCred = 
                Configuration.
                GetSection("Authentication:Credentials").
                GetChildren().
                Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).
                ToDictionary(x => x.Key, x => x.Value); 


            var client = new RestClient(Configuration["tokenurl"]);
            RestRequest request = new RestRequest()
            {
                Method = Method.POST
            };
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{authCred["client-id"]}:{authCred["client-secret"]}")));
            request.AddParameter("application/x-www-form-urlencoded", $"grant_type={authCred["grant-type"]}&scope={authCred["scope"]}", ParameterType.RequestBody);
            var response = client.Execute(request);
            Token test = JsonConvert.DeserializeObject<Token>(response.Content);

这实际上工作正常。

我的问题是,我是否必须自己构建一个逻辑来处理这个令牌,或者是否已经有一个框架可以为我完成所有工作(我已经阅读了有关 DotNetOpenAuth 但没有找到对我有帮助的示例) ?

标签: c#oauth-2.0dotnetopenauth

解决方案


推荐阅读