ASP.NET Core中集成微信快捷登录的程序

工具:

Visual Studio 2015 update 3

Asp.Net Core 1.0

1 准备工作

申请微信公众平台接口测试帐号,申请网址:(http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login)。申请接口测试号无需公众帐号,可以直接体验和测试公众平台所有高级接口。

1.1 配置接口信息

1.2 修改网页授权信息

 

点击“修改”后在弹出页面填入你的网站域名:

 

2  新建网站项目

 2.1 选择ASP.NET Core Web Application 模板

 

 

2.2 选择Web 应用程序,并更改身份验证为个人用户账户

 

 

3 集成微信登录功能

3.1添加引用

打开project.json文件,添加引用Microsoft.AspNetCore.Authentication.OAuth

 

3.2 添加代码文件

在项目中新建文件夹,命名为WeChatOAuth,并添加代码文件(本文最后附全部代码)。

 

3.3 注册微信登录中间件

打开Startup.cs文件,在Configure中添加代码:

1
2
3
4
5
app.UseWeChatAuthentication(new WeChatOptions()
{
    AppId = "******",
    AppSecret = "******"
});
注意该代码的插入位置必须在app.UseIdentity()下方。

 

4 代码

 

 1 // Copyright (c) .NET Foundation. All rights reserved.
 2 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 3
 4 using System;
 5 using Microsoft.AspNetCore.Authentication.WeChat;
 6 using Microsoft.Extensions.Options;
 7
 8 namespace Microsoft.AspNetCore.Builder
 9 {
10     /// <summary>
11     /// Extension methods to add WeChat authentication capabilities to an HTTP application pipeline.
12     /// </summary>
13     public static class WeChatAppBuilderExtensions
14     {
15         /// <summary>
16         /// Adds the <see cref="WeChatMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables WeChat authentication capabilities.
17         /// </summary>
18         /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
19         /// <returns>A reference to this instance after the operation has completed.</returns>
20         public static IApplicationBuilder UseWeChatAuthentication(this IApplicationBuilder app)
21         {
22             if (app == null)
23             {
24                 throw new ArgumentNullException(nameof(app));
25             }
26
27             return app.UseMiddleware<WeChatMiddleware>();
28         }
29
30         /// <summary>
31         /// Adds the <see cref="WeChatMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables WeChat authentication capabilities.
32         /// </summary>
33         /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
34         /// <param name="options">A <see cref="WeChatOptions"/> that specifies options for the middleware.</param>
35         /// <returns>A reference to this instance after the operation has completed.</returns>
36         public static IApplicationBuilder UseWeChatAuthentication(this IApplicationBuilder app, WeChatOptions options)
37         {
38             if (app == null)
39             {
40                 throw new ArgumentNullException(nameof(app));
41             }
42             if (options == null)
43             {
44                 throw new ArgumentNullException(nameof(options));
45             }
46
47             return app.UseMiddleware<WeChatMiddleware>(Options.Create(options));
48         }
49     }
50 }

 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace Microsoft.AspNetCore.Authentication.WeChat
{
    public static class WeChatDefaults
    {
        public const string AuthenticationScheme = "WeChat";

        public static readonly string AuthorizationEndpoint = "https://open.weixin.qq.com/connect/oauth2/authorize";

        public static readonly string TokenEndpoint = "https://api.weixin.qq.com/sns/oauth2/access_token";

        public static readonly string UserInformationEndpoint = "https://api.weixin.qq.com/sns/userinfo";
    }
}

 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Authentication.WeChat
{
    internal class WeChatHandler : OAuthHandler<WeChatOptions>
    {
        public WeChatHandler(HttpClient httpClient)
            : base(httpClient)
        {
        }

        protected override async Task<AuthenticateResult> HandleRemoteAuthenticateAsync()
        {
            AuthenticationProperties properties = null;
            var query = Request.Query;

            var error = query["error"];
            if (!StringValues.IsNullOrEmpty(error))
            {
                var failureMessage = new StringBuilder();
                failureMessage.Append(error);
                var errorDescription = query["error_description"];
                if (!StringValues.IsNullOrEmpty(errorDescription))
                {
                    failureMessage.Append(";Description=").Append(errorDescription);
                }
                var errorUri = query["error_uri"];
                if (!StringValues.IsNullOrEmpty(errorUri))
                {
                    failureMessage.Append(";Uri=").Append(errorUri);
                }

                return AuthenticateResult.Fail(failureMessage.ToString());
            }

            var code = query["code"];
            var state = query["state"];
            var oauthState = query["oauthstate"];

            properties = Options.StateDataFormat.Unprotect(oauthState);

            if (state != Options.StateAddition || properties == null)
            {
                return AuthenticateResult.Fail("The oauth state was missing or invalid.");
            }

            // OAuth2 10.12 CSRF
            if (!ValidateCorrelationId(properties))
            {
                return AuthenticateResult.Fail("Correlation failed.");
            }

            if (StringValues.IsNullOrEmpty(code))
            {
                return AuthenticateResult.Fail("Code was not found.");
            }

            //获取tokens
            var tokens = await ExchangeCodeAsync(code, BuildRedirectUri(Options.CallbackPath));

            var identity = new ClaimsIdentity(Options.ClaimsIssuer);

            AuthenticationTicket ticket = null;

            if (Options.WeChatScope == Options.InfoScope)
            {
                //获取用户信息
                ticket = await CreateTicketAsync(identity, properties, tokens);
            }
            else
            {
                //不获取信息,只使用openid
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, tokens.TokenType, ClaimValueTypes.String, Options.ClaimsIssuer));
                ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.AuthenticationScheme);
            }

            if (ticket != null)
            {
                return AuthenticateResult.Success(ticket);
            }
            else
            {
                return AuthenticateResult.Fail("Failed to retrieve user information from remote server.");
            }
        }

       
        /// <summary>
        /// OAuth第一步,获取code
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
        {
            //加密OAuth状态
            var oauthstate = Options.StateDataFormat.Protect(properties);

            //
            redirectUri = $"{redirectUri}?{nameof(oauthstate)}={oauthstate}";

            var queryBuilder = new QueryBuilder()
            {
                { "appid", Options.ClientId },
                { "redirect_uri", redirectUri },
                { "response_type", "code" },
                { "scope", Options.WeChatScope },                
                { "state",  Options.StateAddition },
            };
            return Options.AuthorizationEndpoint + queryBuilder.ToString();
        }

 

        /// <summary>
        /// OAuth第二步,获取token
        /// </summary>
        /// <param name="code"></param>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        protected override  async Task<OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri)
        {
            var tokenRequestParameters = new Dictionary<string, string>()
            {
                { "appid", Options.ClientId },
                { "secret", Options.ClientSecret },
                { "code", code },
                { "grant_type", "authorization_code" },
            };

            var requestContent = new FormUrlEncodedContent(tokenRequestParameters);

            var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint);
            requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            requestMessage.Content = requestContent;
            var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted);
            if (response.IsSuccessStatusCode)
            {
                var payload = JObject.Parse(await response.Content.ReadAsStringAsync());

                string ErrCode = payload.Value<string>("errcode");
                string ErrMsg = payload.Value<string>("errmsg");

                if (!string.IsNullOrEmpty(ErrCode) | !string.IsNullOrEmpty(ErrMsg))
                {
                    return OAuthTokenResponse.Failed(new Exception($"ErrCode:{ErrCode},ErrMsg:{ErrMsg}"));
                }

                var tokens = OAuthTokenResponse.Success(payload);

                //借用TokenType属性保存openid
                tokens.TokenType = payload.Value<string>("openid");

                return tokens;
            }
            else
            {
                var error = "OAuth token endpoint failure";
                return OAuthTokenResponse.Failed(new Exception(error));
            }
        }

        /// <summary>
        /// OAuth第四步,获取用户信息
        /// </summary>
        /// <param name="identity"></param>
        /// <param name="properties"></param>
        /// <param name="tokens"></param>
        /// <returns></returns>
        protected override async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens)
        {
            var queryBuilder = new QueryBuilder()
            {
                { "access_token", tokens.AccessToken },
                { "openid",  tokens.TokenType },//在第二步中,openid被存入TokenType属性
                { "lang", "zh_CN" }
            };

            var infoRequest = Options.UserInformationEndpoint + queryBuilder.ToString();

            var response = await Backchannel.GetAsync(infoRequest, Context.RequestAborted);
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpRequestException($"Failed to retrieve WeChat user information ({response.StatusCode}) Please check if the authentication information is correct and the corresponding WeChat Graph API is enabled.");
            }

            var user = JObject.Parse(await response.Content.ReadAsStringAsync());
            var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.AuthenticationScheme);
            var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, user);

            var identifier = user.Value<string>("openid");
            if (!string.IsNullOrEmpty(identifier))
            {
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identifier, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var nickname = user.Value<string>("nickname");
            if (!string.IsNullOrEmpty(nickname))
            {
                identity.AddClaim(new Claim(ClaimTypes.Name, nickname, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var sex = user.Value<string>("sex");
            if (!string.IsNullOrEmpty(sex))
            {
                identity.AddClaim(new Claim("urn:WeChat:sex", sex, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var country = user.Value<string>("country");
            if (!string.IsNullOrEmpty(country))
            {
                identity.AddClaim(new Claim(ClaimTypes.Country, country, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var province = user.Value<string>("province");
            if (!string.IsNullOrEmpty(province))
            {
                identity.AddClaim(new Claim(ClaimTypes.StateOrProvince, province, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var city = user.Value<string>("city");
            if (!string.IsNullOrEmpty(city))
            {
                identity.AddClaim(new Claim("urn:WeChat:city", city, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var headimgurl = user.Value<string>("headimgurl");
            if (!string.IsNullOrEmpty(headimgurl))
            {
                identity.AddClaim(new Claim("urn:WeChat:headimgurl", headimgurl, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var unionid = user.Value<string>("unionid");
            if (!string.IsNullOrEmpty(unionid))
            {
                identity.AddClaim(new Claim("urn:WeChat:unionid", unionid, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            await Options.Events.CreatingTicket(context);
            return context.Ticket;
        }
    }
}

 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Globalization;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Authentication.WeChat
{
    /// <summary>
    /// An ASP.NET Core middleware for authenticating users using WeChat.
    /// </summary>
    public class WeChatMiddleware : OAuthMiddleware<WeChatOptions>
    {
        /// <summary>
        /// Initializes a new <see cref="WeChatMiddleware"/>.
        /// </summary>
        /// <param name="next">The next middleware in the HTTP pipeline to invoke.</param>
        /// <param name="dataProtectionProvider"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="encoder"></param>
        /// <param name="sharedOptions"></param>
        /// <param name="options">Configuration options for the middleware.</param>
        public WeChatMiddleware(
            RequestDelegate next,
            IDataProtectionProvider dataProtectionProvider,
            ILoggerFactory loggerFactory,
            UrlEncoder encoder,
            IOptions<SharedAuthenticationOptions> sharedOptions,
            IOptions<WeChatOptions> options)
            : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (dataProtectionProvider == null)
            {
                throw new ArgumentNullException(nameof(dataProtectionProvider));
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            if (encoder == null)
            {
                throw new ArgumentNullException(nameof(encoder));
            }

            if (sharedOptions == null)
            {
                throw new ArgumentNullException(nameof(sharedOptions));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (string.IsNullOrEmpty(Options.AppId))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, nameof(Options.AppId)));
            }

            if (string.IsNullOrEmpty(Options.AppSecret))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, nameof(Options.AppSecret)));
            }
        }

        /// <summary>
        /// Provides the <see cref="AuthenticationHandler{T}"/> object for processing authentication-related requests.
        /// </summary>
        /// <returns>An <see cref="AuthenticationHandler{T}"/> configured with the <see cref="WeChatOptions"/> supplied to the constructor.</returns>
        protected override AuthenticationHandler<WeChatOptions> CreateHandler()
        {
            return new WeChatHandler(Backchannel);
        }
    }
}

 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Collections.Generic;
using Microsoft.AspNetCore.Authentication.WeChat;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// Configuration options for <see cref="WeChatMiddleware"/>.
    /// </summary>
    public class WeChatOptions : OAuthOptions
    {
        /// <summary>
        /// Initializes a new <see cref="WeChatOptions"/>.
        /// </summary>
        public WeChatOptions()
        {
            AuthenticationScheme = WeChatDefaults.AuthenticationScheme;
            DisplayName = AuthenticationScheme;
            CallbackPath = new PathString("/signin-wechat");
            StateAddition = "#wechat_redirect";
            AuthorizationEndpoint = WeChatDefaults.AuthorizationEndpoint;
            TokenEndpoint = WeChatDefaults.TokenEndpoint;
            UserInformationEndpoint = WeChatDefaults.UserInformationEndpoint;
            //SaveTokens = true;          

            //BaseScope (不弹出授权页面,直接跳转,只能获取用户openid),
            //InfoScope (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
            WeChatScope = InfoScope;
        }

        // WeChat uses a non-standard term for this field.
        /// <summary>
        /// Gets or sets the WeChat-assigned appId.
        /// </summary>
        public string AppId
        {
            get { return ClientId; }
            set { ClientId = value; }
        }

        // WeChat uses a non-standard term for this field.
        /// <summary>
        /// Gets or sets the WeChat-assigned app secret.
        /// </summary>
        public string AppSecret
        {
            get { return ClientSecret; }
            set { ClientSecret = value; }
        }

        public string StateAddition { get; set; }
        public string WeChatScope { get; set; }

        public string BaseScope = "snsapi_base";

        public string InfoScope = "snsapi_userinfo";
    }
}

时间: 2024-08-01 08:57:07

ASP.NET Core中集成微信快捷登录的程序的相关文章

ASP.NET Core中的依赖注入(4): 构造函数的选择与服务生命周期管理

ServiceProvider最终提供的服务实例都是根据对应的ServiceDescriptor创建的,对于一个具体的ServiceDescriptor对象来说,如果它的ImplementationInstance和ImplementationFactory属性均为Null,那么ServiceProvider最终会利用其ImplementationType属性返回的真实类型选择一个适合的构造函数来创建最终的服务实例.我们知道服务服务的真实类型可以定义了多个构造函数,那么ServiceProvid

ASP.NET Core中的依赖注入(1):控制反转(IoC)

ASP.NET Core在启动以及后续针对每个请求的处理过程中的各个环节都需要相应的组件提供相应的服务,为了方便对这些组件进行定制,ASP.NET通过定义接口的方式对它们进行了"标准化",我们将这些标准化的组件称为服务,ASP.NET在内部专门维护了一个DI容器来提供所需的服务.要了解这个DI容器以及现实其中的服务提供机制,我们先得知道什么是DI(Dependence Injection),而一旦我们提到DI,又不得不说IoC(Inverse of Control). 目录 一.流程控

ASP.NET Core中的依赖注入(2):依赖注入(DI)

IoC主要体现了这样一种设计思想:通过将一组通用流程的控制从应用转移到框架之中以实现对流程的复用,同时采用"好莱坞原则"是应用程序以被动的方式实现对流程的定制.我们可以采用若干设计模式以不同的方式实现IoC,比如我们在上面介绍的模板方法.工厂方法和抽象工厂,接下来我们介绍一种更为有价值的IoC模式,即依赖注入(DI:Dependency Injection,以下简称DI). 目录 一.由外部容器提供服务对象 二.三种依赖注入方式     构造器注入     属性注入     方法注入

ASP.NET Core中的依赖注入(5):ServicePrvider实现揭秘【补充漏掉的细节】

到目前为止,我们定义的ServiceProvider已经实现了基本的服务提供和回收功能,但是依然漏掉了一些必需的细节特性.这些特性包括如何针对IServiceProvider接口提供一个ServiceProvider对象,何创建ServiceScope,以及如何提供一个服务实例的集合. 一.提供一个ServiceProvider对象 我们知道当将服务类型指定为IServiceProvider接口并调用ServiceProvider的GetService方法是,ServiceProvider对象本

ASP.NET Core中的依赖注入(3): 服务的注册与提供

在采用了依赖注入的应用中,我们总是直接利用DI容器直接获取所需的服务实例,换句话说,DI容器起到了一个服务提供者的角色,它能够根据我们提供的服务描述信息提供一个可用的服务对象.ASP.NET Core中的DI容器体现为一个实现了IServiceProvider接口的对象. ServiceProvider与ServiceDescriptor 服务的注册与提供     利用ServiceProvider来提供服务     提供一个服务实例的集合     获取ServiceProvider自身对象  

ASP.NET Core 中的依赖注入 [共7篇]

一.控制反转(IoC) ASP.NET Core在启动以及后续针对每个请求的处理过程中的各个环节都需要相应的组件提供相应的服务,为了方便对这些组件进行定制,ASP.NET通过定义接口的方式对它们进行了"标准化",我们将这些标准化的组件称为服务,ASP.NET在内部专门维护了一个DI容器来提供所需的服务.要了解这个DI容器以及现实其中的服务提供机制,我们先得知道什么是DI(Dependence Injection),而一旦我们提到DI,又不得不说IoC(Inverse of Contro

浅谈如何在ASP.NET Core中实现一个基础的身份认证_实用技巧

ASP.NET终于可以跨平台了,但是不是我们常用的ASP.NET, 而是叫一个ASP.NET Core的新平台,他可以跨Windows, Linux, OS X等平台来部署你的web应用程序,你可以理解为,这个框架就是ASP.NET的下一个版本,相对于传统ASP.NET程序,它还是有一些不同的地方的,比如很多类库在这两个平台之间是不通用的. 今天首先我们在ASP.NET Core中来实现一个基础的身份认证,既登陆功能. 前期准备: 1.推荐使用 VS 2015 Update3 作为你的IDE,下

谈谈如何在ASP.NET Core中实现CORS跨域_实用技巧

CORS(Cross-origin resource sharing)是一个W3C标准,翻译过来就是 "跨域资源共享",它主要是解决Ajax跨域限制的问题. CORS需要浏览器和服务器支持,现在所有现代浏览器都支持这一特性.注:IE10及以上 只要浏览器支持,其实CORS所有的配置都是在服务端进行的,而前端的操作浏览器会自动完成. 在本例中,将演示如何再ASP.NET Core中实现CORS跨域. 前期准备 你需要windows系统. 你需要安装IIS. 推荐使用VS2015 Upda

详解如何在ASP.NET Core中应用Entity Framework_实用技巧

首先为大家提醒一点,.NET Core和经典.NET Framework的Library是不通用的,包括Entity Framework! 哪怎么办? 别急,微软为.NET Core发布了.NET Core版本的Entity Framework,具体配置方法与经典.NET Framework版本的稍有区别,下面的内容就为带领大家在ASP.NET Core中应用Entity Framework DB first. 注:目前部分工具处于Preview版本,正式版本可能会稍有区别.  前期准备: 1.