.net - 在 IdentityServer4 中保护客户端
问题描述
我有以下情况:
我对如何在 IdentityServer4 中设置API 2感到困惑,因为在我看来它既是一个Client
(因为它正在消耗API 1提供的资源)又是一个ApiResource
(因为我想保护它以便只记录-在用户可以访问它)。
我考虑过将API 2设置为 aClient
并使用 cookie 身份验证对其进行保护。我认为这与他们在示例中的 MvcClient 中所做的类似。但是,我不喜欢它,因为有关用户的所有信息都存储在服务器端,所以我的 JavaScript 应用程序无法知道用户的姓名、电子邮件等。
处理这种情况的最佳方法是什么?
解决方案
基本上,您需要使用 Identity Server 保护您的两个 API。就像是:
API 1 Startup.cs:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:5000";
options.SupportedTokens = SupportedTokens.Both;
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
API 2 相同,但options.ApiName
应该不同。然后,当在 Identity Server 端构建时,您的 javascript 客户端应该被允许访问这 2 个 api(允许的范围):
new Client
{
ClientId = "your.js.client.id",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { "http://localhost:5003/callback.html" },
PostLogoutRedirectUris = { "http://localhost:5003/index.html" },
AllowedCorsOrigins = { "http://localhost:5003" },
AllowedScopes =
{
"api2",
"api1"
}
}
此代码来自官方文档。
然后在 API 2 中,当你想调用 API 1 的控制器时,你需要类似:
var client = new HttpClient();
client.SetBearerToken(accessToken);
client.GetStringAsync("https://localhost/api1/test");
你在哪里得到access_token
:
[Authorize]
public async Task<IActionResult> ControllerMethodInApi2()
{
var accessToken = await context.HttpContext.GetTokenAsync("access_token");
return View();
}
这应该适合你。
推荐阅读
- javascript - Fetch 仅适用于刷新
- javascript - 表输入值使用 JQuery 返回 NaN
- c - 优化和时间切片导致多任务数据问题
- generics - 如何将接受迭代器的函数提升为具有引用参数的泛型并要求该项为 i32?
- r - R:使用 dplyr 和 group_by 找到绝对差异
- laravel - Laravel 中具有静态方法的门面与类
- android - Koin:在不同的模块定义之间传递属性
- c# - 从 Azure Function 中的 azure blob 容器读取八位字节流时出现超时错误
- php - 方法 Illuminate\Database\Eloquent\Collection::addEagerConstraints 不存在 LARAVEL
- parsing - Ply shift/reduce 冲突:悬空 else 和空产品