Меню

Ошибка authorization has been denied for this request

I just created new Web API project (using MVC) in visual studio 2015 and for the testing purpose, I ran that project but ended up below error.

After running the project, it brings up Home Page correctly but when I navigated to /api/values or /api/values/5, it gives me below xml message.

<Error>
    <Message>Authorization has been denied for this request.</Message>
</Error>

Can someone please help? I am new to Web API.
Please note that I don’t want to remove the Authorize attribute. I would like to access the resource after authorization only. So I am looking for what is wrong.

asked Aug 15, 2016 at 21:36

atp9's user avatar

atp9atp9

8801 gold badge11 silver badges22 bronze badges

0

In the ValuesController there is an attribute Authorize if you remove it, then it will work as home page.

The Authorize attribute just prevent an anonymous users from accessing the ValuesController.

to work with this attribute, you need first to register a user, and then login to get user’s token, then you can use the token to authorize your self and get access .

In this page Individual-accounts-in-web-api is explained all what do you need

answered Aug 15, 2016 at 22:23

Tarek Abo ELkheir's user avatar

0

It happens because you have an Authorize attribute on your ValuesController

[Authorize]
public class ValuesController : ApiController

Just remove [Authorize] and try again

EDIT

According to your edit: You should create a new user and login or use [AllowAnonymous] as mentioned by @Marcus H. Read more about Identity

answered Aug 15, 2016 at 21:47

Roman Marusyk's user avatar

Roman MarusykRoman Marusyk

22.6k24 gold badges69 silver badges112 bronze badges

0

I got the answer here.

https://stackoverflow.com/a/29405794/8107314

And it was very useful to fix my error my error

I just came across the same problem and found the solution:

You need to register the OAuth Token Generator and OAuth Token Consumer things before WebAPI is registered.

Kind of makes sense if you think of this as a pipeline, where Authentication/Authorization should come before any request handling by the controllers.

TL;DR: Change

appBuilder.UseWebApi(config);

this.ConfigureOAuthTokenGenerator(appBuilder);
this.ConfigureOAuthConsumer(appBuilder);

To

this.ConfigureOAuthTokenGenerator(appBuilder);
this.ConfigureOAuthConsumer(appBuilder);

appBuilder.UseWebApi(config);

Beakie's user avatar

Beakie

1,9382 gold badges19 silver badges45 bronze badges

answered Feb 22, 2018 at 14:03

K C Frank's user avatar

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

dupuis2387 opened this issue

Feb 4, 2020

· 19 comments

Assignees

@mdrichardson

Comments

@dupuis2387

i’m using the nodejs version of «botbuilder»: «~4.5.1»
and I’m still encountering issues with «Error: Authorization has been denied for this request» even after having
MicrosoftAppCredentials.trustServiceUrl('https://smba.trafficmanager.net/apis/', new Date(8640000000000000));
in my code.

It randomly happens and without doing anything, it’ll resume being able to communicate with the person that I’ve <SNIP>’d out.

FWIW, this bot is hosted in Azure under an app service instance, and has «Always On» already on.
If a timestamp would help troubleshoot if there was a fluke with some service bot/skype outage, it just happened on Mon 2/3/2020 3:59 PM EST

{
   "stack": "Error: Authorization has been denied for this request.n    at new RestError (D:\home\site\wwwroot\node_modules\@azure\ms-rest-js\dist\msRest.node.js:1397:28)n    at D:\home\site\wwwroot\node_modules\@azure\ms-rest-js\dist\msRest.node.js:1849:37n    at process._tickCallback (internal/process/next_tick.js:68:7)",
   "message": "Authorization has been denied for this request.",
   "statusCode": 401,
   "request": {
      "body": {
         "type": "message",
         "serviceUrl": "https://smba.trafficmanager.net/apis/",
         "channelId": "skype",
         "from": {
            "id": "<SNIP>",
            "name": "<SNIP>"
         },
         "conversation": {
            "id": "<SNIP>"
         },
         "recipient": {
            "id": "<SNIP>",
            "name": "<SNIP>"
         },
         "text": "The message that the bot was trying to send to the recipient.",
         "inputHint": "acceptingInput",
         "replyToId": "<SNIP>"
      }
   },
   "response": {
      "body": {
         "message": "Authorization has been denied for this request."
      }
   },
   "body": {
      "message": "Authorization has been denied for this request."
   }
}

@mdrichardson

@dupuis2387 Can you provide a conversation ID that this has occurred on? At the very least, I’ll need an AppId or bot name to look into this further.

Where in your code are you calling trustServiceUrl()? So long as it’s called prior to the bot sending a message to that serviceUrl (even after a bot restart), it should be fine.

@dupuis2387

sure…here we are (i thought divulging that would be sensitive information):

{
   "stack": "Error: Authorization has been denied for this request.n    at new RestError (D:\home\site\wwwroot\node_modules\@azure\ms-rest-js\dist\msRest.node.js:1397:28)n    at D:\home\site\wwwroot\node_modules\@azure\ms-rest-js\dist\msRest.node.js:1849:37n    at process._tickCallback (internal/process/next_tick.js:68:7)",
   "message": "Authorization has been denied for this request.",
   "statusCode": 401,
   "request": {
      "body": {
         "type": "message",
         "serviceUrl": "https://smba.trafficmanager.net/apis/",
         "channelId": "skype",
         "from": {
            "id": "28:e7e117fc-904e-4782-af12-dceafb4e9ac0",
            "name": "NRS VIDEO RELAY SERVICE"
         },
         "conversation": {
            "id": "29:1zNwNjv0VsMmllDwoj8tbyE_c_9JawLJZtToLNeskZeJ5z8swuX0MDZIBu9X8Ok-b"
         },
         "recipient": {
            "id": "29:1zNwNjv0VsMmllDwoj8tbyE_c_9JawLJZtToLNeskZeJ5z8swuX0MDZIBu9X8Ok-b",
            "name": "NRS VRSTERP10"
         },
         "text": "<SNIP>",
         "inputHint": "acceptingInput",
         "replyToId": "1580763518872"
      }
   },
   "response": {
      "body": {
         "message": "Authorization has been denied for this request."
      }
   },
   "body": {
      "message": "Authorization has been denied for this request."
   }
} 

and im calling MicrosoftAppCredentials.trustServiceUrl right inside my index.js file, after creating the adapter and setting up some event handlers:

const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppId,
    appPassword: process.env.MicrosoftAppPassword,
});


adapter.use(async (turnContext, next) => {

    .....
    turnContext.onSendActivities(async (ctx, activities, nextSend) => {
        // Deliver activities
        await nextSend();

        .....
     });

    await next();

    ....

});


// Catch-all for errors.
adapter.onTurnError = async (context, error) => {

    ....

};


MicrosoftAppCredentials.trustServiceUrl('https://smba.trafficmanager.net/apis/', new Date(8640000000000000));



@mdrichardson

@dupuis2387 I’ll start looking into this. As far as sensitive info, the bot name or appId is fine—it’s just passwords, mostly that you need to keep private.

Placement is fine. Are you sure that’s the right serviceUrl for every message? I don’t recall what Skype does, but Teams has several different serviceUrls.

@dupuis2387

@mdrichardson so per the provided Microsoft samples, to continue a conversation, we’re meant to keep a json payload from a conversation interaction that looks like


{
    "activityId": "1572800137595",
    "bot": {
        "id": "28:e7e117fc-904e-4782-af12-dceafb4e9ac0",
        "name": "NRS VIDEO RELAY SERVICE"
    },
    "channelId": "skype",
    "conversation": {
        "id": "29:1qM0tG1lMQtJQAGw1E4iR9KpzvSnYbiA1w2HkIctUBBM"
    },
    "serviceUrl": "https://smba.trafficmanager.net/apis/",
    "user": {
        "id": "29:1qM0tG1lMQtJQAGw1E4iR9KpzvSnYbiA1w2HkIctUBBM",
        "name": "Alex"
    }
}

Every instance of every contact that we’ve accrued and saved the payload thereof, has only every had the above service url. And all we care about is just communication on the skype channel (not skype for business, teams, or really anything else).

However, i do not definitively know; i dont know of any place that lists all serviceUrls you’re meant to trust in regards to skype…..but given that the error recorded in my original post, has https://smba.trafficmanager.net/apis/ as the api url, im imagining that that rules out other potential serviceUrls not being trusted, but I could be wrong.

@mdrichardson

The best way to ensure this works, even if an API is changed, is right before the bot sends a message to the user, call trustServiceUrl(turnContext.activity.serviceUrl, <expiration>). Again, still looking into the specifics, though.

@mdrichardson

@dupuis2387 I forgot that we can’t check Skype bots via ConversationId. Can you provide the bot’s name (the name of the App Registration in Azure)?

@dupuis2387

@mdrichardson

@dupuis2387 I’m not able to find it by that name on the backed. What is it listed as in App Registrations? If it’s the same, what is it listed in the Web App Bot or Bot Channels Registration in the Azure Portal?

@dupuis2387

The bot channels registration is CnxNrsAlphaDeployment

@mdrichardson

@dupuis2387 Got it. Any chance your bot has >100 users?

@dupuis2387

Yes, since it «went live», there’s been a total of 371 individual people that have communicated with it

@mdrichardson

@dupuis2387 That’s likely your problem. If you open your Web App Bot/Bot Channels Registration in the Azure Portal, click Channels, then click «edit» by Skype:

image

If you haven’t re-published it recently, you might be okay. I’m currently not seeing any issues on the backend, though — Skype handles most of the communication, so there’s not a ton that we can look into.

@dupuis2387

Yep, so I got it in before the deadline , and it was approved, literally the day of, in October, as confirmed by a Microsoft support engineer. Also, I’ve not republished since. Anything else it could be?

@mdrichardson

@dupuis2387 I see.

  1. Is this an intermittent problem, still, or was it only really happening on Monday?
  2. If still occuring can you try adding trustServiceUrl(turnContext.activity.serviceUrl, <expiration>) at the top of onMessage() and let me know if the problem still occurs?

@dupuis2387

It’s been happening on and off probably since it went live in October. I have recorded instances on 12/4, 1/3, 1/10, and 1/16, all across different contacts/activities. But, let me go ahead and try your suggested code change, and see if it persists. Thank you, for looking at this.

@mdrichardson

@dupuis2387 Sounds good. Did you change your Bot ID recently? I can’t seem to find any logs on our end older than a couple of days. Might be a Skype thing, though, now that it’s deprecated.

Also, I checked those dates to see if other customers in your region were reporting issues and couldn’t find anything. Does’t appear to have been widespread enough to diagnose as a service issue, at this point.

@mdrichardson

@dupuis2387 How’s this going? If it’s still occuring, can you include any console logs?

@dupuis2387

The code change went into production 48hrs ago. However, I can’t say it’s 100% fixed the issue yet, given how random it is, when it pops up.
Should I close for now and re-open it again, later, if it re-manifests?

Edit: sorry, i hit the wrong button (accidentally hit close instead of comment).

@mdrichardson

@dupuis2387 We can close for now. If it pops up again, please get timestamps as accurate as possible along with any logs you can share.

nt-7

pushed a commit
to nt-7/bot-docs
that referenced
this issue

Nov 27, 2021

@DanDev33

@ivorb

nt-7

pushed a commit
to nt-7/bot-docs
that referenced
this issue

Nov 27, 2021

@Kaiqb

When using an API that required Access Approval or is Private, I sometimes get the error message that of "message": "Authorization has been denied for this request.". How do you fix that?

Many of the APIs that require Access Approval or are Private require secondary authentication information. This is usually a Basic Authorization Header (a base64 encoded ucsbNetId:password combination) which will be used by the backend system to authenticate who or what application is calling into the API service. As a client you would be aware if a system required secondary authentication information, as you would be asked to provide a UcsbNetId when applying for access.

When the service is called, if the UcsbNetId/Password combination can’t be authenticated successfully, or the UcsbNetId hasn’t been authorized to access the API a common error message of "message": "Authorization has been denied for this request." may be replied.

Some common mistakes that lead to this error message are:

  • Not including a Basic Authorization Header.
  • Forgetting to base64 encode the ucsbNetId:password combination.
  • The API provider hasn’t added your ucsbNetId to the authorization systems.

If you are sure you’re doing the first two above, please reach out to support@developer.ucsb.edu to see if your application’s ucsbNetId can be added.

    • Remove From My Forums
    • Question

    • User-111502429 posted

      So i made a login with google button, when i click it i get the access token successfully using this 

      /// <reference path="jquery-3.4.1.min.js" />
      function getAccessToken()
      {
          debugger;
          if (location.hash) {
              if (location.hash.split('access_token=')) {
                  var accessToken = location.hash.split('access_token=')[1].split('&')[0];
                  if (accessToken)
                  {
                      isUserRegistered(accessToken);
                  }
              }
          }
      }
      
      function isUserRegistered(accessToken)
      {
          $.ajax({
              url: '/api/Account/UserInfo',
              method: 'GET',
                  headers:
                  {
                  'content-type': 'application/JSON',
                  'Authorization': 'Bearer ' + accessToken
                  },
              success: function (response)
              {
                  debugger;
                  if (response.HasRegistered)
                  {
                      debugger;
                      localStorage.setItem('accessToken', accessToken);
                      localStorage.setItem('userName', response.Email);
                      window.location.href = "/api/TestController";
                  }
                  else
                  {
                      signupExternalUser(accessToken);
                  }
              }
              });
      
          function signupExternalUser(accessToken)
          {
              $.ajax({
                  url: '/api/Account/RegisterExternal',
                  method: 'POST',
                  headers: {
                      'content-type': 'application/json',
                      'Authorization': 'Bearer ' + accessToken
                  },
                  success: function () {
                      debugger;
                      window.location.href = "/api/Account/ExternalLogin?provider=Google&response_type=token&client_id=self&redirect_uri=";  //here the uri is filled but i removed it for now
                  }
              });
      
          }
      
      }

      as u can see in the code i said that after successfull login i want it to redirect me api/TestController  but i get «Authorization has been denied for this request»  why is that??

      Here is my startup.Auth

          public partial class Startup
          {
              public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
      
              public static string PublicClientId { get; private set; }
      
              // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
              public void ConfigureAuth(IAppBuilder app)
              {
                  // Configure the db context and user manager to use a single instance per request
                  app.CreatePerOwinContext(ApplicationDbContext.Create);
                  app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
      
                  // Enable the application to use a cookie to store information for the signed in user
                  // and to use a cookie to temporarily store information about a user logging in with a third party login provider
                  app.UseCookieAuthentication(new CookieAuthenticationOptions());
                  app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
      
                  // Configure the application for OAuth based flow
                  PublicClientId = "self";
                  OAuthOptions = new OAuthAuthorizationServerOptions
                  {
                      TokenEndpointPath = new PathString("/Token"),
                      Provider = new ApplicationOAuthProvider(PublicClientId),
                      AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                      AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                      // In production mode set AllowInsecureHttp = false
                      AllowInsecureHttp = true
                  };
      
                  // Enable the application to use bearer tokens to authenticate users
                  app.UseOAuthBearerTokens(OAuthOptions);
      
                  // Uncomment the following lines to enable logging in with third party login providers
                  //app.UseMicrosoftAccountAuthentication(
                  //    clientId: "",
                  //    clientSecret: "");
      
                  //app.UseTwitterAuthentication(
                  //    consumerKey: "",
                  //    consumerSecret: "");
      
                  //app.UseFacebookAuthentication(
                  //    appId: "",
                  //    appSecret: "");
      
                  app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
                  {
                      ClientId = "fsdfsfs", // consider them filled correctly
                      ClientSecret = "fsdfdsfsf" // consider them filled correctly
                  });
              }
          }
      
      

      And here is my statup.cs

          public partial class Startup
          {
              public void Configuration(IAppBuilder app)
              {
                  ConfigureAuth(app);
              }
          }
      

    I was creating an ASP.NET Web API today and when I called one of the Web APIs (/api/values) I got the following response:

    {“Message”:”Authorization has been denied for this request.”}

    It turns out by default ‘Individual User Accounts” authentication is enabled by default.  See Figure 1.

    image

    Figure 1, {“Message”:”Authorization has been denied for this request.”} ASP.NET Web API always default

    So what I did was change that to “No Authentication” and I got my testing project up and running real quick, See Figure 2.

    image

    Figure 2, {“Message”:”Authorization has been denied for this request.”} ASP.NET Web API always default, No Authentication

    The result were then as expected.  Sure I could have enabled some authentication, but just wanted to do some performance testing real fast and nothing else.

    This site runs basic WordPress, there is no code I wrote specifically that stores cookies or uses cookies. The site renders ads and captures usage analytics which may result in cookies. By clicking “OK” or by accessing content on this site, you consent to the use of all cookies.

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка asio sys windows 10
  • Ошибка authentication method 10 not supported