问题描述
我试图确定是否有可能编写ASP.NET Core API,该API根据我已配置的身份服务器使用的身份,使用引用令牌或JWT令牌使用身份服务器令牌。 IS4的后端配置非常简单,我只是不敢相信我可以配置2种不同的令牌中间件,并且我的服务都可以使用它并且知道该怎么做。
所以想法是:
- 如果我的API获得了jwtToken,它将尝试使用jwt中间件向身份服务器授权。
- 如果我的API获得了参考令牌,它将尝试使用自省中间件向身份服务器授权。
很明显,如果为IS4服务上配置的任何内容提供了错误的令牌类型,它将失败。
处理令牌端点和吊销端点也应该很容易,这只是我所关心的中间件魔术。
我知道您通常不想这样做,但是我们有一个合适的用例。我目前关心的只是它是否可能。我不熟悉auth中间件在后端的工作方式。
解决方法
根据Identity Server 4 Protecting APIs document,我们可以看到它支持在asp.net核心中同时使用JWT和引用令牌。
您可以将ASP.NET Core设置为根据传入的令牌分派到正确的处理程序,有关更多信息,请参见this blog。
services.AddAuthentication("token")
// JWT tokens
.AddJwtBearer("token",options =>
{
options.Authority = Constants.Authority;
options.Audience = "resource1";
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
// if token does not contain a dot,it is a reference token
options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
})
// reference tokens
.AddOAuth2Introspection("introspection",options =>
{
options.Authority = Constants.Authority;
options.ClientId = "resource1";
options.ClientSecret = "secret";
});
,
我要做的是在这两种情况下都使用内省和声明缓存,这样API无需知道或关心它接收哪种访问令牌。
仅当第一次收到访问令牌时,才会进行自省。随后具有相同令牌的请求将使用缓存的声明。
资源
,Supporting both JWTs and reference tokens
除了@Zhi Lv 帖子,您可能还需要添加授权策略、身份验证方案以允许验证 JWT 和引用令牌。
这里是示例代码模板,适当地替换了 api 名称、api 秘密和受众。
#include <type_traits>
#include <string_view>
template<const char *const t_name>
class TestString {
public:
static constexpr bool TestStringCondition(const char *name) noexcept {
return std::string_view(name).find('a') != std::string_view::npos; // random condition
}
constexpr TestString() noexcept {
static_assert(TestStringCondition(t_name));
}
};
constexpr char okay[] = "okay"; // array,so it is a static object with linkage
int main() {
static const TestString<okay> testString{};
}