using Owin;
using System.Collections.Generic;
using IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Services.InMemory;
namespace IdSrv
{
class Startup
{
public void Configuration(IAppBuilder app)
{
var options = new IdentityServerOptions
{
Factory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get())
.UseInMemoryUsers(new List<InMemoryUser>()),
RequireSsl = false
};
app.UseIdentityServer(options);
}
}
}
[Route("test")]
public class TestController : ApiController
{
public IHttpActionResult Get()
{
var caller = User as ClaimsPrincipal;
return Json(new
{
message = "OK computer",
client = caller.FindFirst("client_id").Value
});
}
}
控制器上的用户属性让您从访问令牌中访问该请求的权限。
添加Startup
添加以下Startup.cs为建立Web API和identityserver配置信任启动类
using IdentityServer3.AccessTokenValidation;
public void Configuration(IAppBuilder app)
{
// accept access tokens from identityserver and require a scope of 'api1'
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://localhost:5000",
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { "api1" }
});
// configure web api
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
// require authentication for all controllers
config.Filters.Add(new AuthorizeAttribute());
app.UseWebApi(config);
}
试着打开浏览器,访问测试控制器-你应该看到一个401,因为必要的访问令牌丢失。
添加Console客户端
在下一部分中,我们将添加一个简单的控制台客户端,该客户端将请求访问令牌,并使用该接口进行身份验证。
首先添加一个新的控制台项目并安装一oauth2客户端需要的NuGet包:
install-package IdentityModel
第一段代码 获取客户端Token使用客户端证书:
using IdentityModel.Client;
static TokenResponse GetClientToken()
{
var client = new TokenClient(
"http://localhost:5000/connect/token",
"silicon",
"F621F470-9731-4A25-80EF-67A6F7C5F4B8");
return client.RequestClientCredentialsAsync("api1").Result;
}
第二段代码 使用访问令牌调用API:
static void CallApi(TokenResponse response)
{
var client = new HttpClient();
client.SetBearerToken(response.AccessToken);
Console.WriteLine(client.GetStringAsync("http://localhost:14869/test").Result);
}