简体   繁体   English

我收到“此请求的授权已被拒绝”。 使用 OWIN oAuth 中间件时的错误消息(具有单独的身份验证和资源服务器)

[英]I get “Authorization has been denied for this request.” error message when using OWIN oAuth middleware (with separate Auth and Resource Server)

I am attempting to decouple my auth and resource server.我正在尝试分离我的身份验证和资源服务器。 I am following the example provided in this tutorial:我正在遵循本教程中提供的示例:

http://bitoftech.net/2014/09/24/decouple-owin-authorization-server-resource-server-oauth-2-0-web-api/ http://bitoftech.net/2014/09/24/decouple-owin-authorization-server-resource-server-oauth-2-0-web-api/

This is the code in my Startup.cs in my auth server:这是我的身份验证服务器中 Startup.cs 中的代码:

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 (ie my sample Web api application):这是我的资源服务器(即我的示例 Web api 应用程序)中的 startup.cs:

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:当我将以下请求发布到我的身份验证服务器的“\\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).我的身份验证服务器和资源/Web api 项目在不同的解决方案中,并且在不同的端口上运行(......不确定这是否重要,但我认为我提到了它)。

At this point these 2 projects are making use of oAuth OWIN middleware (and has very little custom code).此时,这两个项目正在使用 oAuth OWIN 中间件(并且几乎没有自定义代码)。 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.另请注意,我在两个 Visual Studio 2013 Web 应用程序项目中运行两台服务器,这些项目位于在不同端口上运行的不同 VS 2013 解决方案中。 I am not sure if that matters but thought I would mention it.我不确定这是否重要,但我想我会提到它。

Thanks in advance.提前致谢。

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.在注册 WebAPI之前,您需要注册 OAuth Token Generator 和 OAuth Token Consumer 东西。

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 TL;DR:改变

appBuilder.UseWebApi(config);

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

To

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

appBuilder.UseWebApi(config);

I was also receiving the error message 'Authorization has been denied for this request', although I don't have separate auth and resource servers.我还收到错误消息“此请求的授权已被拒绝”,尽管我没有单独的身份验证和资源服务器。

I am using Ninject's OwinHost and had it configured in Startup before configuring OAuth, as follows:我正在使用 Ninject 的 OwinHost 并在配置 OAuth 之前在启动中配置它,如下所示:

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();

    app.UseNinjectMiddleware(() =>
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }).UseNinjectWebApi(config);

    ConfigureOAuth(app);

    WebApiConfig.Register(config);
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(config);
}

I found that moving the Ninject configuration to the end resolved the problem, like so:我发现将 Ninject 配置移到最后解决了问题,如下所示:

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();

    ConfigureOAuth(app);

    WebApiConfig.Register(config);
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(config);

    app.UseNinjectMiddleware(() =>
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }).UseNinjectWebApi(config);
}

Maybe your problem is to do with the startup order of your middleware.也许您的问题与中间件的启动顺序有关。

In my post I was clear that you need to override the machineKey node for both APIs (Authorization Server and Resource Server) and share the same machineKey between both web.config files.在我的帖子中,我很清楚您需要覆盖两个 API(授权服务器和资源服务器)的 machineKey 节点,并在两个 web.config 文件之间共享相同的 machineKey。 How do you host those 2 different projects?你如何主持这两个不同的项目? they are on the same machine or different machines?他们在同一台机器上还是不同的机器上? Please go back to step 5 from the post and check how you can achieve this.请返回帖子中的第 5 步并检查如何实现此目的。

在过去的几天里,我遇到了完全相同的问题,尽管我将两个应用程序托管在同一台机器上(不同的端口),但是如果不添加机器密钥两个 web.config 文件确保相同的包版本,它就无法工作安装在两个应用程序中的数量

For me, the problem was a mismatched version number in Owin packeges:对我来说,问题是 Owin 包中的版本号不匹配:

 <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>

After updating the required older packages, everything worked like a charm.更新所需的旧包后,一切都像魅力一样。 :) :)

June 6 2018 update - using the latest WebAPI and OWIN packages. 2018 年 6 月 6 日更新- 使用最新的 WebAPI 和 OWIN 包。 I've been banging my head against this problem for more than I would like to admit.我一直在用我的头来解决这个问题,这比我想承认的要多。 None of the above suggestions worked for me, things suddenly started working once I added a certain project dependency that I wasn't even using in my code: the Microsoft.Owin.Host.SystemWeb NuGet package .上述建议都不适合我,一旦我添加了一个我什至没有在我的代码中使用的项目依赖项事情就会突然开始工作Microsoft.Owin.Host.SystemWeb NuGet 包 This setup is way too finicky and black-boxed for my taste, I don't know why it works like this, but here's what I did.这个设置对我来说太挑剔和黑盒了,我不知道为什么它会这样工作,但这就是我所做的。

The minimal setup that I needed for the resource service (the authentication/token service was already setup):我需要的资源服务的最小设置(身份验证/令牌服务已经设置):

  • add references to Microsoft.Owin.Security.Oauth and Microsoft.Owin.Host.SystemWeb添加对Microsoft.Owin.Security.OauthMicrosoft.Owin.Host.SystemWeb引用
  • create a startup.cs file with the following content:创建一个包含以下内容的 startup.cs 文件:

     using Microsoft.Owin; using Owin; using Microsoft.Owin.Security.OAuth; [assembly: OwinStartup(typeof(MyProject.Startup))] namespace MyProject { public class Startup { public void Configuration(IAppBuilder app) { app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions{ }); } } }
  • Add the following to your Web.config file in the <appSettings> section将以下内容添加到<appSettings>部分的Web.config文件中

<add key="owin:appStartup" value="MyProject.Startup" />

In your OwinStartup class, IAppBuilder.UseOAuthBearerTokens() needs to be called BEFORE IAppBuilder.UseWebApi()在您的 OwinStartup 类中,需要在 IAppBuilder.UseWebApi() 之前调用 IAppBuilder.UseOAuthBearerTokens()

public void Configuration(IAppBuilder app)
{
    app.UseOAuthBearerTokens(...);
    app.UseWebApi(...);
}

Running web applications in IIS with different pool you'll get different keys.在具有不同池的 IIS 中运行 Web 应用程序,您将获得不同的密钥。 So, you should run auth and resource applications with the same application pool.因此,您应该使用相同的应用程序池运行身份验证和资源应用程序。 Check this https://gyorgybalassy.wordpress.com/2013/12/07/how-unique-is-your-machine-key/检查这个https://gyorgybalassy.wordpress.com/2013/12/07/how-unique-is-your-machine-key/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 此请求已被拒绝授权。 总是 - Authorization has been denied for this request. Always 此请求的授权已被拒绝。 邮差 - Authorization has been denied for this request. Postman 在 MVC 项目中运行 webapi 时,此请求错误的授权已被拒绝 - Authorization has been denied for this request error when running webapi in MVC project 此请求的授权已被拒绝:JWT承载 - Authorization has been denied for this request : JWT Bearer IdentityServer3 .Net Web API。 收到错误-该请求的授权被拒绝 - IdentityServer3 .Net Web API. Getting error - Authorization has been denied for this request 仅在生产环境中“对此请求的授权被拒绝” - “Authorization has been denied for this request” in production environment only 验证使用OWIN身份验证中间件的项目中的用户 - Validate user in project that is using OWIN auth middleware 如何忽略Identity Framework魔法并使用OWIN auth中间件来获取我寻求的声明? - How do I ignore the Identity Framework magic and just use the OWIN auth middleware to get the claims I seek? 当我向Quickbooks添加新客户时,“远程服务器返回错误:(400)错误的请求。” - “remote server returned an error: (400) Bad Request.” when I am adding new Customer to Quickbooks.. 处理您的请求时发生错误。 尝试登录我的应用程序时出现此错误 - An error occurred while processing your request. I get this error when trying to log in to my application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM