web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested Answer

401 - Unauthorized Error while generating token through Plugin

(0) ShareShare
ReportReport
Posted on by

Hello,

I have created a Plugin to call REST API but while I am generating token it gives "401 Unauthorized" error in the result.

Below is the code I am using to generate the token. As soon as it goes to res, it throws an error.

private static async Task GetToken(string clientId, string clientSecret, string tokenBaseUrl)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new System.Uri(tokenBaseUrl);
               

                try
                {
                    var keysValues = new List<KeyValuePair>
                    {
                        new KeyValuePair("grant_type", "client_credentials"),
                        new KeyValuePair("client_id", clientId),
                        new KeyValuePair("clientSecret", clientSecret)
                        

                };
                   

                    var res = await client.PostAsync("/ul/auth/oauth/v2/token", new FormUrlEncodedContent(keysValues));
                    return JsonConvert.DeserializeObject(await res.Content.ReadAsStringAsync()).access_token.Value;
                
                
                }
                catch(Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
        }

In header the error is "x-ca-err: 300201"

2022_2D00_01_2D00_25-00_5F00_17_5F00_05_2D00_.png

However, I have tested my code in console app, it's working and also verified - client id, client secret, url - everything is correct.

Any help is really appreciated!!

Thank You!

I have the same question (0)
  • Guido Preite Profile Picture
    54,086 Moderator on at

    is this code to get a dataverse token? if yes, the code you posted I doubt it works inside a console application, both values and the url are wrong

  • Divya_R Profile Picture
    on at

    Hi  Guido Preite ,

    Thanks for your reply. No, this code is to call an external API, and the above code posted is generating token in console app with no issues.

    I am calling GetToken method like this -

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetToken(_clientId, _clientSecret, _tokenBaseUrl));CodeCode

    clientId, clientSecret an tokenURL I have added into Unsecure configuration.

    Thank You!

  • Guido Preite Profile Picture
    54,086 Moderator on at

    If is an external API there are very few things you can try. First of all I will try by putting the values directly inside the plugin (maybe you have an error when you retrieve the info from the unsecure configuration), second I will check again the name of the parameters you are passing, for the grant_type client_credentials looks strange to me that you are passing client_id but "clientSecret", it normally is "client_secret"

    hope it helps

  • Divya_R Profile Picture
    on at

    Hi Guido Preite,

    Thanks so much. It really helped.. my bad that clientSecret was the problem.

    I am getting one more error though while updating the entity. I am getting the correct json response but the exception I am getting is on - service.Update(entity);

    Exception : Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract which is not supported. Consider modifying the definition of collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.

    Below is the code and packages used in my plugin:

    public void Execute(IServiceProvider serviceProvider)
            {
                string id = "";
    
               
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    
                try {
                    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                    {
                        Entity entity = (Entity)context.InputParameters["Target"];
    
                        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
                        if (context.MessageName == "Create")
                        {
                            
                            if (entity.LogicalName == "contact" && entity.Attributes.Contains("email"))
                            {
                                String emailaddress = entity.GetAttributeValue("email");
                                id = email.Split('@')[0];
    
                                var jsonResponse = JObject.Parse(ContactData(_clientId, _clientSecret, _tokenBaseUrl, _urlBase, idul).GetAwaiter().GetResult());
                               
                              
                                if (entity.GetAttributeValue("name") == null)
                                {
                                    entity["name"] = jsonResponse["name"];
                                    service.Update(entity);
                                }
    
                            }
                        }
    
                    }
                }


    Packages used:

    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;
    using System.Net.Http;
    using System.Net;
    using System.IO;
    using IdentityModel.Client;
    using System.Runtime.Serialization;
    using System.Web;
    using System.Net.Http.Headers;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

  • Suggested answer
    Bipin D365 Profile Picture
    28,995 Moderator on at

    Hi,

    create the entities in the JSON as classes, and let JSON.NET deserialize the JSON into that.

    stackoverflow.com/.../project-without-service-reference-error-type-newtonsoft-json-linq-jtoken-is

    Please mark my answer verified if this is helpful!

    Regards,

    Bipin Kumar

    Follow my Blog: xrmdynamicscrm.wordpress.com/

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Season of Sharing Community Challenge Winners!

Congratulations to our community stars!

Women in Power Builds Momentum

Expanding mentorship, skilling, and AI innovation

Congratulations to the July Top 10 Community Leaders

These are the community rock stars!

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
11manish Profile Picture

11manish 90 Super User 2026 Season 2

#2
Daniyal Khaleel Profile Picture

Daniyal Khaleel 40 Most Valuable Professional

#3
Muhammad Shahzad Shafique Profile Picture

Muhammad Shahzad Sh... 35 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans