SPA+.NET Core3.1 GitHub第三方授权登录 使用AspNet.Security.OAuth.GitHub

使用SPA+.NET Core3.1实现 GitHub第三方授权登录 类似使用AspNet.Security.OAuth.GitHub,前端使用如下:VUE+Vue-Router+axios

AspNet.Security.OAuth.GitHub

GitHub授权登录

什么配置的过程不说了。。有一推。

下面为示例

client_id:0be6b05fc717bfc4fb67
client_secret:dcaced9f176afba64e89d88b9b06ffc4a887a609

Get

https://github.com/login/oauth/authorize?client_id=0be6b05fc717bfc4fb67&redirect_uri=https://localhost:5001/signin-github

会重定向到

https://localhost:5001/signin-github?code=07537a84d12bbae08361

这个code放到下面的请求中,获取access_token
POST方式(PostMan去请求)

https://github.com/login/oauth/access_token?client_id=0be6b05fc717bfc4fb67&client_secret=dcaced9f176afba64e89d88b9b06ffc4a887a609&code=07537a84d12bbae08361

Get方式

https://api.github.com/user?access_token=787506afa3271d077b98f18af56d7cfdc8db43b4

然后就能获取用户信息

{
   "login": "luoyunchong",
   "id": 18613266,
   "node_id": "MDQ6VXNlcjE4NjEzMjY2",
   "avatar_url": "https://avatars1.githubusercontent.com/u/18613266?v=4",
   "gravatar_id": "",
   "url": "https://api.github.com/users/luoyunchong",
   "html_url": "https://github.com/luoyunchong",
   "followers_url": "https://api.github.com/users/luoyunchong/followers",
   "following_url": "https://api.github.com/users/luoyunchong/following{/other_user}",
   "gists_url": "https://api.github.com/users/luoyunchong/gists{/gist_id}",
   "starred_url": "https://api.github.com/users/luoyunchong/starred{/owner}{/repo}",
   "subscriptions_url": "https://api.github.com/users/luoyunchong/subscriptions",
   "organizations_url": "https://api.github.com/users/luoyunchong/orgs",
   "repos_url": "https://api.github.com/users/luoyunchong/repos",
   "events_url": "https://api.github.com/users/luoyunchong/events{/privacy}",
   "received_events_url": "https://api.github.com/users/luoyunchong/received_events",
   "type": "User",
   "site_admin": false,
   "name": "IGeekFan",
   "company": null,
   "blog": "https://blog.igeekfan.cn",
   "location": null,
   "email": "[email protected]",
   "hireable": null,
   "bio": "学习之路漫漫无期。",
   "public_repos": 14,
   "public_gists": 0,
   "followers": 16,
   "following": 11,
   "created_at": "2016-04-22T10:33:44Z",
   "updated_at": "2019-12-21T14:49:33Z"
}

.NET Core3.1

以下代码为主要代码,完整代码看下面的DEMO链接。

使用WebApi时,看了一些项目,全是基于MVC结构的,都不是我想要的。看了一些博客上面介绍 ,步骤都是千篇一律,都是配合前后端分离的。

  • 前端运行在:http://localhost:8081
  • 后端运行在:https://localhost:5001

    前后端分离的SPA 配合第三方授权登录流程如下

本地测试时,gitHub回调地址设置 http(s)://ip:端口/signin-github

  • 如: https://localhost:5001/signin-github。

1. 上面这个明明填写的后端的地址,那后端怎么把结果通知前端呢?

前端请求https://localhost:5001/signin?provider=GitHub&redirectUrl=http://localhost:8080/login-result

  • 提供参数provider为GitHub,
  • redirectUrl为GitHub授权登录后,回调signin-github后,后端再去重定向的地址,这里填前端的一个路由。

2. 后端只提供了signin,signin-callback路由,没有signin-github,那github上配置的路由是怎么回调回来呢?

google-登录,微软文档,其中有一个更改默认回调 URI,通过 AddGitHub中的CallbackPath属性配置。

介绍了回调地址应配置signin-google,所以这里应该是signin-github,他是可以配置的,不需要自己写程序处理signin-google这个路由,内部有中间件已经处理了。

3. 回调到signin-github后,后端怎么处理,才能让前端刷新。获取登录后的信息呢。

具体上面的根据code获取access_token,根据access_token获取用户的信息的过程,这些处理的过程,都不需要我们自己处理。我们可以用直接获取用户信息。

一个方法SignIn,只要return Challenge(properties, provider);

  • provider 为 GitHub,
  • properties var properties = new AuthenticationProperties { RedirectUri = url };

这个url为另一个获取用户信息的路由,只要拼接好地址即可。

var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
string email = authenticateResult.Principal.FindFirst(ClaimTypes.Email)?.Value;
string name = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value;

需要注入

private readonly IHttpContextAccessor _contextAccessor;
public AuthenticationController( IHttpContextAccessor contextAccessor)
{
    _contextAccessor = contextAccessor;
}

代码部署(简化)

打开NuGet包管理,安装包

Install-Package AspNet.Security.OAuth.GitHub

appSettings.json

"Authentication": {
    "GitHub": {
      "ClientId": "0be6b05fc717bfc4fb67",
      "ClientSecret": "dcaced9f176afba64e89d88b9b06ffc4a887a609"
    }
}

add扩展方法

public static class JwtConfiguration
{
    public static void AddJwtConfiguration(this IServiceCollection services, IConfiguration configuration)
    {

        services.AddAuthentication(opts =>
            {
                opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddCookie(options =>
        {
            options.LoginPath = "/signin";
            options.LogoutPath = "/signout";
        }).AddGitHub(options =>
        {
            options.ClientId = configuration["Authentication:GitHub:ClientId"];
            options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
        });
    }
}

默认情况下,如头像,email,是没有获取的。

.AddGitHub(options =>
{
    options.ClientId = configuration["Authentication:GitHub:ClientId"];
    options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
    //options.CallbackPath = new PathString("~/signin-github");//与GitHub上的回调地址相同,默认即是/signin-github
    options.Scope.Add("user:email");
    //authenticateResult.Principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value;  得到GitHub头像
    options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url");
    options.ClaimActions.MapJsonKey(LinConsts.Claims.BIO, "bio");
    options.ClaimActions.MapJsonKey(LinConsts.Claims.BlogAddress, "blog");
});

#其中LinConsts类为静态常量
public static class LinConsts
{
    public static class Claims
    {
        public const string BIO = "urn:github:bio";
        public const string AvatarUrl = "urn:github:avatar_url";
        public const string BlogAddress = "urn:github:blog";
    }
}

startup.cs

ConfigureServices中配置此服务

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddJwtConfiguration(Configuration);

创建AuthenticationController.cs
增加SignIn,用于处理用户授权成功后,重定回signin-callback,并将参数带回。

        private readonly IHttpContextAccessor _contextAccessor;
        private readonly IConfiguration _configuration;

        public AuthenticationController(IHttpContextAccessor contextAccessor, IConfiguration configuration)
        {
            _contextAccessor = contextAccessor;
            _configuration = configuration;
        }

        [HttpGet("~/signin")]
        public async Task<IActionResult> SignIn(string provider, string redirectUrl)
        {
            var request = _contextAccessor.HttpContext.Request;
            var url =
                $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}-callback?provider={provider}&redirectUrl={redirectUrl}";
            var properties = new AuthenticationProperties { RedirectUri = url };
            properties.Items["LoginProviderKey"] = provider;
            return Challenge(properties, provider);

        }

在signin方法中,用户点击授权后(第一次),会根据其传递的URL,重定向到这个地址,signin-callback,参数也会一同携带。provider为GitHub,redirectUrl为:http://localhost:8081/login-result.

[HttpGet("~/signin-callback")]
public async Task<IActionResult> Home(string provider = null, string redirectUrl = "")
{
    var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
    if (!authenticateResult.Succeeded) return Redirect(redirectUrl);
    var openIdClaim = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier);
    if (openIdClaim == null || string.IsNullOrWhiteSpace(openIdClaim.Value))
        return Redirect(redirectUrl);

    //TODO 记录授权成功后的信息 

    string email = authenticateResult.Principal.FindFirst(ClaimTypes.Email)?.Value;
    string name = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value;
    string gitHubName = authenticateResult.Principal.FindFirst(GitHubAuthenticationConstants.Claims.Name)?.Value;
    string gitHubUrl = authenticateResult.Principal.FindFirst(GitHubAuthenticationConstants.Claims.Url)?.Value;
    //startup 中 AddGitHub配置项  options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url");
    string avatarUrl = authenticateResult.Principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value;

    return Redirect($"{redirectUrl}?openId={openIdClaim.Value}");
}

参考

Demo 示例

原文地址:https://www.cnblogs.com/igeekfan/p/12110012.html

时间: 2024-08-29 01:02:38

SPA+.NET Core3.1 GitHub第三方授权登录 使用AspNet.Security.OAuth.GitHub的相关文章

Github 第三方授权登录教程

Github 第三方授权登录教程 ####大致流程图 ####1.首先注册一个github帐号,Applications>Developer applications>Register a new application. ####2.填入参数 Application name--应用名称,随意填 Homepage URL--如上图可以填本地地址进行测试,127.0.0.1:port/xx/xx Application description--应用描述,随意填 Authorization c

【Android应用开发详解】实现第三方授权登录、分享以及获取用户资料

由于公司项目的需要,要实现在项目中使用第三方授权登录以及分享文字和图片等这样的效果,几经波折,查阅了一番资料,做了一个Demo.实现起来的效果还是不错的,不敢独享,决定写一个总结的教程,供大家互相交流.学习和参考,博主只求能和大家共同进步.希望能多多支持! 这篇文章中,我们使用到了Share SDK,它是为iOS.Android.WP8的APP提供社会化功能的一个组件,目前支持如QQ.微信.新浪微博.腾讯微博.开心网.人人网.豆瓣.网易微博.搜狐微博.facebook.twitter.googl

【Android应用开发详解】第01期:第三方授权认证(一)实现第三方授权登录、分享以及获取用户资料

转载请注明出处:http://blog.csdn.net/yangyu20121224/article/details/9057257 由于公司项目的需要,要实现在项目中使用第三方授权登录以及分享文字和图片等这样的效果,几经波折,查阅了一番资料,做了一个Demo.实现起来的效果还是不错的,不敢独享,决定写一个总结的教程,供大家互相交流.学习和参考,博主只求能和大家共同进步.希望能多多支持! 这篇文章中,我们使用到了Share SDK,它是为iOS.Android.WP8的APP提供社会化功能的一

【转】【Android应用开发详解】第01期:第三方授权认证(一)实现第三方授权登录、分享以及获取用户资料

转载请注明出处:http://blog.csdn.net/yangyu20121224/article/details/9057257 由于公司项目的需要,要实现在项目中使用第三方授权登录以及分享文字和图片等这样的效果,几经波折,查阅了一番资料,做了一个Demo.实现起来的效果还是不错的,不敢独享,决定写一个总结的教程,供大家互相交流.学习和参考,博主只求能和大家共同进步.希望能多多支持! 这篇文章中,我们使用到了Share SDK,它是为iOS.Android.WP8的APP提供社会化功能的一

springboot开发qq第三方授权登录

前几天随手写了一个qq第三方授权登录功能,现总结一下(这里以个人开发网站应用为例): 首先要成为qq互联开发者:https://connect.qq.com/index.html申请步骤请参考文档和百度:https://wiki.connect.qq.com/%E6%88%90%E4%B8%BA%E5%BC%80%E5%8F%91%E8%80%85等待审核通过,通过之后会看到(示例): 然后开始创应用,我这边是网站应用,创建流程请参考文档https://wiki.connect.qq.com/_

iOS开发中 实现登录时关于使用QQ做为第三方授权登录的问题

注意:QQ本身没有授权功能,所以想要使用QQ做第三方登录必须通过QQ空间来实现! 第一步:集成ShareSDK(步骤同集成分享的一样,如果已经集成过就不用再重新集成了),这里需要注意的是,由于是要通过QQ空间来实现授权登录,所以在下载ShareSDK包的时候别忘了勾选QQ空间,不然会报尚未导入平台(6)的错误. 第二步:打开工程中的*AppDelegate.m(*代表你的工程名字)?文件,导入QQSDK的头文件:            #import <TencentOpenAPI/QQApiI

基于OAuth2.0协议的QQ第三方授权登录iOS代码分析

简要说明: 授权登录已经成为注册方式里的主流,目前授权登录方式主要SSO跳转授权登录和OAuth2.0两种,前者好处无需用户再次输入密码就可以直接授权成功,但前提是必须用户手机端安装了该软件,比如QQ,后者的优势就是是否安装无关紧要,是一个HTML的页面呈现,麻烦就在于要输入用户名和密码,这就非常不爽了,但是有时候偏偏必须这么做,理由嘛,自行想想就好,接下来我们就看看如果利用OAuth2.0的方式来做QQ授权登录,如果想了解QQ的SSO授权登录,可以看我(博客主页)之前的博客:基于第三方QQ授权

QQ第三方授权登录OAuth2.0实现(Java)

准备材料 1.已经备案好的域名 2.服务器(域名和服务器为统一主体或域名已接入服务器) 3.QQ号 4.开发流程:https://wiki.connect.qq.com/%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C_oauth2-0 创建应用 1.访问 https://connect.qq.com/manage.html ,登录. 2.创建网站应用,填写网站基本信息以及平台信息,提交审核.注:网站回调域后续会用到,是点击授权登录时回调地址,需要与后续开发一致. 程序开

django实现github第三方本地登录

1.安装 pip install social-auth-app-django 2.生成Client ID和Client Secret 3.修改setting.py INSTALLED_APPS = [ 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'djan