我已经设置了 IdentityServer4 和另一个客户端 ASP.NET Core 应用程序。客户端需要通过 IdentityServer 进行身份验证并请求访问标准 MVC Web API 项目的第三个应用程序。
我已按照此示例https://identityserver.github.io/Documentation/docsv2/overview/simplestOAuth.html实现客户端凭据流的步骤
现在我完全不知道如何让 WEB API 首先识别承载令牌,然后给我一些授权来访问 web api 端点。
这是我的 IdentityServer Statrup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddInMemoryStores()
.AddInMemoryClients(Config.GetClients())
.AddInMemoryScopes(Config.GetScopes());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Debug);
app.UseDeveloperExceptionPage();
app.UseIdentityServer();
}
}
和 Config.cs
public class Config
{
// scopes define the resources in your system
public static IEnumerable<Scope> GetScopes()
{
return new List<Scope>
{
new Scope
{
Name = "api1"
}
};
}
// clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
// no human involved
new Client
{
ClientName = "Silicon-only Client",
ClientId = "silicon",
Enabled = true,
AccessTokenType = AccessTokenType.Reference,
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = new List<Secret>
{
new Secret("F621F470-9731-4A25-80EF-67A6F7C5F4B8".Sha256())
},
AllowedScopes = new List<string>
{
"api1"
}
}
};
}}
ASP.NET Core 调用 IdentityServer 和 Web API
[Route("api/testing")]
public class TestingController : Controller
{
// GET: api/values
[HttpGet]
public IActionResult Get()
{
var responce = GetClientToken();
return Json(new
{
message = CallApi(responce)
});
}
static TokenResponse GetClientToken()
{
var client = new TokenClient(
Constants.TokenEndpoint,
"silicon",
"F621F470-9731-4A25-80EF-67A6F7C5F4B8");
return client.RequestClientCredentialsAsync("api1").Result;
}
static string CallApi(TokenResponse response)
{
var client = new HttpClient
{
BaseAddress = new Uri(Constants.AspNetWebApiSampleApi),
Timeout = TimeSpan.FromSeconds(10)
};
client.SetBearerToken(response.AccessToken);
try
{
var auth = client.GetStringAsync().Result;
return auth;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
那么任何人都可以解释或分享一些关于我应该怎么做才能让 WEB APi(带有 owin 中间件)来处理来自 ASP.NET Core 客户端的调用的链接吗?我应该在 Owin 配置(IAppBuilder 应用程序)方法中放置什么设置。