【发布时间】:2020-07-31 10:27:40
【问题描述】:
我构建了一个扩展 gitlab 用户体验的应用程序,组织的管理员(组织是系统中的租户)可以配置他们的 gitlab 安装(在他们的 gitlab 实例中注册 OAuth2 应用程序),组织中的普通用户可以通过 OAuth2 使用他们的 gitlab 帐户进行身份验证。
我目前的问题是,凭据(oauth2 客户端 ID 和客户端密码,以及基本 URL)由组织管理员提供并存储在数据库中。我想为每个组织提供自己的子域,使用 Gitlab 登录按钮应将用户重定向到他们的 gitlab 实例并遵循通常的 oauth2 流程进行身份验证,但我不知道如何配置 asp.net 核心身份框架动态决定(基于子域)哪些凭据用于 oauth2 流。所有教程和微软提供的文档都假定您只提供了一个“硬编码”oauth2(通常在 Startup 类的 ConfigureServices 方法中配置)。
我当前的实现遵循 microsoft 提供的文档,如下所示:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "Gitlab";
}).AddCookie()
.AddOAuth("Gitlab", options =>
{
options.ClientId = Configuration["Gitlab:ClientId"];
options.ClientSecret = Configuration["Gitlab:ClientSecret"];
options.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/signin-gitlab");
options.AuthorizationEndpoint = Configuration["Gitlab:BaseUrl"] + "/oauth/authorize";
options.TokenEndpoint = Configuration["Gitlab:BaseUrl"] + "/oauth/token";
options.UserInformationEndpoint = Configuration["Gitlab:BaseUrl"] + "/api/v4/user";
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
options.ClaimActions.MapJsonKey("gitlab:avatar_url", "avatar_url");
options.ClaimActions.MapJsonKey("gitlab:profile_url", "web_url");
options.SaveTokens = true;
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var user = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync());
context.RunClaimActions(user);
}
};
});
}
如何实施这样的系统?
【问题讨论】:
-
我不了解 Gitlab,但 ASP.NET Core 允许您根据需要为任何使用选项模式的任何请求动态设置选项。如何配置 OAuth 权限、客户端 ID 和密码?
-
目前我将它们设置在
ConfigureServices方法的Startup类中,据我所知,该方法仅在启动时运行一次。 -
你能告诉我ConfigureServices的相关代码吗?
-
我添加了 ConfigureServices 方法的相关部分。请注意,此代码使用
Configuration的静态方法,而不是我使用更动态方法的失败实验。 -
应该是可行的。请稍等,直到我找到我在我的一个项目中使用的示例,以便我为您写一个答案。
标签: asp.net-core oauth-2.0 asp.net-core-identity