我正在尝试使用 IdentityServer3 和客户端凭据流程来设置一个简单的示例。该示例包含一个控制台客户端,使用从 IdentityServer 接收的令牌调用 Web API 资源。 Web API 和 IdentityServer 托管在 IIS 中。
我设法使用以下方法从 IdentityServer 获取令牌:
var client = new TokenClient(
"https://machine+domain/WebHostedId3/connect/token",
"client",
"secret");
但是当我尝试使用以下方式调用 Web API 时:
var client = new HttpClient();
client.SetBearerToken(token);
var response = client.GetStringAsync("http://localhost/WebHostedApi/api/products").Result;
我收到 401(响应状态代码并不表示成功:401(未经授权)。
IdentityServer的设置如下:
public class Clients
{
public static List<Client> Get()
{
return new List<Client>
{
new Client
{
ClientName = "Client Credentials Flow Client",
Enabled = true,
ClientId = "client",
AccessTokenType = AccessTokenType.Reference,
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
Flow = Flows.ClientCredentials,
AllowedScopes = new List<string>
{
"api"
}
}
};
}
}
public class Scopes
{
public static IEnumerable<Scope> Get()
{
return new[]
{
new Scope
{
Name = "api",
DisplayName = "API Scope",
Type = ScopeType.Resource,
Emphasize = false
}
};
}
}
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}")
.CreateLogger();
var factory = new IdentityServerServiceFactory()
.UseInMemoryUsers(new System.Collections.Generic.List<InMemoryUser>())
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get());
var options = new IdentityServerOptions
{
Factory = factory,
};
appBuilder.UseIdentityServer(options);
}
}
网络 API:
public static class WebApiConfig
{
public static HttpConfiguration Register()
{
var config = new HttpConfiguration();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultRouting",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// require authentication for all controllers
config.Filters.Add(new AuthorizeAttribute());
return config;
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}")
.CreateLogger();
app.UseIdentityServerBearerTokenAuthentication(
new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "machine+domain:443",
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { "api" }
});
app.UseWebApi(WebApiConfig.Register());
}
}
用于 SSL 的证书是使用 IIS 创建自签名证书功能创建的,并连接到 IdentityServer 的 https 绑定。除了“响应状态代码不表示成功:401(未经授权)”异常之外,我找不到更多详细信息。来自 IdentityServer 的日志看起来不错。帮助将不胜感激。