用于 ASP.NET Core 的 Keycloak 客户端 [英] Keycloak client for ASP.NET Core

查看:67
本文介绍了用于 ASP.NET Core 的 Keycloak 客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何现有的用于 Asp.net Core 的 Keycloak 客户端?我找到了一个适用于 .net 的 NuGet 包,但它不适用于 Core.您是否有任何想法如何轻松地与此安全服务器集成(或使用任何其他替代方案)?

Is there any existing Keycloak client for Asp.net Core? I have found a NuGet package for .net but it doesn't work with Core. Do you have any ideas how to easily integrate with this security server (or maybe using any other alternatives)?

推荐答案

我今天玩了一点.最直接的方法是也使用 OpenId 标准.

I've played a bit with this today. The most straightforward way is too use OpenId standard.

在 Startup.cs 中,我使用了 OpenIdConnect 身份验证:

In Startup.cs I used OpenIdConnect Authentication:

    public void Configure(...)
    { (...)
         app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
            AutomaticAuthenticate = true,
            CookieHttpOnly = true,
            CookieSecure = CookieSecurePolicy.SameAsRequest
        });
        app.UseOpenIdConnectAuthentication(CreateKeycloakOpenIdConnectOptions());`(...)
 }`

OpenIdConnectOptions 方法:

OpenIdConnectOptions method:

private OpenIdConnectOptions CreateKeycloakOpenIdConnectOptions()
    {
        var options = new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc",
            SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme,
            Authority = Configuration["Authentication:KeycloakAuthentication:ServerAddress"]+"/auth/realms/"+ Configuration["Authentication:KeycloakAuthentication:Realm"],
            RequireHttpsMetadata = false, //only in development
            PostLogoutRedirectUri = Configuration["Authentication:KeycloakAuthentication:PostLogoutRedirectUri"],
            ClientId = Configuration["Authentication:KeycloakAuthentication:ClientId"],
            ClientSecret = Configuration["Authentication:KeycloakAuthentication:ClientSecret"],
            ResponseType = OpenIdConnectResponseType.Code,
            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true

        };
        options.Scope.Add("openid");
        return options;
    }

在 appsettings.json 中为 Keycloak 添加配置:

In appsettings.json add configuration for Keycloak:

{
  (...),
  "Authentication": {
    "KeycloakAuthentication": {
      "ServerAddress": "http://localhost:8180",
      "Realm": "demo",
      "PostLogoutRedirectUri": "http://localhost:57630/",
      "ClientId": "KeycloakASPNETCore",
      "ClientSecret": "secret-get-it-in-keycloakConsole-client-credentials"
    }
  }
}

Keycloak 客户端配置如下:

Keycloak client is configuerd as followed:

如果我想按角色授权用户,我会这样做:

If I want to Authorize user by role I do something like this:

在 ConfigureServices 方法中添加声明授权:

Add authorization by claims in ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
    {
        (...)

        services.AddAuthorization(options =>
        {
            options.AddPolicy("Accounting", policy =>
            policy.RequireClaim("member_of", "[accounting]")); //this claim value is an array. Any suggestions how to extract just single role? This still works.
        });
    }

我在 ValuesController(默认 Web API 模板)中编辑了 get 方法:

I've edited get method in ValuesController (Default Web API template):

[Authorize(Policy = "Accounting")]
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values        
    [HttpGet]
    public Dictionary<string,string> Get()
    {
        var userPrinciple = User as ClaimsPrincipal;
        var claims = new Dictionary<string, string>();

        foreach (var claim in userPrinciple.Claims)
        {
            var key = claim.Type;
            var value = claim.Value;

            claims.Add(key, value);
        }


        return claims;
    }

如果我使用具有会计角色的用户或在具有会计角色的组中登录,它应该在地址 localhost:57630/api/values 上显示我的用户声明.

If I login with user that has accounting role or is in group that has accounting role, it should display my user claims on address localhost:57630/api/values.

我希望这对你有用.

.NET Core 2大家好!我的应用程序的工作方式发生了很大变化,我还没有完全测试 .NET Core 2,但您仍然可以尝试在 ConfigureServices 中像这样连接到 Keycloak:

.NET Core 2 Hi everyone! The way my app works changed quite a bit and I have not fully tested .NET Core 2 yet, but you can still try connecting to Keycloak like this in ConfigureServices:

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {

                options.Authority = Configuration["Authentication:KeycloakAuthentication:ServerAddress"] + "/auth/realms/" + Configuration["Authentication:KeycloakAuthentication:Realm"];
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidAudiences = new string[] { "curl", "financeApplication", "accountingApplication", "swagger"}
                };
                options.RequireHttpsMetadata = false; //for test only!
                options.SaveToken = true;
                options.Validate();

            });

在配置中:

app.UseAuthentication();

您可以稍后使用 IHttpContextAccessor httpContextAccessor 访问您的令牌,例如:

You can access your token later with IHttpContextAccessor httpContextAccessor, for example:

public KeycloakAuthorizationRequirementHandler(IConfiguration config,
            IHttpContextAccessor httpContextAccessor,
            IMemoryCache memoryCache)
        {
            _config = config;
            _httpContextAccessor = httpContextAccessor;
            _memoryCache = memoryCache;
        }

//获取访问令牌

var accessToken = _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

_httpContextAccessor.HttpContext.Items["username"] = username;

告诉我进展如何.

这篇关于用于 ASP.NET Core 的 Keycloak 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆