Episerver 10 User is not authorized for this request error get call resAPI to get catalogs (/episerverapi/commerce/catalogs)

Vote:
 

I setup new commerce site (version 10) and test call restAPI "/episerverapi/commerce/catalogs" but it's authorized error.

- I had setup ServiceAPI.

*with default user (admin) get token return error: User is not authorized.

*with windowmembership:

- Get token return success:

                client.BaseAddress = new Uri("https://mysite/");
                var fields = new Dictionary
                {
                    { "grant_type", "password" },
                    { "username", "myuser" },
                    { "password", "mypassword" }
                };
                try
                {
                    var response = client.PostAsync("/episerverapi/token", new FormUrlEncodedContent(fields)).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var content = response.Content.ReadAsStringAsync().Result;
                        token = Newtonsoft.Json.Linq.JObject.Parse(content).GetValue("access_token");
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

- Get catalogs error:

             using (var client = new HttpClient())
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate
                {
                    return (true);
                };
                client.BaseAddress = new Uri("https://mysite/");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());
                if(bIsXMLOutput)
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
                }
                var result = client.GetAsync("/episerverapi/commerce/catalogs").Result.Content.ReadAsStringAsync().Result;
            }

in my old site (episerver 9) it's no error.

Compare user in episerver9 and episerver10 i see new concept EPi_AspNetIdentityUserProvider. May u clear its for me.

please help me with this issue.

Many thanks.

#173852
Jan 11, 2017 9:34
Vote:
 

As I guess, you got error at 

var result = client.GetAsync("/episerverapi/commerce/catalogs").Result.Content.ReadAsStringAsync().Result;

Could you show me the exception message?

#173919
Jan 13, 2017 3:25
Vote:
 

Hi Son Do,

With admin user (default user): I can't get token.

With the windowmembership: I get token, but can't get catalog

result message: "\"User is not authorized for this request\"" is error message. I had check user/password. it's WebAdmins user.

Thanks.

#173920
Jan 13, 2017 3:40
Vote:
 

Hi Sy,

Your information was not enough for me find out the issue, it's too generic. Could you show me more detail on this line:

var response = client.PostAsync("/episerverapi/token", new FormUrlEncodedContent(fields)).Result;

What is result of this request?

#173921
Jan 13, 2017 5:09
Vote:
 

Hi Son Do,

PostAsync request return HttpStatusCode.OK. I can get token successfully:

token value: {FHh06o7k8qDCh1b5UiaP4W5QCjQ55nz4MdFjX-ToGK11IsWaxzVTEyp9mueQogrtVQOInyqsFYDnAwoBut0SXVuzrCf8z148yNenfgwYxe-pMpIsyLlvxXNyeoAVr9tyDzCAYM2fOgbOuRIP_DEnCL_tSE6U-WU4zLAs3gAUCuTARGKxqlPepk71wjo7CfF41WFK2J3Wm54KbfH19BT5c29dH6aK5ciWVPkZ1fJS6tsK06luALyDPTD_B9-N69ihdiKZ-PHDEVg5ayjanyd-mYEt-CacBU0wLoKBQy5BS-HIULoCm73D6wxYxwv2HzH4}

I user this token to get catalog:

                client.BaseAddress = new Uri("https://mysite/");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());
                if(bIsXMLOutput)
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
                }
                var result = client.GetAsync("/episerverapi/commerce/catalogs").Result.Content.ReadAsStringAsync().Result;

request is not success. \"User is not authorized for this request\" Error only on Episerver10

Regards,

Sy

#173922
Edited, Jan 13, 2017 5:22
Vote:
 

Hi Sy,

It's strange. I'm comparing your code and service client code on GitHub but they are the same.

Could you show me your package.config, I want to build environment to issue you got.

Regards,

/Son Do

#173928
Jan 13, 2017 7:43
Vote:
 
#173940
Edited, Jan 13, 2017 9:59
Vote:
 

Hi Son Do,

I think there is not true on my setting up step.

Today i setup latest commerce. (VS2015, CMS 10.3.1, Commerce 10.2.2)

Duplicated step:

- Setup CMS site(Alloy site).

- Setup Commerce in CMS site.

- Setup EPiServer.ServiceApi.Commerce.

Add to web.config:

<add key="owin:AutomaticAppStartup" value="true" />
<add key="owin:AppStartup" value="eCommerce10.Startup" />

Add newuser: sy.nguyen WebAdmins group

Get token: {StatusCode: 400, ReasonPhrase: 'Bad Request'}

                client.BaseAddress = new Uri("https://ecom4.dev.nis:433/");
                var fields = new Dictionary<string, string>
                {
                    { "grant_type", "password" },
                    { "username", "sy.nguyen" },
                    { "password", "abc@54321" }
                };
                try
                {
                    var response = client.PostAsync("/episerverapi/token", new FormUrlEncodedContent(fields)).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var content = response.Content.ReadAsStringAsync().Result;
                        token = Newtonsoft.Json.Linq.JObject.Parse(content).GetValue("access_token");
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

I think having some change in episerver10. Thanks advance.

Sy

#173950
Edited, Jan 13, 2017 11:51
Vote:
 

Hi Sy,

You are using latest cms and service api, so we're having a bug about authentication with service api:

The returned result is not in json format,  so parsing json causes error.

I hope we could fix it and release in cms package soon. 

Thank for your patience. 

/Son Do 

P/s: please send me your contact, I will call you when I have information about the fix. 

#173967
Edited, Jan 14, 2017 4:11
Vote:
 

Hi Son Do,

my email: sy.nguyen@niteco.se

I am updating my addon to episerver 10. Call me when u had new version without this isssue.

Regards,

Sy

#173973
Jan 16, 2017 3:43
Vote:
 

Hi Son Do,

*** Chúc Mừng Năm Mới ***

Come back after Tet holiday with lastest episerver version. Old issue is still persist. :) Episerver has plan to fix it?

Regards,

Sy

#174866
Feb 07, 2017 9:21
Vote:
 

Hi Sy,

We had plan fixing this issue and will be released soon.  I will mail to you when it out.

Thanks for your patience.

/Son Do

#174886
Edited, Feb 07, 2017 11:20
Vote:
 

Hi Sy,

I’m happy to announce that Episerver.ServiceApi 3.0 was released.

This document describes breaking change: http://world.episerver.com/documentation/upgrading/episerver-service-api/service-api-3/

And this describes how to install it to your project http://world.episerver.com/documentation/upgrading/episerver-service-api/service-api-3/installation-and-configuration/

 

Thanks again for your patience!

/Son Do

#175142
Feb 14, 2017 2:07
Vote:
 

I'm using the version 3. But I still get "User is not authorized for this request" when I'm trying to access https://localhost/episerverapi/commerce/catalogs.

I'm using Basic authentication and using the Admin user and pwd.

I just decide the try access "/commerce/catalogs" to test, because my focus is /episerverapi/token but it in this moment is returning {

{
"error": "unsupported_grant_type"
}

Can someone help me?

#175947
Mar 07, 2017 7:45
Vote:
 

Hi Anderson,

If you use ASP.NET Membership, you need to add those code below to Startup file: 

app.UseServiceApiMembershipTokenAuthorization();

If you use AspNetIdentity, adding this

app.AddCmsAspNetIdentity<ApplicationUser>();


Refer to section "Configuring OWIN startup" in this document, http://world.episerver.com/documentation/upgrading/episerver-service-api/service-api-3/installation-and-configuration/

And if you're in develop environment (without SSL), you need this 

<add key="episerver:serviceapi:requiressl" value="false" />

Could you told us that the membership type you're using? And you could  use this tool https://github.com/episerver/ServiceApi-Client to verify your service api.

#175949
Mar 07, 2017 7:57
Vote:
 

Thank you @Son Do. 

Adding this code on my startup.cs

app.UseServiceApiMembershipTokenAuthorization(new ServiceApiTokenAuthorizationOptions
{
           AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60)
});

Make my login work very well. 

But, doesn't matter which method I try to call from the API I get the same error: "User is not authorized for this request"

I checked my permission table and my user has permission for Read and Write.

It is possible test the calls from POSTMAN? How can I define the token?

#176032
Mar 08, 2017 6:55
Vote:
 

Yes, it is possible using Postman to test your service api.

After getting token using http://domain.com/episerverapi/token, you will get a token for next request.

Using this token with 'bearer' prefix, you will get result.

service api - postman

Hope this helps!

/Son Do

#176034
Mar 08, 2017 7:27
Vote:
 

This was exactly what I have tried. But the retorn from the API is the same.

do you have any another ideia?

#176046
Mar 08, 2017 12:07
Vote:
 

You say your user has read access and write access. Do you mean the Permissions 'ReadAccess' and 'WriteAccess' to the GroupName 'EPiServerServiceApi' (correct case is important) in the tblUserPermission table in the CMS database? Are they set specifically for the user or for a role the user is in? In any case, is the IsRole column correct?

#176058
Mar 08, 2017 20:39
Vote:
 

Thank you, Magnus

I'm using Admin to login in. 

3	Administrators	1	ReadAccess	EPiServerServiceApi
2	Administrators	1	WriteAccess	EPiServerServiceApi

Also, I did SQL Profiler. 

When the code executes this command:

the list returned is:

  • Administrators
  • ApiUsers
  • Everyone
  • Management Users
  • Order Managers
  • Order Supervisor
  • Receiving Manager
  • Registered
  • Shipping Manager
  • WebAdmins
  • WebEditors
  • EPiServerServiceApi

and this is my startup class:

app.AddCmsAspNetIdentity<ApplicationUser>();

            // Enable bearer token authentication using Membership for Service Api
            app.UseServiceApiMembershipTokenAuthorization();



I have no more ideas how to fix it.

#176062
Edited, Mar 08, 2017 23:41
Vote:
 

Look like we don't need 

app.AddCmsAspNetIdentity<ApplicationUser>();
#176110
Mar 10, 2017 5:24
Vote:
 

I understood Son, I already removed it. but I still with the problem, I opened a tick with episerver to investigation. 

#176111
Mar 10, 2017 5:27
Vote:
 

It looks like parts of the sql profiler info was lost. With the permissions table set up like this, the key is really that true is returned from a principal.IsInRole("Administrators") call (where principal is the authenticated user you use). Can you verify this somehow (e.g. log in manually to the site with the same user account and put a call to PrincipalInfo.CurrentPrincipal.IsInRole("Administrators"))?

#176113
Mar 10, 2017 8:45
Vote:
 

Thank you guys. 

I found the issue. In the version 2.0 I got the recommendation to implement in a different Domain. In the version 3.0 It must be implemented on the CMS.

I just was able to figure out this when I started to decompile the Episerver DLLS.

#176217
Edited, Mar 14, 2017 3:38
Vote:
 

I'm sorry, I don't understand what you mean by different URL vs on the CMS. Could you elaborate? What did you find by decompiling? Understanding the issue better can help us help others in the future. Thank you!

#176219
Mar 14, 2017 7:09
Vote:
 

Son Do,

I setup latest version episerver 10.

Setup 3.0 serviceAPI.

I can get token: {XnSx1YawazzL_TuhqONyEVNB7fOhIbSEnIhK9ye0CXU7ZnsOYTx9J0_Bisok-E4hUbom2mu8i5qBbUxxD8QvJGriH2SRPxjRTKxr7jzGaaahDzQrs_A-pDkyQA8ev49LK3TYapyyOvfuKWCY1Uv4b2FA-GAVKPOhmHu9LCFzqump2WcqH1DvWx2EBx3hX-QihiTdBfyFzYhlNDmo0e6U9kgEER2eSG5YVOJsufaJGxmt27ovoKbitB-iDaN5SMl2kadraG185O2vJ-olo-zo243jFEF1ravv6luSE3nq7omQxDVB_rQh-zKNd6ft7mPClwQpLl_mX54YWrPpy1c2fFwGXx_xh_b5WSLRxl3rQYPfeNlbVjeUPmPH7FN_0FOZKPo7d9NUGEe-RvT2nEoqDyosoAOh0zTSZtUWdQOobBM-yQTYJM-hkFVdHlR9yt7C4fcBeDrUOC1_CVBBr8TJfw3AktVhmYTSTTSt2-XaO4MzdtwfHnzHCTlaNb4IJoNX9YD1tFZ2sqeXqwucnfaz2A}

using token to get /episerverapi/commerce/catalogs to get catalog is not success:

result: error code 500, ReasonPhrase: 'Internal Server Error'

"{\"Message\":\"An error has occurred.\",\"ExceptionMessage\":\"Sequence contains more than one element\",\"ExceptionType\":\"System.InvalidOperationException\",\"StackTrace\":\"   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)\\r\\n   at Microsoft.Owin.Security.AuthenticationManager.<AuthenticateAsync>d__8.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\r\\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n   at System.Web.Http.HostAuthenticationFilter.<AuthenticateAsync>d__0.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\r\\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n   at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\r\\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()\"}"

May you show me any clue with this issue. Thanks a lot.

 Regards,

Sy

#176325
Edited, Mar 16, 2017 8:42
Vote:
 
#176332
Mar 16, 2017 9:50
Vote:
 

Hi Sy,

Have you got any special catalog in your site?

I tried to install service api in Quicksilver site and request this /episerverapi/commerce/catalogs, this is the result I got:

Request catalog info

If you did extend with your own implementation, I suggest that you could submit a support ticket to support team, send them your code for investigate, I think you will get better solution.

P/s: Sorry for late feedback for this thread.

/Son Do

#177506
Apr 13, 2017 11:13
Vote:
 

anyone, who checked out sourecoure of QuickSilver with latest version("QuickSilver release version 10.7.1" by Ba Luu on 6/6/2017) & install EPiServer.ServiceApi.Commerce then can get token successfully ? remember that checkout to have the new sourcecode & new site without any cache.

I tried to check out & install EPiServer.ServiceApi.Commerce Version 3.0.1 but can't get token by sourcecode testing as below:

client.BaseAddress = new Uri("https://mysite/");
                var fields = new Dictionary<string, string>
                {
                    { "grant_type", "password" },
                    { "username", "myuser" },
                    { "password", "mypassword" }
                };
                try
                {
                    var response = client.PostAsync("/episerverapi/token", new FormUrlEncodedContent(fields)).Result;
                    if (response.StatusCode == HttpStatusCode.OK)

{........}

StatusCode always return Badrequest.

remember to check out a new sourcecode & buid a new site, not pull to current sourcecode to avoid cache.

PS: of course I checked the ServiceApi installed successully by access https://mysite/EPiServerApi/version & https://mysite/EPiServerApi/Token from browser

Thanks

#179549
Edited, Jun 15, 2017 8:53
Vote:
 

When I had this problem was because I had ServiceApi installed at the same host. in Your case "https://mysite/", I created a new Host "https://serviceApi" and this I added the service API.

#179550
Jun 15, 2017 8:59
Vote:
 

haha,

I also tried many times as you did but not lucky as you :)

#179551
Jun 15, 2017 9:06
Vote:
 

This is still an issue with ServiceApi 5. (https://world.episerver.com/documentation/class-libraries/rest-apis/service-api/)

I consitently get those unauthorized messages from the service api. 

Anybody here with strong answer?

#255496
Edited, May 25, 2021 12:24
Vote:
 

Wow you resurrected an old thread Manoj. Might be worth starting a new thread.

#255624
May 26, 2021 23:07
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.