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

后端 未结 7 1214
借酒劲吻你
借酒劲吻你 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:35

    In Postman, click Generate Code and then in Generate Code Snippets dialog you can select a different coding language, including C# (RestSharp).

    Also, you should only need the access token URL. The form parameters are then:

    grant_type=client_credentials
    client_id=abc    
    client_secret=123
    

    Code Snippet:

    /* using RestSharp; // https://www.nuget.org/packages/RestSharp/ */
    
    var client = new RestClient("https://service.endpoint.com/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&client_id=abc&client_secret=123", ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);
    

    From the response body you can then obtain your access token. For instance for a Bearer token type you can then add the following header to subsequent authenticated requests:

    request.AddHeader("authorization", "Bearer ");
    

提交回复
热议问题