c# - WebAPI2:微服务架构中的授权代码流
问题描述
身份提供者:Keycloak-9.0.0 .net 版本:4.5.2
基本上我正在尝试集成 c# webapi 服务,如下所示。
我已经为 C# 使用了 Keycloak 连接器(https://github.com/mattmorg55/Owin.Security.Keycloak),它被设计为 OWIN 身份验证中间件组件
使用 keycloak 示例我得到错误。但我不确定呼叫是否被转发到 keycloak 进行验证,而是我得到一个错误。
- 如果未启用 WebAPI 模式,我会收到“签名验证失败无法匹配孩子”
- 如果启用 webAPI 模式,我得到 401 ({"Message":"Authorization has been denied for this request."}Access Unauthorized: 需要有效的不记名令牌授权标头
创业班
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Bearer"
});
app.UseKeycloakAuthentication(new KeycloakAuthenticationOptions
{
Realm = "test_keycloak",
ClientId = "test",
ClientSecret = "9f25fd55-851f-4eed-9fb9-24a0a0e4ff11",
KeycloakUrl = "http://localhost:8080/auth",
AuthenticationType = "Bearer",
SignInAsAuthenticationType = "Bearer",
AllowUnsignedTokens = false,
DisableIssuerSigningKeyValidation = false,
DisableIssuerValidation = false,
UseRemoteTokenValidation = true,
EnableWebApiMode = true,
DisableAudienceValidation = false,
Scope= "openid",
});
}
我在 keycloak 中没有看到任何日志。可能出了什么问题?我该如何调试?
由于它是标准的 Oauth2 流程,我可以使用 Microsoft.Owin.Security.OpenIdConnect 进行令牌验证吗?
例如,在 java 中,spring security 具有相同的简单配置(使用 jwt-cert -url)
需要你的投入!
解决方案
我也可以用 microsoft.owin.security.jwt 解决。这是代码。
注意:没有做异常处理。只是基本代码。
public void Configuration(IAppBuilder app) {
HttpClient htpp = new HttpClient();
var keysResponse = htpp.GetAsync("https://<FQDN of keycloak>/auth/realms/<realm>/protocol/openid-connect/certs").Result;
var rawKeys = keysResponse.Content.ReadAsStringAsync().Result;
Microsoft.IdentityModel.Tokens.JsonWebKeySet jsonWebKeySet = JsonConvert.DeserializeObject<Microsoft.IdentityModel.Tokens.JsonWebKeySet>(rawKeys);
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
AuthenticationMode = AuthenticationMode.Active,
Realm = <realm>",
TokenValidationParameters = new TokenValidationParameters() {
AuthenticationType = "Bearer",
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
ValidAudiences = new string[] { <clientID> },
ValidIssuer = "<FQDN of keycloak>/auth/realms/<realm>",
ValidateLifetime = true,
ValidateAudience = true,
IssuerSigningKeys = jsonWebKeySet.GetSigningKeys(),
}
});
}
推荐阅读
- c++ - 解决#define与结构成员的冲突
- flutter - 使用依赖项/插件发布 Flutter 应用程序
- postgresql - 如何提高我的 postgres 查询的选择速度?
- odoo - 关于传递参数的 Odoo 10 XML RPC 问题
- php - 如何使用表单中的内容将文件写入服务器?
- typescript - 使用 TS\ES6 getter 访问深层属性(如快捷方式)
- powershell - 退出循环并开始新的并行循环
- javascript - 我有一个分为 tabS 的表单,我想在移动到下一个选项卡之前验证表单元素输入
- entity-framework - 所有选择查询的 EF Read-Uncommitted
- javascript - 我怎样才能安排更多的div?