设置机器到机器(WebAPI的控制台)授权使用Identity Server3



我正在尝试使用IdentityServer3作为授权服务来从控制台应用程序设置授权到WebAPI端点。这不是自托管的API,它将是公众面对的。我尝试遵循身份服务器上的文档,并且我独立运行API和IdentityServer。我遇到麻烦的地方是获取API路由以检查授权并从Identity Server中请求/接收访问令牌。

在身份服务器中,我有启动.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}certificatesidsrv3test.pfx",
                    AppDomain.CurrentDomain.BaseDirectory), "idsrv3test");
            }

和web.config for 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之类的呼叫并达到端点。

Console应用程序包含在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;
        }
    }

当执行任务错误时(任务已取消)。我收到的消息所请求的资源不支持获得。我认为这将是一个CORS问题,但是我在Identity Server上启用了CORS,甚至在Web.config中的HTTP协议中添加了CORS:

<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中本地运行此操作,目前正在使用Identity Server源提供的证书。

谢谢

使用所谓的客户凭据授予

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

这是使用IdentityServer3

的样本

https://github.com/indistityserver/indistityserver3.samples/tree/master/master/source/clients/consolecleclientcredentialsclient

CORS与此情况无关,因为它仅适用于基于浏览器的客户端。因此,这可能是您的Web服务器的某个问题。

最新更新