Ошибка 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

8901 gold badge11 silver badges23 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

23.2k24 gold badges71 silver badges114 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,9383 gold badges19 silver badges45 bronze badges

answered Feb 22, 2018 at 14:03

K C Frank's user avatar

When developing an application, you may come across the error message «Authorization has been denied for this request.» This usually occurs when the user or the application does not have the necessary permissions to perform a specific action. In this guide, we will discuss the possible causes for this error and provide step-by-step solutions to help you resolve it.

Table of Contents

1) Possible Causes of the Error

2) Step-by-Step Solutions

  • Check API Key and Secret
  • Verify User Roles and Permissions
  • Inspect the Authentication Token
  • Check CORS Configuration

3) FAQ

Possible Causes of the Error

There are several reasons why you might encounter this error message. Some of the most common causes include:

  1. Invalid or expired API key and secret
  2. Incorrect user roles and permissions
  3. Malformed or expired authentication token
  4. Improper Cross-Origin Resource Sharing (CORS) configuration

Step-by-Step Solutions

1. Check API Key and Secret

One of the most common reasons for the «Authorization has been denied for this request» error is using an invalid or expired API key and secret. To resolve this issue:

  1. Verify that you are using the correct API key and secret provided by the service.
  2. Check if the API key and secret have expired or been revoked. If so, generate new ones.
  3. Update your application with the correct API key and secret and try the request again.

2. Verify User Roles and Permissions

Another possible cause for this error is that the user attempting to perform the action does not have the necessary permissions. To fix this issue:

  1. Review the user roles and permissions assigned to the account.
  2. Ensure that the user has the appropriate role to perform the action.
  3. If necessary, update the user’s role to grant them the required permissions.
  4. Retry the request with the updated user role.

3. Inspect the Authentication Token

A malformed or expired authentication token can also cause this error. To resolve this issue:

  1. Inspect the authentication token to ensure it has the correct format.
  2. Check if the token has expired. If so, request a new token and update your application.
  3. Verify that the token has the necessary claims for the request. If not, request a new token with the appropriate claims.
  4. Retry the request with the updated authentication token.

4. Check CORS Configuration

Improper Cross-Origin Resource Sharing (CORS) configuration can also lead to the «Authorization has been denied for this request» error. To fix this issue:

  1. Review your server’s CORS configuration to ensure it allows requests from your application’s domain.
  2. Update the CORS configuration if necessary to include your application’s domain.
  3. Ensure that your application sends the appropriate CORS headers with its requests.
  4. Retry the request after updating the CORS configuration.

FAQ

1. Can I bypass the «Authorization has been denied for this request» error?

Bypassing this error is not recommended, as it can lead to security vulnerabilities in your application. Instead, follow the steps outlined in this guide to resolve the issue properly.

2. Why am I receiving this error even though I have the correct API key and secret?

You may still encounter this error even with the correct API key and secret if there are other issues with the user’s permissions, the authentication token, or the CORS configuration. Follow the steps in this guide to check and resolve these issues.

3. How do I know if my authentication token has expired?

Authentication tokens typically include an expiration timestamp called «exp» in their payload. Inspect the token’s payload and compare the «exp» value to the current time to determine if the token has expired.

4. How can I prevent this error from occurring in the future?

To minimize the occurrence of this error, ensure that your application always uses valid API keys and secrets, properly manages user roles and permissions, and handles authentication tokens correctly. Additionally, make sure your server’s CORS configuration is set up correctly to allow requests from your application’s domain.

5. Should I use a different authentication method to avoid this error?

Switching authentication methods may not necessarily prevent this error, as it can occur due to various reasons, such as user permissions or CORS configuration. Instead, ensure that your application follows best practices for authentication and authorization, and follow the steps in this guide to resolve the issue.

Related: Understanding Authentication and Authorization
Related: Configuring CORS in Your Application

  • Remove From My Forums
  • Question

  • I have a simple ASP.Net web application consist of .aspx web from hosted on azure as cloud service. In my application there is no user login.
    I want to connect with Microsoft Graph API and and to use Microsoft Bookings API to get the BookingBusiness collection on my home page load without user login. I am currently debugging my web app on my desktop using Azure emulator.
    I have the ofiice 365 premium account access assoiciated with my microsoft account (XXXXX@microsoft.com) and I had created a Booking business using my v- alias through Booking tools (https://outlook.office.com/owa/?path=/bookings).
    I registered an app in AAD in the same tenant with all required permission and provided the Cliend Id and secret in the code to get the access token. I am using Client credentials Grant flow to get the access token and try to invoke the booking API.
    I am able to get the access token, but when the code try to get the the list of booking businesses it is giving below exception.

    DataServiceClientException: {
      «error»: {
        «code»: «»,
        «message»: «Authorization has been denied for this request.»,
        «innerError»: {
          «request-id»: «d0ac6470-9aae-4cc2-9bf3-ac83e700fd6a»,
          «date»: «2018-09-03T08:38:29»
        }
      }
    }

    The code and registered app setting details are in below screen shot.

            private static async Task<AuthenticationResult> AcquireToken()
            {
                var tenant = "microsoft.onmicrosoft.com"; //"yourtenant.onmicrosoft.com";
                var resource = "https://graph.microsoft.com/";
                var instance = "https://login.microsoftonline.com/";
                var clientID = "7389d0b8-1611-4ef9-a01f-eba4c59a6427";
                var secret = "mxbPBS10|[#!mangJHQF791";
                var authority = $"{instance}{tenant}";
                var authContext = new AuthenticationContext(authority);
                var credentials = new ClientCredential(clientID, secret);           
    
                var authResult = await authContext.AcquireTokenAsync(resource, credentials);
                
                return authResult;
            }
    
    
            protected void MSBooking()
            {               
                var authenticationContext = new AuthenticationContext(GraphService.DefaultAadInstance, TokenCache.DefaultShared);
                var authenticationResult =  AcquireToken().Result;
    
                          
    	    var graphService = new GraphService(
                GraphService.ServiceRoot,
                () => authenticationResult.CreateAuthorizationHeader());
    
               // Get the list of booking businesses that the logged on user can see.
                
                var bookingBusinesses = graphService.BookingBusinesses; ----- this line throwing an exception "Authorization has                                been denied for this request."
            }

    GraphService.cs

    // ---------------------------------------------------------------------------
    // <copyright file="GraphService.cs" company="Microsoft">
    //     Copyright (c) Microsoft Corporation.  All rights reserved.
    // </copyright>
    // ---------------------------------------------------------------------------
    
    namespace Microsoft.Bookings.Client
    {
        using System;
        using System.Net;
    
        using Microsoft.OData;
        using Microsoft.OData.Client;
    
        public partial class GraphService
        {
            /// <summary>
            /// The resource identifier for the Graph API.
            /// </summary>
            public const string ResourceId = "https://graph.microsoft.com/";
    
            /// <summary>
            /// The default AAD instance to use when authenticating.
            /// </summary>
            public const string DefaultAadInstance = "https://login.microsoftonline.com/common/";
    
            /// <summary>
            /// The default v1 service root
            /// </summary>
            public static readonly Uri ServiceRoot = new Uri("https://graph.microsoft.com/beta/");
    
            /// <summary>
            /// Initializes a new instance of the <see cref="BookingsContainer"/> class.
            /// </summary>
            /// <param name="serviceRoot">The service root.</param>
            /// <param name="getAuthenticationHeader">A delegate that returns the authentication header to use in each request.</param>
            public GraphService(Uri serviceRoot, Func<string> getAuthenticationHeader)
                : this(serviceRoot)
            {
                this.BuildingRequest += (s, e) => e.Headers.Add("Authorization", getAuthenticationHeader());
            }
    
            /// <summary>
            /// Gets or sets the odata.maxpagesize preference header.
            /// </summary>
            /// <remarks>
            /// Using the Prefer header we can control the resulting page size of certain operations,
            /// in particular of GET bookingBusinesses(id)/appointments and bookingBusinesses(id)/customers.
            /// </remarks>
            public int? MaxPageSize
            {
                get;
                set;
            } = null;
    
            /// <summary>
            /// Gets or sets the odata.continue-on-error preference header.
            /// </summary>
            /// <remarks>
            /// Using the Prefer header we can control if batch operations stop or continue on error.
            /// </remarks>
            public bool ContinueOnError
            {
                get;
                set;
            }
    
            /// <summary>
            /// Gets or sets the web proxy to use when sending requests.
            /// </summary>
            public IWebProxy WebProxy
            {
                get;
                set;
            }
    
            partial void OnContextCreated()
            {
                // Default to send only the properties that were set on a data object
                this.EntityParameterSendOption = EntityParameterSendOption.SendOnlySetProperties;
    
                // Allows new results to override cached results, if the object is not changed.
                this.MergeOption = MergeOption.PreserveChanges;
    
                if (this.BaseUri.AbsoluteUri[this.BaseUri.AbsoluteUri.Length - 1] != '/')
                {
                    throw new ArgumentException("BaseUri must end with '/'");
                }
    
                this.BuildingRequest += (s, e) => e.Headers.Add("client-request-id", Guid.NewGuid().ToString());
    
                this.SendingRequest2 += (s, e) =>
                    {
                        var requestMessage = e.RequestMessage as HttpWebRequestMessage;
                        if (requestMessage != null)
                        {
                            var preferenceHeader = new ODataRequestOnHttpWebRequest(requestMessage.HttpWebRequest).PreferHeader();
                            preferenceHeader.MaxPageSize = this.MaxPageSize;
                            preferenceHeader.ContinueOnError = this.ContinueOnError;
    
                            requestMessage.HttpWebRequest.Proxy = this.WebProxy;
                        }
                    };
            }
        }
    }

    • Edited by

      Monday, September 3, 2018 3:38 PM
      Edited PII Data

Good evening, community experts.

I was integrating my application with Skype using the REST API (Bot Framework). Everything worked perfectly until today.
In the morning, while checking the functionality of the application, I noticed that the bot’s response did not displayed in Skype. I decided to send a message through «Postman», and I received the following response:

{
    "message": "Authorization has been denied for this request."
}

I thought there might be a problem with token. Through the request below, I got a new one, but it didn’t help:

curl -k -X POST https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token -d "grant_type=client_credentials&client_id=<APP ID>&client_secret=<APP PASWORD>&scope=https%3A%2F%2Fapi.botframework.com%2F.default"

Here are my «Postman» POST HTTPS query settings:

URL:
https://smba.trafficmanager.net/apis/v3/conversations/<CONVERSATION ID>/activities/<MESSAGE ID>

HEADERS:
Postman-Token: <calculated when request is sent>
Content-Lenght: <calculated when request is sent>
Host: <calculated when request is sent>
Content-Type: application/json
Authorization: Bearer 0SzRndyIsImtpZCI6ImppYk5ia0ZTU2JteFBZck45Q0...

BODY:
{
    "type": "message",
    "from": {
        "id": <BOT ID>,
        "name": <BOT NAME>
    },
   "recipient": {
        "id": <USER ID>,
        "name": <USER NAME>
    },
    "text": <MESSAGE>
}

Please tell me what the problem might be? Everything worked fine yesterday! Could there be a problem with the SSL certificate? Or should the Authorization parameter be passed in some other way? Thank you in advance!

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.

    Понравилась статья? Поделить с друзьями:
  • Ошибка b1346 hyundai santa fe
  • Ошибка authenticate decrypt packet error packet hmac authentication failed
  • Ошибка b1342 форд мондео 3
  • Ошибка auth a10 в личном кабинете мегафон
  • Ошибка b1325 опель астра j