我正在寻找一个在C#的Keycloak客户端的工作实现。DylanPlecki和MattMorg (后来)在github上的两个项目对我都不起作用,很可能不再进行维护。
我的任务是让给定用户的所有角色在我们的数据库服务器上实现更精细的数据库访问。所以实际上我并不是一个认证服务器,而更多的是为了获取用户的信息。在我们公司,我们正在开始使用OAUTh2.0 ;-)。
所以我的问题是:有没有人知道,如何最有效地访问keycloak服务器来保护应用程序的安全性并获得角色?也许是通过RestAPI,或者OIDC协议?
发布于 2020-07-23 08:18:00
@Thomas Brüggemann's answer (最终)让我走上了正确的道路:
我使用RestClient类来获取我的用户的角色。最后一个悬而未决的问题是,我必须将键入的凭据存储在RAM中。如果你在webapp的上下文中,这肯定会在keycloak登录页面实现中得到更好的解决。但我继续寻找更好的解决方案。也许作为第一步,我将在获得令牌后直接删除用户/密码组合。
我的目标是访问一个keycloak服务器,以获得我需要的角色,以完善我的用户管理。作为一个非常原始的测试示例,我在最后一行中获得了一个字典,其中包含所请求用户的所有角色:
using RestSharp;
using System.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.Security.Claims;
using System.Web;
using System.Security.Principal;
using Microsoft.AspNet.Identity;
[..]
[..]
public String GetAccessAndRefreshToken()
{
RestClient client = new RestClient("http://YourKeycloakServer:YourKCPort/auth/realms/YourRealm/protocol/openid-connect/token");
RestRequest request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("client_id", "YourAppsNameInKeycloak");
request.AddParameter("username", AuthenticationViewModel.UserName);
request.AddParameter("password", AuthenticationViewModel.Pass);
request.AddParameter("client_secret", "YourSecretinKeycloak");
IRestResponse response = client.Execute(request);
String content = response.Content;
return content;
}
public List<String> GetRoles(String content)
{
JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();
//string pattern = @"{\n.* ""(.*)"",";
String pattern = @".*access_token\"":\""(.*)\"",\""expires.*";
MatchCollection accessTokenMatch = Regex.Matches(content, pattern, RegexOptions.IgnoreCase);
var group1 = (String)accessTokenMatch[0].Groups[1].ToString();
JwtSecurityToken token = (JwtSecurityToken)jwtHandler.ReadToken((String)accessTokenMatch[0].Groups[1].ToString());
Claim realmAccessClaim = token.Claims.First((claim) => claim.Type == "realm_access");
Dictionary<string, string[]> realmAccessAsDict = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(realmAccessClaim.Value);
List<String> roles = realmAccessAsDict.FirstOrDefault().Value.ToList();
return roles;
}
[..]最后,您将获得一个字符串形式的角色列表,您可以手动解析它们。
https://stackoverflow.com/questions/63044966
复制相似问题