我目前有一个aspnet core 2.1应用程序,其中的身份验证和授权由身份处理,用户,角色和声明都保存在de数据库中。
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
是否有一种方法(仅)将身份验证切换到oauth2,然后在数据库中搜索用户(如果基于电子邮件或登录名被发现),然后告诉Identity该用户已登录?这样,我不应该更改控制器中的授权功能。
我已经通过oauth2身份验证(提供者为github)成功进行了测试。
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "GitHub";
})
.AddCookie()
.AddOAuth("GitHub", options =>
{
options.ClientId = "my client id";
options.ClientSecret = "my client secret";
options.CallbackPath = new PathString("/Home/Index");
options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
options.TokenEndpoint = "https://github.com/login/oauth/access_token";
options.UserInformationEndpoint = "https://api.github.com/user";
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 = JObject.Parse(await response.Content.ReadAsStringAsync());
context.RunClaimActions(user);
}
};
});
问题是if (_signInManager.IsSignedIn(User))
这样的代码将不再起作用,因为此身份验证是通过oath2进行的。