Create client token OAuth2 question

Robin McAninch 21 Reputation points
2022-02-10T02:00:00.663+00:00

Hi
I have a secured API that I am trying to call from an existing MVC project. I have a client secret and it works fine in Postman. My first attempt at building a token in C# to be sent via an HTTP Client worked but it did not include the role so it came back as unauthorized. The Postman token works. If I drop the postman token in my project it calls the API without issue. I used a tool to decode the jwt and the Postman token has the role and the one in my code does not. How do I request a client credential token in .Net framework classic (4.7) where I get roles back? I can't seem to just find an example of the client. Almost all the info I find is how to secure the API. I don't need to secure the API. I just need a token with the roles in it.

The restsharp code in postman doesn't work because my prerequest script has already gotten the right token.. The big difference I see between Postman and my code is that my code is using a resource and not a scope. Looking at the postman token call it has in the request body

grant_type: "client_credentials"
client_id: "XXXXXXX"
client_secret: "XXXXXXXXXXXXXX"
scope: "@@@@@@@@@@@@@"

Any help would be appreciated. Ideally I just want to create an httpclient get a token, do a simple get and be done.

Thanks

Developer technologies ASP.NET Other
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2022-02-10T08:43:15.007+00:00

    Hi @Robin McAninch ,
    I suggest you can try to use FormUrlEncodedContent to achieve requesting Web API OAuth token using HttpClient.
    https://learn.microsoft.com/en-us/dotnet/api/system.net.http.formurlencodedcontent?view=net-6.0

    var client = new HttpClient();  
    client.BaseAddress = new Uri("***");  
    var content = new FormUrlEncodedContent(new[]  
    {  
          new KeyValuePair<string, string>("grant_type", "client_credentials"),  
          new KeyValuePair<string, string>("scope", Injected.Instance.Platform.GetId())  
     });  
      
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(plainTextBytes));  
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");  
    var result = await client.PostAsync("token",content);  
    string resultContent = await result.Content.ReadAsStringAsync();  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Robin McAninch 21 Reputation points
    2022-02-10T19:13:32.887+00:00

    Taking some of what you posted (thank you) and a bit of further digging I believe that I have the answer. I needed to

    using(HttpClient client = new HttpClient())
    {
    var content = new FormUrlEncodedContent(new[]
    {
    new KeyValuePair<string,string>("grant_type","client_credentials"),
    new KeyValuePair<string, string>("client_id","XXXXXXXXXXXXXX"),
    new KeyValuePair<string, string>("client_secret","ZZZZZZZZZZZZ"),
    new KeyValuePair<string, string>("scope","@@@@@@@@")
    });

    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

    var res = await client.PostAsync("https://login.microsoftonline.com/#################/oauth2/v2.0/token", content);
    string resp = await res.Content.ReadAsStringAsync();

    And now my token is showing roles whereas before it wasn't coming back. I also modelled this on a Pre-request jscript I was using in Postman but I got the info on lines 3 and 10 from your response. Thank you very much for your help

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.