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

I am attempting to decouple my auth and resource server. I am following the example provided in this tutorial:

Decouple OWIN Authorization Server from Resource Server

This is the code in my Startup.cs in my auth server:

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AuthServer.Web
{
   public class xxxxx
   {
      public void Configuration(IAppBuilder app) {
         ConfigureOAuth(app);
      }

      public void ConfigureOAuth(IAppBuilder app)
      {
         OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
         {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
         };

         // Token Generation
         app.UseOAuthAuthorizationServer(OAuthServerOptions);
         app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

      }
   }
}

This is the startup.cs in my resource server (i.e. my sample Web api application):

using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AuthTestApi.Web
{
   public class Startup
   {
      public void Configuration(IAppBuilder app)
      {
         app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
         app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
      }      
   }
}

When I post the following request to the «token» endpoint of my auth server I sucessfully receive a token:

{
access_token: "PszrzJUtQUhX42GMryWjZiVHuKiJ9yCVH_1tZURumtC5mTj2tpuRDF3tXcN_VNIYuXY40IG0K7W3KASfJ9DlNIU2jMOkL2U5oEAXLNRRQuNYdEJ7dMPb14nW19JIaM4BMk00xfQ8MFRw0p6-uoh0-e-Q6iAiTwDNN3F7bYMF9qm874qhLWEcOt6dWQgwpdDUVPDi7F07-Ck0zAs48Dg5w4q93vDpFaQMrziJg9aaxN8",
token_type: "bearer",
expires_in: 86399
}

When I post the following request to my controller I receive the «Authorization has been denied for this request» error message?

GET /api/Test HTTP/1.1
Host: localhost:63305
Accept: application/json
Content-Type: application/json
Authorization: Bearer PszrzJUtQUhX42GMryWjZiVHuKiJ9yCVH_1tZURumtC5mTj2tpuRDF3tXcN_VNIYuXY40IG0K7W3KASfJ9DlNIU2jMOkL2U5oEAXLNRRQuNYdEJ7dMPb14nW19JIaM4BMk00xfQ8MFRw0p6-uoh0-e-Q6iAiTwDNN3F7bYMF9qm874qhLWEcOt6dWQgwpdDUVPDi7F07-Ck0zAs48Dg5w4q93vDpFaQMrziJg9aaxN8
Cache-Control: no-cache
Postman-Token: aeca8515-70b1-ef2c-f317-bf66136dccab

My auth server and resource / web api projects are in different solutions and are running on different ports (…not sure if that matters but thought Id mention it).

At this point these 2 projects are making use of oAuth OWIN middleware (and has very little custom code). The middleware is blackbox somewhat and just need some assistance in figuring out why I am receiving this error message.

Also note that the I am running both servers in two Visual Studio 2013 Web application projects that are in different VS 2013 solutions that are running on different ports. I am not sure if that matters but thought I would mention it.

Thanks in advance.

  • 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.

    Перейти к контенту

    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:homesitewwwrootnode_modules@azurems-rest-jsdistmsRest.node.js:1397:28)n    at D:homesitewwwrootnode_modules@azurems-rest-jsdistmsRest.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:homesitewwwrootnode_modules@azurems-rest-jsdistmsRest.node.js:1397:28)n    at D:homesitewwwrootnode_modules@azurems-rest-jsdistmsRest.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.

    • Ошибка audio system was not initialized correctly error code 0
    • Ошибка audio renderer error
    • Ошибка audi pre sense на ауди q7
    • Ошибка audi adaptive light на светодиодных фарах
    • Ошибка attempted write to readonly memory на windows 10 как исправить