使用身份服务器 3 设置机器到机器(控制台到 Web API)授权

Setup machine to machine (Console to WebAPI) authorization with identity server3

我正在尝试使用 identityserver3 作为授权服务来设置从控制台应用程序到 WebAPI 端点的授权。这不是自托管的 API,它将面向 public。我试图按照身份服务器上的文档进行操作,并且我独立拥有 API 运行 和 IdentityServer 运行。我遇到问题的地方是获取 api 路由来检查授权和 request/receive 来自身份服务器的访问令牌。

在身份服务器中,我将 startup.cs 文件定义为:

public void Configuration(IAppBuilder app)
            {
                app.Map("/identity", idsrvApp =>
                {
                    var corsPolicyService = new DefaultCorsPolicyService()
                    {
                        AllowAll = true
                    };

                    var defaultViewServiceOptions = new DefaultViewServiceOptions();
                    defaultViewServiceOptions.CacheViews = false;

                    var idServerServiceFactory = new IdentityServerServiceFactory()
                        .UseInMemoryClients(Clients.Get())
                        .UseInMemoryScopes(Scopes.Get())  
                        .UseInMemoryUsers(Users.Get());   

                    idServerServiceFactory.CorsPolicyService = new
                        Registration<IdentityServer3.Core.Services.ICorsPolicyService>(corsPolicyService);

                    idServerServiceFactory.ConfigureDefaultViewService(defaultViewServiceOptions);

                    var options = new IdentityServerOptions
                    {
                        Factory = idServerServiceFactory,
                        SiteName = "Sumbission Security Token Service",
                        SigningCertificate = LoadCertificate(),
                        IssuerUri = "https://samplesubmission/identity",
                        PublicOrigin = "https://localhost:44306",                    
                    };

                    idsrvApp.UseIdentityServer(options);
                });
            }

            X509Certificate2 LoadCertificate()
            {
                return new X509Certificate2(
                    string.Format(@"{0}\certificates\idsrv3test.pfx",
                    AppDomain.CurrentDomain.BaseDirectory), "idsrv3test");
            }

并在 web.config 内为 IdSrv 添加了

WebAPI 包含以下内容

public class SampleController: ApiController
    {
        [Route("test")]
        public IHttpActionResult Get()
            {
            var caller = User as ClaimsPrincipal;//grants access to claim from access token

            Message msg = new Message
            {
                Msg = "Connction made with secure api" + DateTime.Now,
               // Client = caller.FindFirst("client_id").Value
            };
            return Json(msg);
        }
    }

    public class Message
    {
        public string Msg { get; set; }
        public string Client { get; set; }
    }

startup.cs

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            app.UseIdentityServerBearerTokenAuthentication(
             new IdentityServerBearerTokenAuthenticationOptions
             {
                 Authority = "https://localhost:44306/identity",
                 RequiredScopes = new[] { "vendorsubmission" },
             });
        }
    }

在 API 中禁用 OWIn 我可以进行 https://localhost:44307/test 之类的调用并到达终点。

控制台应用程序在 program.cs

中包含此内容
class Program
    {

        static void Main(string[] args)
        {
            var response = GetClientToken();
            CallApi(response);
        }

        static void CallApi(TokenResponse response)
        {
            var client = new HttpClient();
            client.SetBearerToken(response.AccessToken);
            System.Console.WriteLine(client.GetStringAsync("http://localhost:44307/test").Result);
        }

        static TokenResponse GetClientToken()
        {
            var client = new TokenClient(
                "http://localhost:44306/identity/connect/token",
                "samplecnsl", //client name
                "F621F470-9731-4A25-80EF-67A6F7C5F4B8"); //secret

            return  client.RequestClientCredentialsAsync("vendorsubmission").Result;

        }
    }

执行任务时出错(任务被取消)。我收到消息请求的资源不支持 GET。我认为这将是一个 cors 问题,但我在身份服务器上启用了 CORS,我什至在 web.config:

中添加了 http 协议
<httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>

任何人都可以提供一些关于如何让控制台应用程序从身份服务器检索令牌的指导吗?我觉得这是一个授权问题。我在 Dev IISExpres 中本地 运行,我目前正在使用身份服务器源提供的证书。

谢谢

使用所谓的客户端凭据授予

https://www.rfc-editor.org/rfc/rfc6749#section-4.4

这是一个使用 identityserver3 的示例

https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/Clients/ConsoleClientCredentialsClient

CORS 与此场景无关,因为它仅适用于基于浏览器的客户端。所以这可能是您的网络服务器存在问题。