首页 > 解决方案 > WebAPI2:微服务架构中的授权代码流

问题描述

身份提供者:Keycloak-9.0.0 .net 版本:4.5.2

基本上我正在尝试集成 c# webapi 服务,如下所示。

授权码流程

我已经为 C# 使用了 Keycloak 连接器(https://github.com/mattmorg55/Owin.Security.Keycloak),它被设计为 OWIN 身份验证中间件组件

使用 keycloak 示例我得到错误。但我不确定呼叫是否被转发到 keycloak 进行验证,而是我得到一个错误。

  1. 如果未启用 WebAPI 模式,我会收到“签名验证失败无法匹配孩子”
  2. 如果启用 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)

需要你的投入!

标签: c#asp.net-web-apioauth-2.0keycloakopenid-connect

解决方案


我也可以用 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(),
                
            }
        });
    }

推荐阅读