OAuth2 +生成新的授权承载访问令牌C#MVC

时间:2018-05-22 09:07:31

标签: c# asp.net-mvc postman

任何人都可以帮我在C#MVC中生成访问令牌。

PostMan Access Token Generation

以下代码在控制台应用程序中正常工作但它在MVC中无法正常工作#得到错误" URL无法解析"

 static void Main(string[] args)  {
       Console.WriteLine("Starting ...");
        DoIt().Wait();
        Console.ReadLine();
    }
 private static async Task<string> DoIt()     {

        accessToken = await GetAccessToken();

return accessToken;
    }

    private static async Task<string> GetAccessToken()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseUrl);

            // We want the response to be JSON.
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Build up the data to POST.
            List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            postData.Add(new KeyValuePair<string, string>("client_id", "clientId"));
            postData.Add(new KeyValuePair<string, string>("client_secret", "clientSecret"));
            postData.Add(new KeyValuePair<string, string>("access_token_url", "Access Token URL"));

            FormUrlEncodedContent content = new FormUrlEncodedContent(postData);

            // Post to the Server and parse the response.
            HttpResponseMessage response = client.PostAsync("Token", content).Result;
            string jsonString = await response.Content.ReadAsStringAsync();
            object responseData = JsonConvert.DeserializeObject(jsonString);

            // return the Access Token.
            return ((dynamic)responseData).access_token;
        }
    }

0 个答案:

没有答案