ASP.NET Core集成微信登錄

来源:http://www.cnblogs.com/early-moon/archive/2016/08/29/5819760.html
-Advertisement-
Play Games

工具: Visual Studio 2015 update 3 Asp.Net Core 1.0 1 準備工作 申請微信公眾平臺介面測試帳號,申請網址:(http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login)。申請介面測試號無需公 ...


工具:

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中添加代碼:

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 }
WeChatAppBuilderExtensions.cs
// 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";
    }
}
WeChatDefaults.cs
// 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;
        }
    }
}
WeChatHandler.cs
// 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);
        }
    }
}
WeChatMiddleware.cs
// 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";
    }
}
WeChatOptions.cs

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在javascript中,像原型,閉包這樣的概念,只要我們能領悟其中的原理,一切都會顯得格外清晰與明瞭。 原型屬性(prototype): 下麵我們簡單定義一個函數 在這些函數一定義就被賦予的屬性中,就包括prototype屬性,她的初始化是一個空對象: 當然我們也可以自己添加該屬性: 而且我們可以 ...
  • 效果: ...
  • js中的NaN不和任何值相等,包括自身。 所以可以使用x!=x來判斷x是否是NaN,當且僅當x為NaN時,表達式的結果為true。 可以依此刪除數組中的'NaN'。 ...
  • $("cli-open").click(function(){ var scrollTop = document.body.scrollTop;//保存點擊前滾動條的位置 window.onscroll=function(){ document.body.scrollTop = scrollTop; ...
  • 需要給剛體添加一個自定義的屬性:m_customGravity,這樣就可以動態的修改每一個剛體自定義的重力,查找box2d源碼大約在5486行,加上紅色的一句代碼 使用的方法://創建一個圓形剛體var circle = new Circle({x:mousePoint.x,y:mousePoint ...
  • 不啰嗦上代碼: 怎麼調用不用我說了吧,看返回的4個方法: addTranEvent,addAnimEvent,removeAnimEvent,setStyleAttribute ...
  • 第二版 (-1)寫在前面 本文不是要詳細說明Validation插件的使用,而是將滿足開發需求的代碼已最應該使用的方式寫出來,並附有詳細的註釋 想要瞭解更多,去jquery的官網,有最新,最全面的,後續可能會寫怎麼從jquery官網獲得信息的博文 (0)資源配置 官網的jar包: lib 有該插件所 ...
  • 如何簡單相容性的實現父元素是半透明背景色,而子元素不受影響。 相容所有瀏覽器的背景顏色半透明CSS代碼: 註意:startColorStr 和 endColorStr 的值,前兩位是十六進位的透明度,後面六位是十六進位的顏色。 其格式為 #AARRGGBB 。 AA 、 RR 、 GG 、 BB 為 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...