Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM forum
Suggested answer

401 - Unauthorized Error while generating token through Plugin

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!

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,962 Moderator on at
    RE: 401 - Unauthorized Error while generating token through Plugin

    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/

  • Divya_R Profile Picture
    Divya_R on at
    RE: 401 - Unauthorized Error while generating token through Plugin

    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;

  • Guido Preite Profile Picture
    Guido Preite 54,065 Moderator on at
    RE: 401 - Unauthorized Error while generating token through Plugin

    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
    Divya_R on at
    RE: 401 - Unauthorized Error while generating token through Plugin

    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
    Guido Preite 54,065 Moderator on at
    RE: 401 - Unauthorized Error while generating token through Plugin

    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

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

Anton Venter – Community Spotlight

Kudos to our October Community Star of the month!

Announcing Our 2024 Season 2 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Dynamics 365 Community Newsletter - September 2024

Check out the latest community news

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 290,558 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 228,647 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans