abp Vnext OpenIddect 扩展微信小程序授权登录

这篇具有很好参考价值的文章主要介绍了abp Vnext OpenIddect 扩展微信小程序授权登录。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

abp Vnext OpenIddect 扩展微信小程序授权登录,ABP VNEXT,微信小程序,.netcore,ABP Vnext,OpenIddict

abp vnext6.0之后官方替换了原来的ids4,采用了openIddict的oauth认证框架。使用之前的方法已经不行,以下是OpenIddect 使用ITokenExtensionGrant接口进行的授权登入扩展,按照以下代码可实现,欢迎交流指正。

新建用于接收微信返回数据字段类

public class Results
{
  /// <summary>
  /// 用户唯一标识
  /// </summary>
  public string openid { get; set; }
  /// <summary>
  /// 会话密钥
  /// </summary>
  public string session_key { get; set; }
  /// <summary>
  /// 用户在开放平台的唯一标识符,若当前小程序已绑定到微信开放平台帐号下会返回
  /// </summary>
  public string unionid { get; set; }
  /// <summary>
  /// 错误码
  /// </summary>
  public int errcode { get; set; }
  /// <summary>
  /// 错误信息
  /// </summary>
  public string  errmsg { get; set; } 
}

在HttpApi.Host新建类

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Text.Json;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.OpenIddict.Controllers;
using Volo.Abp.OpenIddict.ExtensionGrantTypes;

namespace Demo
{
    [IgnoreAntiforgeryToken]
    [ApiExplorerSettings(IgnoreApi = true)]
    public class TokenExtensionGrant : AbpOpenIdDictControllerBase, ITokenExtensionGrant
    {
        protected IOptions<IdentityOptions> IdentityOptions => LazyServiceProvider.LazyGetRequiredService<IOptions<IdentityOptions>>();

        public const string ExtensionGrantName = "wechat_code";
        public string Name => ExtensionGrantName;

        public async Task<IActionResult> HandleAsync(ExtensionGrantContext context)
        {
            LazyServiceProvider = context.HttpContext.RequestServices.GetRequiredService<IAbpLazyServiceProvider>();

            string code = context.Request.GetParameter("code").ToString();
            if (string.IsNullOrEmpty(code))
            {
                return NewForbidResult("code参数为空!");
            }
            var results = GetResults(context, code);

            switch (results.errcode)
            {
                case 0:
                    string providerKey = results.openid;
                    var claimsPrincipal = await ServerValidate(context, "wechat", providerKey);
                    return claimsPrincipal == null ? 
                        RetForbidResult("未绑定微信") 
                        : 
                        SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
                //可以自行根据微信返回错误代码进行相应的错误处理
                default:
                    return NewForbidResult(results.errmsg);
            }
        }
        
        private ForbidResult NewForbidResult(string msg)
        {
            return new ForbidResult(
                new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme },
                GetAuthenticationProperties(msg));
        }

        private AuthenticationProperties GetAuthenticationProperties(string msg)
        {
            return new AuthenticationProperties(new Dictionary<string, string>
            {
                [OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.InvalidRequest,
                [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = msg
            });
        }
        /// <summary>
        /// 服务器验证
        /// </summary>
        /// <param name="context"></param>
        /// <param name="loginProvider"></param>
        /// <param name="providerKey"></param>
        /// <returns></returns>
        private async Task<ClaimsPrincipal> ServerValidate(ExtensionGrantContext context, string loginProvider, string providerKey)
        {
            await IdentityOptions.SetAsync();

            var user = await UserManager.FindByLoginAsync(loginProvider, providerKey);
            if (user == null)
            {
                return null;
            }

            var principal = await SignInManager.CreateUserPrincipalAsync(user);

            var scopes = context.Request.GetScopes();
            principal.SetScopes(scopes);
            var resources = await GetResourcesAsync(scopes);
            principal.SetResources(resources);

            return principal;
        }
        /// <summary>
        /// 根据code得到微信openid
        /// </summary>
        /// <param name="context"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private Results GetResults(ExtensionGrantContext context, string code) 
        {
            string _appid = "WeChat_appId";
            string _secret = "WeChat_secret";

            string url = string.Format(
                        "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", 
                        _appid,
                        _secret,
                        code);
            HttpClient client = new HttpClient();
            HttpResponseMessage response = client.GetAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                string resContent = response.Content.ReadAsStringAsync().Result;
                var results = JsonSerializer.Deserialize<Results>(resContent);
                return results;
            }
            else 
            {
                return new Results { errmsg = "微信接口请求失败" };
            }
        }
    }
}

在HttpApiHostModule.cs 文件中添加注册

使用上面定义的ExtensionGrantName扩展的这个openiddict的认证流程的名字

public override void PreConfigureServices(ServiceConfigurationContext context)
    {
        ///······
        PreConfigure<OpenIddictServerBuilder>(builder =>
        {
            builder.Configure(options =>
            {
                options.GrantTypes.Add(Demo.ExtensionGrantName);
            });
        });
    }

请求地址和参数

host:/connect/token
methon:POST
media type:aplication/x-www-form-urlencoded
body:
	grant_type=wechat_code
	code=微信小程序提供的code
	client_id=自己项目的client_id
	scope=自己项目 openid offline_access

钉钉可参考本文进行OpenIddect 扩展授权登录,欢迎交流指正,谢谢阅读。

参考文章(感谢以下文章和作者):
【Abp vnext 6.0手机号验证码登录】【作者:瓦力】文章来源地址https://www.toymoban.com/news/detail-686192.html

到了这里,关于abp Vnext OpenIddect 扩展微信小程序授权登录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序授权登录流程

    我是IT果果日记,微信公众号请搜索 IT果果日记 一个普通的技术宅,定期分享技术文章,欢迎点赞、关注和转发,请多关照。 首先, 我们要了解什么是微信小程序登录?它的作用是什么? 微信小程序登录是为了让开发者的服务器获取用户的openId以及session_key的令牌。 请不要

    2024年02月14日
    浏览(41)
  • 微信小程序授权登录详细解析

    一、首先在wxml页面定义一个普通按钮,在用bindtap定义一个事件  二、去到js页面,使用wx.getUserProfile获取到用户信息,主要获取微信昵称和微信头像  三、使用wx.login获取code发送请求   四、将code、nickName、avatarUrl传入到后端  五、后端接受到code、用户头像、用户昵称  六、

    2024年02月09日
    浏览(52)
  • 【微信小程序】授权登录流程解析

      目录 微信授权登录流程 1. 官方图示流程详解 2. 代码登录流程拆解 2.1 前端代码示例讲解 2.2 后端代码示例讲解 2.3 代码登录流程拆解 🌟 3. 表情包存储展示(扩展) 附议  ① 微信服务器验证: 当用户打开小程序时,小程序会向用户展示登录按钮,用户点击登录按钮后,小

    2024年02月08日
    浏览(32)
  • UNIAPP---实现微信小程序登录授权和手机号授权(uniapp做微信小程序)

    描述:uniapp开发小程序,先授权用户信息后再出现手机号授权的页面进行手机号授权。完成后返回上一页面并把信息存入后台以及前台缓存中,方便使用。 1.在uniapp的manifest.json进行微信小程序配置 2.封装request请求api.js(如果已封装可跳过) 3.封装微信授权登录以及获取手机

    2024年02月11日
    浏览(32)
  • 微信小程序-授权登录(手机号码)

    template     view class=\\\"work-container\\\"         view class=\\\"login\\\"             view class=\\\"content\\\"                 button class=\\\"button_wx\\\" open-type=\\\"getPhoneNumber\\\" @getphonenumber=\\\"getPhoneNumber\\\"                     u-icon name=\\\"weixin-fill\\\" color=\\\"#FFFFFF\\\" size=\\\"50\\\"/u-icon                     

    2024年02月06日
    浏览(43)
  • 微信小程序授权手机号码登录

    因公司项目需要做微信小程序相关项目,故记录一下相关开发要点。 使用的是binarywang工具包,版本为4.1.0。 后端框架使用springboot 更多其他功能使用推荐查看https://github.com/binarywang/binarywang 3.1 微信小程序开发的相关配置 在application.yml文件中配置 3.2创建配置文件 代码如下(示

    2024年02月09日
    浏览(45)
  • 微信小程序手机号授权登录

    微信小程序,手机号授权登录需求。 大体流程是这样的: 小程序端使用 getPhoneNumber 向微信平台获取授权 通过微信授权后,小程序端接收微信授权后的回调 小程序携带微信的回调请求自己的服务端 服务端请求微信获取手机号并将手机号回调给小程序端 具体步骤和代码如下:

    2024年02月13日
    浏览(40)
  • 微信小程序实现授权登录及退出

    1.登录获取用户昵称,头像 2.创建云函数 右击新建文件夹cloud 在根目录project.config.json中添加: 右击文件夹cloud选择当前环境 右击文件夹cloud新建Node.js云函数,命名login 在新建文件夹login的index.js文件中: 右击login文件夹选择上传并部署:云端安装依赖(不上传node_modules),显

    2024年02月08日
    浏览(45)
  • 新!uniapp微信小程序微信授权登录

     11月后,微信小程序对于微信授权登录做了逻辑上的更改,之前的一键授权获取用户信息的功能已不再适用。已发布审核完成的小程序不受影响,但要想再发布,只能换成新的登陆逻辑了。 首先,要说明的,个人中心页面,未登陆时,应有登陆按钮,最好不要通过路由守卫

    2024年02月09日
    浏览(40)
  • Java - 微信小程序授权手机号登录

            最近做了一个关于商城的项目,B端选用若依的开源框架,C端还是vue前后端分离。其中C端主要是小程序的形式,所以想着来总结一下对接微信小程序登录中Java部分遇到的坑即代码分享! 废话不多说,直接上代码! 1、controller 层代码          入参我这边是直接使用

    2024年02月04日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包