在 Asp Net Core 6 中与 Github 进行身份验证

5

我想在我的Asp Net Core 6项目中添加与GitHub的身份验证,但是我在互联网上找到的所有内容都是针对较旧版本的Asp Net。该怎么实现呢?

我向我的项目添加了Microsoft.AspNetCore.Authentication.OAuth包,并创建了一个GitHub OAuth应用程序。我还使用客户端ID和客户端密钥进行了添加。

dotnet user-secrets set Github:ClientId <clientid>
dotnet user-secrets set Github:ClientSecret <clientsecret>

我在网上搜索了一些教程,但是只找到了使用低于6版本的Asp Net的教程。


1
你能否编辑你的问题并展示你尝试过什么,并描述你遇到的问题? - Linda Lawton - DaImTo
2个回答

2

请使用 AspNet.AspNet.Security.OAuth.GitHubOctoKit 库。你需要在项目路径下运行安装命令。例如:

PM> cd .\GithubAuth
PM> Install-Package AspNet.Security.OAuth.GitHub -Version 6.0.5
PM> Install-Package Octokit -Version 0.50.0

我在我的dotnet core 6应用程序中进行了测试,它运行良好。

更多详情请查看以下博客:

在这些博客中,提到了Linux平台,您可以忽略它。

为ASP.NET Core应用添加GitHub OpenID认证


但是在教程中使用的是Startup.cs,而我有一个Program.cs。我的了解是他们在Asp Net 6中进行了更改。结构也完全不同。 - CheckerPhil
@CheckerPhil 不用担心。在 .net 5 中的示例代码,像 services.AddAuthentication... - Jason Pan
@CheckerPhil 在 .NET 6 中,你可以像这样编写代码: builder.Service.AddAuthentication.... - Jason Pan
@CheckerPhil,.Net6并不像你想象的那么复杂,基本上是一样的。如果我的回答有帮助,请将其接受为答案(点击回复旁边的标记选项,将其从灰色变为填充状态)。请参阅https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work。 - Jason Pan
1
我只是复制了Github项目链接中提供的Startup.cs文件到我的Program.cs中,然后它就可以工作了。谢谢! - CheckerPhil

2
这是来自于ASP.NET Core 7.0的外部OAuth认证提供程序的说明。

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/other-logins?view=aspnetcore-7.0

在这里注册一个新的OAuth应用程序:

https://github.com/settings/applications/new

如果你想让你的组织拥有它,那么请使用这个指南:

https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app

授权 OAuth 应用的文档

https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps

微软的文档说:
第三方 NuGet 包,例如由 aspnet-contrib 维护的包,可用于补充 ASP.NET Core 团队实现的身份验证提供程序。
这是他们的 NuGet:

https://www.nuget.org/packages/AspNet.Security.OAuth.GitHub

如果您收到错误消息Unable to unprotect the message.State.,请检查是否有多个OIDC连接并确保您的CallbackPath是唯一的。
然后,您可以添加以下代码:
services.AddAuthentication()
    .AddGitHub(options =>
    {
        options.ClientSecret = "<ClientSecret>";
        options.ClientId = "<ClientId>";
        options.CallbackPath = "/signin-oidc-github";
    })
    .AddIdentityServerJwt();

Github SSO 将会像这样:

enter image description here

如果你想要GitHub用户的电子邮件,代码应该是这样的:

如果您想要GitHub用户的电子邮件,代码应该如下:

services.AddAuthentication()
    .AddGitHub(options =>
    {
        options.ClientSecret = "<ClientSecret>";
        options.ClientId = "<ClientId>";
        options.CallbackPath = "/signin-oidc-github";
        options.Scope.Add("user:email");
    })
    .AddIdentityServerJwt();

enter image description here

https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps


对于正在使用Asp.Net 7的人们,我在Github上有一个“Hello World”Web应用程序,演示了与GitHub的OAuth。 - codybartfast

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接