keycloak~uma遠端資源授權對接asp.net core
阿新 • • 發佈:2021-11-18
官方的keycloak的介面卡並沒有提供.net版本的,所以我們需要自己去實現一下,目前打算把資源伺服器對接KC之後,讓資源伺服器的API介面通過KC的UMA授權方式來管理起來,所以需要對這個功能進行開發,springboot版本官方已經實現,.net core版本我們自己實現了一下,對UMA授權不清楚的同學可以先看我這篇文章《keycloak~授權功能的使用》。
- 新增標準的依賴包
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.13" />
- 如果你只用kc做認證,授權自己去實現,你可以直接引用OIDC包,然後對OIDC產生的token進行解析,拿到kc頒發的角色即可
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.1.13" />
- OIDC方式,本例子中的實現,當用戶沒有登入時,會重定向到KC登入頁進行認證
/// <summary> /// OIDC認證 /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <param name="scopes"></param> /// <returns></returns> public static AuthenticationBuilder addKcOidc(this IServiceCollection services, IConfiguration configuration, ICollection<string> scopes) { return services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie()//開啟cookie的支援 .AddOpenIdConnect(options => { options.Authority = configuration["Oidc:Authority"]; options.ClientId = configuration["Oidc:ClientId"]; options.ClientSecret = configuration["Oidc:ClientSecret"]; options.SaveTokens = true; options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken; options.RequireHttpsMetadata = false; options.GetClaimsFromUserInfoEndpoint = true; options.SaveTokens = true; options.Scope.Clear(); foreach (var scope in scopes) { options.Scope.Add(scope); } options.Events = new OpenIdConnectEvents { OnTokenValidated = context => { //獲取到了id_token var identity = context.Principal.Identity as ClaimsIdentity; var token = context.ProtocolMessage.AccessToken; if (token != null) { var payload = token.Split(".")[1]; string payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload)); JObject json = JObject.Parse(payloadJson); if (json.ContainsKey("realm_access")) { var access = json["realm_access"].Values(); foreach (var role in access.Values()) { identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString())); } } // 客戶端角色 if (json.ContainsKey("resource_access")) { var access = json["resource_access"].Values(); foreach (var role in access["roles"].Values()) { identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString())); } } } return Task.CompletedTask; }, OnTokenResponseReceived = context => { return Task.CompletedTask; }, }; }); }
- UMA遠端授權,本例子中,當用戶訪問介面時,沒有帶著token,將返回401,如果token沒有許可權將返回403
/// <summary> /// uma遠端資源 /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <param name="scopes"></param> /// <returns></returns> public static AuthenticationBuilder addKcUma(this IServiceCollection services, IConfiguration configuration) { return services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.Authority = configuration["Oidc:Authority"]; options.Audience = configuration["Oidc:ClientId"]; options.IncludeErrorDetails = true; options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = true, ValidIssuer = configuration["Oidc:Authority"], ValidateLifetime = false }; options.Events = new JwtBearerEvents { OnTokenValidated = context => { //獲取到了id_token var identity = context.Principal.Identity as ClaimsIdentity; if (context.Request.Headers.ContainsKey(AuthName)) { var token = context.Request.Headers[AuthName].ToString(); if (token != null) { var provider = services.BuildServiceProvider();//get an instance of IServiceProvider var clientFactory = provider.GetService<IHttpClientFactory>(); string uma = getUmaToken(clientFactory, options.Authority, options.Audience, token).Result; // 客戶端所擁有的資源 List<UmaResource> umaResources = getUmaPermissions(uma); // 本伺服器的所有資源 List<string> allResources = getServerUmaPermissions(clientFactory, options.Authority, options.Audience, configuration["Oidc:ClientSecret"]).Result; // 過濾本伺服器的資源 umaResources = umaResources.Where(i => allResources.Contains(i.rsid)).ToList(); // 當前url string currentUrl = context.Request.Path; foreach (UmaResource item in umaResources) { // 校驗當前url是否在客戶端授權的url中 List<string> urls = getUmaUrls(clientFactory, options.Authority, item.rsid, token).Result; foreach (string url in urls) { if (url.EndsWith("*")) { if (currentUrl.Contains(url.TrimEnd('*'))) return Task.CompletedTask; } else { if (url.Equals(currentUrl)) return Task.CompletedTask; } } } } } var payload = JsonConvert.SerializeObject(new { Code = "403", Message = "很抱歉,您無權訪問該介面" }); context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.WriteAsync(payload); return Task.FromResult(0); } }; }); }
- 在startup中去註冊我們的認證方式
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.addKcUma(Configuration);
services.AddAuthorization();
services.AddHttpClient();
}
- 未認證的資源將出現403的結果
作者:倉儲大叔,張佔嶺,
榮譽:微軟MVP
QQ:853066980
支付寶掃一掃,為大叔打賞!