How do I get an OAuth 2.0 authentication token in C#

后端 未结 7 1177
借酒劲吻你
借酒劲吻你 2020-12-02 11:15

I have these settings:

  • Auth URL (which happens to be a \"https://login.microsoftonline.com/...\") if that helps.
  • Access Token URL \"https://service.en
7条回答
  •  遥遥无期
    2020-12-02 11:52

    Here is a complete example. Right click on the solution to manage nuget packages and get Newtonsoft and RestSharp:

    using Newtonsoft.Json.Linq;
    using RestSharp;
    using System;
    
    
    namespace TestAPI
    {
        class Program
        {
            static void Main(string[] args)
            {
                String id = "xxx";
                String secret = "xxx";
    
                var client = new RestClient("https://xxx.xxx.com/services/api/oauth2/token");
                var request = new RestRequest(Method.POST);
                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("content-type", "application/x-www-form-urlencoded");
                request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=all&client_id=" + id + "&client_secret=" + secret, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
    
                dynamic resp = JObject.Parse(response.Content);
                String token = resp.access_token;            
    
                client = new RestClient("https://xxx.xxx.com/services/api/x/users/v1/employees");
                request = new RestRequest(Method.GET);
                request.AddHeader("authorization", "Bearer " + token);
                request.AddHeader("cache-control", "no-cache");
                response = client.Execute(request);
            }        
        }
    }
    

提交回复
热议问题