DotNetOpenAuth OAuth2

1.4k views Asked by At

So I've been getting my first steps into OAuth2 and managed to get an access token from a private API using RestSharp. Since that is only one small step in the whole process I've wondered if there is a framework which simplifies the process and manages tokens.

I've read about DotNetOpenAuth in a lot of blogs and I've already spend some time reading through the documentation, but for some reason I don't understand how I would use it to implement a client and some kind of "token manager/handler".

Can anyone provide me with a small sample or at least name the classes with are essential for an OAuth2 client and "token manager/handler"?

Thank you!


Edit

This is a "token" class which basically just stores the data recieved from the authorization server when requesting an access token:

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

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

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

appsettings.json

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

and this is where I request the access token:

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);

This actually works fine.

My question is, do I have to build a logic on my own which handles this token or is there already a framework which does all the work for me (I've read about DotNetOpenAuth but haven't found an example which would help me)?

0

There are 0 answers