我是 ASP.NET Core Identity 的新手,我很难弄清楚如何添加对不受支持的 OAuth2.0 提供程序(如 Discord)的支持。
根据我的理解,我需要使用 AddOAuth() 方法,但我有一些问题。
当我配置 OAuthOptions 时,我可以设置
CallbackPath
,我是否必须创建一个与该路径匹配的控制器操作来处理将用户保存到数据库?
我见过人们使用
OAuthOptions.Events.OnCreatingTicket
来处理添加用户声明,但我也读到有一个 SignInManager<TUser>.GetExternalLoginInfoAsync()
方法,据说应该使用访问令牌来使用 OAuthOptions.UserInformationEndpoint
获取用户信息。
这就是我的代码现在的样子:
// Program.cs
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "Example";
})
.AddCookie()
.AddOAuth("Example", options =>
{
options.ClientId = configuration["Credentials:Example:ClientId"];
options.ClientSecret = configuration["Credentials:Example:ClientSecret"];
options.AuthorizationEndpoint = "https://apis.example.com/oauth/v1/authorize";
options.CallbackPath = new PathString("/api/v1/auth/redirect");
options.TokenEndpoint = "https://apis.example.com/oauth/v1/token";
options.UserInformationEndpoint = "https://apis.example.com/oauth/v1/userinfo";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
});
如果有人可以通过一些示例代码向我展示处理此类情况的正确方法,我将非常感激,因为我已经坚持了两天。
1.Asp.Net Core 自动处理 OAuth 回调,您不需要创建控制器操作。
2.在我的研究中,SignInManager.GetExternalLoginInfoAsync()经常处理OAuth检索的信息。所以 OAuthOptions.Events.OnCreatingTicket 是一个不错的选择
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "Example";
})
.AddCookie()
.AddOAuth("Example", options =>
{
var configuration = builder.Configuration;
options.ClientId = configuration["Credentials:Example:ClientId"];
options.ClientSecret = configuration["Credentials:Example:ClientSecret"];
options.AuthorizationEndpoint = "https://apis.example.com/oauth/v1/authorize";
options.CallbackPath = new PathString("/api/v1/auth/redirect");
options.TokenEndpoint = "https://apis.example.com/oauth/v1/token";
options.UserInformationEndpoint = "https://apis.example.com/oauth/v1/userinfo";
options.Scope.Add("openid");
options.Scope.Add("profile");
// Map claims
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
var userInfo = context.User; // context.User is a JsonElement
var userId = userInfo.GetProperty("id").GetString();
var userName = userInfo.GetProperty("username").GetString();
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId));
context.Identity.AddClaim(new Claim(ClaimTypes.Name, userName));
}
};
});