使用Bearer令牌OATH OWIN授权API

时间:2018-06-27 19:06:42

标签: asp.net-mvc-4 asp.net-web-api owin identityserver3 bearer-token

我在使用外部IdenityServer在API中获取承载令牌时遇到问题。我已经进行了研究,但似乎找不到真正相似的例子。我使用的API要求我对应用程序“服务令牌”进行身份验证,然后获取“用户令牌”。我似乎无法获得该服务的Bearer令牌。

Startup.cs

using Microsoft.Owin;
using Owin;
using TEST;

[assembly: OwinStartup(typeof(Startup))]
namespace TEST
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Startup.Auth.cs

using IdentityServer3.AccessTokenValidation;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System.Configuration;
using System.Web.Http;

namespace TEST
{
    public partial class Startup
    {
        private static readonly string ApiUrl = ConfigurationManager.AppSettings["ApiUrl"];
        private static readonly string ApiScope = ConfigurationManager.AppSettings["ApiScope"];

        public void ConfigureAuth(IAppBuilder app)
        {
            app.Map("/api", inner =>
                {
                    // Web API configuration and services
                    var config = new HttpConfiguration();

                    inner.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                    {
                        Authority = ApiUrl,
                        ValidationMode = ValidationMode.ValidationEndpoint,
                        RequiredScopes = new[] { ApiScope },
                        DelayLoadMetadata = true,
                        PreserveAccessToken = true
                    });

                    config.SuppressDefaultHostAuthentication();
                    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
                    config.Routes.MapHttpRoute(
                                               name: "DefaultApi",
                                               routeTemplate: "{controller}/{id}",
                                               defaults: new { id = RouteParameter.Optional }
                                              );

                     config.MapHttpAttributeRoutes();
                   // WebAPI when dealing with JSON & JavaScript!
                    // Setup json serialization to serialize classes to camel (std. Json format)
                    config.Formatters.Remove(config.Formatters.XmlFormatter);
                    var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
                    formatter.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();


                    inner.UseWebApi(config);
                });
        }
    }
}

TestController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Web;
using System.Web.Http;
using Microsoft.Owin.Security;
using Newtonsoft.Json;

namespace TEST.Controllers
{
    public class TestController : ApiController
    {
        [Authorize]
        public dynamic Get()
        {
            var user = User as ClaimsPrincipal;
            var claims2 = from c in user.Claims
                         select new
                                    {
                                        type = c.Type,
                                        value = c.Value
                                    };
        }
    }
}

web.config进行了更改:

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  <appSettings>
    <add key="owin:AutomaticAppStartup" value="true" />
    <add key="owin:appStartup" value="TEST.Startup, TEST" />
    <add key="ClientId" value="TestUser" />
    <add key="ClientSecret" value="3db2c7d7-410e-429b-96dc-06c870279144" />
    <add key="ApiUrl" value="https://test.example.com:5000" />
    <add key="ApiScope" value="TestScope" />
  </appSettings>
  <system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <authentication mode="None" />
  </system.web>

我已经阅读了threadthis,但没有运气。我正在添加了Web API的MVC4应用程序中工作。我以为表单身份验证会引起问题,因此为什么要在web.config中将其删除。当我按下控制器并用[Authorize]属性装饰时,我得到一个

的响应。
{"Message":"Authorization has been denied for this request."}

如果我击中没有[Authorize]属性的控制器,它将起作用,但是不存在Bearer令牌。我一直在使用Fiddler和Wireshark,但从未看到对IdentityServer的请求。如果我使用邮递员,则可以获取Bearer令牌,然后看到对IdentityServer的请求。 IdentityServer不受我的控制。

我看了很多例子,并回顾了IdentityServer的例子。如果可以给出有关如何记录/调试的一些指示,那将与解决方案一样有用。

0 个答案:

没有答案