├── .gitattributes
├── .github
├── dependabot.yml
└── workflows
│ ├── build-and-test.yml
│ ├── pack-and-publish.yml
│ ├── publish.yml
│ └── test.yml
├── .gitignore
├── Changelog.md
├── Directory.Build.props
├── Directory.Build.targets
├── LICENSE.txt
├── README.md
├── WeixinAuth.sln
├── delete_all_bin_and_obj.cmd
├── global.json
├── src
└── WeixinAuth
│ ├── Apis
│ ├── IWeixinAuthApi.cs
│ └── WeixinAuthApi.cs
│ ├── ClaimActions
│ ├── ClaimActionCollectionMapExtensions.cs
│ └── JsonKeyArrayClaimAction.cs
│ ├── Extensions
│ ├── AuthenticationPropertiesExtensions.cs
│ ├── ClaimsExtensions.cs
│ ├── JsonDocumentAuthExtensions.cs
│ ├── LoggingExtensions.cs
│ └── OAuthTokenResponseExtensions.cs
│ ├── Helpers
│ ├── CompressionExtensions.cs
│ ├── WeixinAuthAuthenticationPropertiesHelper.cs
│ ├── WeixinAuthHandlerHelper.cs
│ └── Zipper.cs
│ ├── WeixinAuth.csproj
│ ├── WeixinAuthAuthenticationBuilderExtensions.cs
│ ├── WeixinAuthClaimTypes.cs
│ ├── WeixinAuthDefaults.cs
│ ├── WeixinAuthHandler.cs
│ ├── WeixinAuthLanguageCodes.cs
│ ├── WeixinAuthOptions.cs
│ ├── WeixinAuthPostConfigureOptions.cs
│ ├── WeixinAuthScopes.cs
│ └── WeixinAuthenticationTokenNames.cs
└── test
└── WeixinAuth.UnitTest
├── TestServers
├── TestExtensions.cs
├── TestHandlers.cs
├── TestHttpMessageHandler.cs
├── TestServerBuilder.cs
└── TestTransaction.cs
├── WeixinAuth.UnitTest.csproj
└── WeixinAuthTests.cs
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | #* text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
5 |
6 | version: 2
7 | updates:
8 | - package-ecosystem: "github-actions"
9 | # Look for workflow files stored in the default location of `/.github/workflows`
10 | directory: "/"
11 | schedule:
12 | interval: "weekly"
13 |
14 | - package-ecosystem: "nuget"
15 | directories:
16 | - "/src/*"
17 | - "/test/*"
18 | schedule:
19 | interval: "weekly"
20 |
--------------------------------------------------------------------------------
/.github/workflows/build-and-test.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a .NET project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net
3 |
4 | name: build-and-test (reusable workflow)
5 |
6 | on:
7 | workflow_call:
8 | inputs:
9 | dotnet-version:
10 | description: "required dotnet version. The default is '8.0.x'."
11 | required: true
12 | type: string
13 | default: '8.0.x'
14 | dotnet-framework:
15 | description: "target framework for dotnet test. The default is 'net8.0'."
16 | required: true
17 | type: string
18 | default: 'net8.0'
19 | configuration:
20 | description: "The configuration to use for building the package. The default is 'Release'."
21 | required: true
22 | type: string
23 | default: 'Release'
24 |
25 | jobs:
26 | build-and-test:
27 | runs-on: ubuntu-latest
28 | env:
29 | NUGET_PACKAGES: ${{ github.workspace }}/.nuget/packages
30 | steps:
31 | - run: echo "The inputs.dotnet version is ${{ inputs.dotnet-version }}, framework is ${{ inputs.dotnet-framework }}."
32 | - run: echo "The inputs.configuration is ${{ inputs.configuration }}."
33 | - run: echo "The job was automatically triggered by a ${{ github.event_name }} event."
34 | - run: echo "This job is now running on a ${{ runner.os }} server hosted by GitHub!"
35 | - run: echo "The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}."
36 |
37 | - name: Check out repository code
38 | uses: actions/checkout@v4
39 | - run: echo "The ${{ github.repository }} repository has been cloned to the runner."
40 | - run: echo "The workflow is now ready to test your code on the runner."
41 | - name: List files in the repository
42 | run: |
43 | ls -la ${{ github.workspace }}
44 |
45 | - name: Setup dotnet
46 | uses: actions/setup-dotnet@v4
47 | with:
48 | dotnet-version: ${{ inputs.dotnet-version }}
49 | global-json-file: global.json
50 | cache: false
51 | - name: Display dotnet version
52 | run: dotnet --version
53 |
54 | - name: Install dependencies
55 | run: dotnet restore
56 | - name: Build
57 | run: dotnet build --no-restore --configuration ${{ inputs.configuration }}
58 |
59 | - name: Test with the dotnet CLI
60 | run: dotnet test --no-build --framework ${{ inputs.dotnet-framework }} --configuration ${{ inputs.configuration }} --verbosity normal --logger trx --results-directory "TestResults-${{ inputs.configuration }}-${{ inputs.dotnet-framework }}"
61 | - name: Upload dotnet test results
62 | uses: actions/upload-artifact@v4
63 | with:
64 | name: dontet-results-${{ inputs.configuration }}-${{ inputs.dotnet-framework }}
65 | path: TestResults-${{ inputs.configuration }}-${{ inputs.dotnet-framework }}
66 | if: ${{ always() }}
67 |
68 | - run: echo "This job's status is ${{ job.status }}."
69 |
--------------------------------------------------------------------------------
/.github/workflows/pack-and-publish.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a .NET project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net
3 |
4 | name: pack-and-publish (reusable workflow)
5 |
6 | on:
7 | workflow_call:
8 | secrets:
9 | NUGET_TOKEN:
10 | description: 'A nuget token to publish to nuget.org'
11 | required: true
12 |
13 | jobs:
14 | pack-and-publish:
15 | runs-on: ubuntu-latest
16 | env:
17 | NUGET_PACKAGES: ${{ github.workspace }}/.nuget/packages
18 | CONFIGURATION: 'Release'
19 | steps:
20 | - run: echo "The job was automatically triggered by a ${{ github.event_name }} event."
21 | - run: echo "This job is now running on a ${{ runner.os }} server hosted by GitHub!"
22 | - run: echo "The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}."
23 |
24 | - name: Check out repository code
25 | uses: actions/checkout@v4
26 | - run: echo "The ${{ github.repository }} repository has been cloned to the runner."
27 | - run: echo "The workflow is now ready to pack your code on the runner."
28 | - name: List files in the repository
29 | run: |
30 | ls -la ${{ github.workspace }}
31 |
32 | - name: Setup dotnet
33 | uses: actions/setup-dotnet@v4
34 | with:
35 | global-json-file: global.json
36 | cache: false
37 | - name: Display dotnet version
38 | run: dotnet --version
39 |
40 | - name: Install dependencies
41 | run: dotnet restore
42 | - name: Build
43 | run: dotnet build --no-restore --configuration ${{ env.CONFIGURATION }}
44 |
45 | - name: Create the NuGet package (.nupkg)
46 | run: dotnet pack --configuration Release
47 | - name: Publish the NuGet package to nuget.org
48 | run: dotnet nuget push "**/bin/Release/*.nupkg" -k $NUGET_AUTH_TOKEN -s https://api.nuget.org/v3/index.json --skip-duplicate
49 | env:
50 | NUGET_AUTH_TOKEN: ${{ secrets.NUGET_TOKEN }}
51 | # You should create this repository secret on https://github.com/myvas/AspNetCore.Email/settings/secrets/actions
52 |
53 | - run: echo "This job's status is ${{ job.status }}."
54 |
55 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | # This workflow will publish NuGet packages to nuget.org
2 | # For more information see: https://docs.github.com/en/actions/use-cases-and-examples/publishing-packages/about-packaging-with-github-actions
3 |
4 | name: publish
5 |
6 | on:
7 | workflow_dispatch:
8 | release:
9 | types: [ published ]
10 |
11 | jobs:
12 | build-and-test:
13 | strategy:
14 | matrix:
15 | dotnet:
16 | - version: '6.0.x'
17 | framework: 'net6.0'
18 | - version: '7.0.x'
19 | framework: 'net7.0'
20 | - version: '8.0.x'
21 | framework: 'net8.0'
22 | - version: '9.0.x'
23 | framework: 'net9.0'
24 | configuration: [ 'Release' ]
25 | uses: ./.github/workflows/build-and-test.yml
26 | with:
27 | dotnet-version: ${{ matrix.dotnet.version }}
28 | dotnet-framework: ${{ matrix.dotnet.framework }}
29 | configuration: ${{ matrix.configuration }}
30 |
31 | pack-and-publish:
32 | needs: [ 'build-and-test' ]
33 | uses: ./.github/workflows/pack-and-publish.yml
34 | secrets:
35 | NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }}
36 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a .NET project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net
3 |
4 | name: test
5 | on:
6 | workflow_dispatch:
7 | push:
8 | branches: [ master ]
9 | paths-ignore:
10 | - "*.md"
11 | - ".github/**"
12 | pull_request:
13 | branches: [ master ]
14 | paths-ignore:
15 | - "*.md"
16 | - ".github/**"
17 |
18 | jobs:
19 | build-and-test:
20 | strategy:
21 | matrix:
22 | dotnet:
23 | - version: '6.0.x'
24 | framework: 'net6.0'
25 | - version: '7.0.x'
26 | framework: 'net7.0'
27 | - version: '8.0.x'
28 | framework: 'net8.0'
29 | - version: '9.0.x'
30 | framework: 'net9.0'
31 | configuration: [ 'Debug', 'Release' ]
32 | uses: ./.github/workflows/build-and-test.yml
33 | with:
34 | dotnet-version: ${{ matrix.dotnet.version }}
35 | dotnet-framework: ${{ matrix.dotnet.framework }}
36 | configuration: ${{ matrix.configuration }}
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | **/logs/
2 | **/bower_components/
3 | **/wwwroot/lib/
4 | **/wwwroot/js/*.min.js
5 | **/wwwroot/js/*.min.css
6 |
7 | ## Ignore Visual Studio temporary files, build results, and
8 | ## files generated by popular Visual Studio add-ons.
9 |
10 | # User-specific files
11 | *.suo
12 | *.user
13 | *.userosscache
14 | *.sln.docstates
15 |
16 | # User-specific files (MonoDevelop/Xamarin Studio)
17 | *.userprefs
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | build/
27 | bld/
28 | [Bb]in/
29 | [Oo]bj/
30 |
31 | # Visual Studio 2015 cache/options directory
32 | .vs/
33 |
34 | # MSTest test Results
35 | [Tt]est[Rr]esult*/
36 | [Bb]uild[Ll]og.*
37 |
38 | # NUNIT
39 | *.VisualState.xml
40 | TestResult.xml
41 |
42 | # Build Results of an ATL Project
43 | [Dd]ebugPS/
44 | [Rr]eleasePS/
45 | dlldata.c
46 |
47 | # DNX
48 | project.lock.json
49 | artifacts/
50 |
51 | *_i.c
52 | *_p.c
53 | *_i.h
54 | *.ilk
55 | *.meta
56 | *.obj
57 | *.pch
58 | *.pdb
59 | *.pgc
60 | *.pgd
61 | *.rsp
62 | *.sbr
63 | *.tlb
64 | *.tli
65 | *.tlh
66 | *.tmp
67 | *.tmp_proj
68 | *.log
69 | *.vspscc
70 | *.vssscc
71 | .builds
72 | *.pidb
73 | *.svclog
74 | *.scc
75 |
76 | # Chutzpah Test files
77 | _Chutzpah*
78 |
79 | # Visual C++ cache files
80 | ipch/
81 | *.aps
82 | *.ncb
83 | *.opendb
84 | *.opensdf
85 | *.sdf
86 | *.cachefile
87 |
88 | # Visual Studio profiler
89 | *.psess
90 | *.vsp
91 | *.vspx
92 | *.sap
93 |
94 | # TFS 2012 Local Workspace
95 | $tf/
96 |
97 | # Guidance Automation Toolkit
98 | *.gpState
99 |
100 | # ReSharper is a .NET coding add-in
101 | _ReSharper*/
102 | *.[Rr]e[Ss]harper
103 | *.DotSettings.user
104 |
105 | # JustCode is a .NET coding add-in
106 | .JustCode
107 |
108 | # TeamCity is a build add-in
109 | _TeamCity*
110 |
111 | # DotCover is a Code Coverage Tool
112 | *.dotCover
113 |
114 | # NCrunch
115 | _NCrunch_*
116 | .*crunch*.local.xml
117 | nCrunchTemp_*
118 |
119 | # MightyMoose
120 | *.mm.*
121 | AutoTest.Net/
122 |
123 | # Web workbench (sass)
124 | .sass-cache/
125 |
126 | # Installshield output folder
127 | [Ee]xpress/
128 |
129 | # DocProject is a documentation generator add-in
130 | DocProject/buildhelp/
131 | DocProject/Help/*.HxT
132 | DocProject/Help/*.HxC
133 | DocProject/Help/*.hhc
134 | DocProject/Help/*.hhk
135 | DocProject/Help/*.hhp
136 | DocProject/Help/Html2
137 | DocProject/Help/html
138 |
139 | # Click-Once directory
140 | publish/
141 |
142 | # Publish Web Output
143 | *.[Pp]ublish.xml
144 | *.azurePubxml
145 | # TODO: Comment the next line if you want to checkin your web deploy settings
146 | # but database connection strings (with potential passwords) will be unencrypted
147 | *.pubxml
148 | *.publishproj
149 |
150 | # NuGet Packages
151 | *.nupkg
152 | # The packages folder can be ignored because of Package Restore
153 | **/packages/*
154 | # except build/, which is used as an MSBuild target.
155 | !**/packages/build/
156 | # Uncomment if necessary however generally it will be regenerated when needed
157 | #!**/packages/repositories.config
158 |
159 | # Microsoft Azure Build Output
160 | csx/
161 | *.build.csdef
162 |
163 | # Microsoft Azure Emulator
164 | ecf/
165 | rcf/
166 |
167 | # Microsoft Azure ApplicationInsights config file
168 | ApplicationInsights.config
169 |
170 | # Windows Store app package directory
171 | AppPackages/
172 | BundleArtifacts/
173 |
174 | # Visual Studio cache files
175 | # files ending in .cache can be ignored
176 | *.[Cc]ache
177 | # but keep track of directories ending in .cache
178 | !*.[Cc]ache/
179 |
180 | # Others
181 | ClientBin/
182 | ~$*
183 | *~
184 | *.dbmdl
185 | *.dbproj.schemaview
186 | *.pfx
187 | *.publishsettings
188 | node_modules/
189 | orleans.codegen.cs
190 |
191 | # RIA/Silverlight projects
192 | Generated_Code/
193 |
194 | # Backup & report files from converting an old project file
195 | # to a newer Visual Studio version. Backup files are not needed,
196 | # because we have git ;-)
197 | _UpgradeReport_Files/
198 | Backup*/
199 | UpgradeLog*.XML
200 | UpgradeLog*.htm
201 |
202 | # SQL Server files
203 | *.mdf
204 | *.ldf
205 |
206 | # Business Intelligence projects
207 | *.rdl.data
208 | *.bim.layout
209 | *.bim_*.settings
210 |
211 | # Microsoft Fakes
212 | FakesAssemblies/
213 |
214 | # GhostDoc plugin setting file
215 | *.GhostDoc.xml
216 |
217 | # Node.js Tools for Visual Studio
218 | .ntvs_analysis.dat
219 |
220 | # Visual Studio 6 build log
221 | *.plg
222 |
223 | # Visual Studio 6 workspace options file
224 | *.opt
225 |
226 | # Visual Studio LightSwitch build output
227 | **/*.HTMLClient/GeneratedArtifacts
228 | **/*.DesktopClient/GeneratedArtifacts
229 | **/*.DesktopClient/ModelManifest.xml
230 | **/*.Server/GeneratedArtifacts
231 | **/*.Server/ModelManifest.xml
232 | _Pvt_Extensions
233 |
234 | # Paket dependency manager
235 | .paket/paket.exe
236 |
237 | # FAKE - F# Make
238 | .fake/
--------------------------------------------------------------------------------
/Changelog.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## 9.0.0 (2024-12-06)
4 | - Added target framework: net9.0
5 |
6 | ## 8.0.0 (2023-11-17)
7 | - Added target framework: net8.0
8 | - Added GitHub actions to test and deploy.
9 |
10 | ## 7.0.11 (2023-09-15)
11 | - Added target framework: net7.0
12 |
13 | ## 6.0.3
14 | - Update to net6.0
15 |
16 | ## 2.1.505 (2019-03-27)
17 | - Update to dotnet-sdk-2.1.505
18 |
19 | ## 2.1.504 (2019-03-09)
20 | - Update to dotnet-sdk-2.1.504
21 |
22 | ## 2.1.412 (2018-10-12)
23 | - Fix [state-128-bytes-limitation-problem](https://github.com/myvas/AspNetCore.Authentication/issues/2) in WeixinAuth
24 |
25 | ## 2.1.408 (2018-10-10)
26 | - Add new 3 unit tests.
27 |
28 | ## 2.1.406 (2018-10-08)
29 | - Update to dotnet-sdk-2.1.403
30 | - Split WeixinOAuth into [WeixinOpen](https://github.com/myvas/AspNetcore.Authentication.WeixnOpen) and [WeixinAuth](https://github.com/myvas/AspNetCore.Authentication.WeixinAuth)
31 | - Add new feature [QQConnect](https://github.com/myvas/AspNetcore.Authentication.QQConnect)
32 |
33 | ## 2.1.301 (2018-06-12)
34 | - Update to dotnet-sdk-2.1.300
35 |
36 | ## 2.0.0-beta-11203 (2017-12-03)
37 | - Use [ViewDivert](https://github.com/myvas/AspNetCore.ViewDivert) in Demo to adapt MicroMessenger browser to its dedicated views
38 |
39 | ## 2.0.0-alpha-71117 (2017-11-19)
40 | - Update to aspnetcore 2.0
41 |
42 | ## 1.1.1-alpha-70325 (2017-03-26)
43 | - Initial release
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | https://github.com/myvas/AspNetCore.Authentication.WeixinAuth
4 | git
5 | latest
6 | Myvas.AspNetCore.Authentication
7 | © $([System.DateTime]::Now.Year) Myvas Foundation
8 |
9 |
10 |
11 | 9.0
12 | v
13 | alpha
14 | false
15 | true
16 |
17 |
18 |
19 | $(MinVerMajor).$(MinVerMinor).$(MinVerPatch).$([System.DateTime]::Now.AddYears(-2021).ToString("yMMdd"))
20 |
21 |
22 |
23 |
24 | $(MSBuildThisFileDirectory)
25 |
26 |
27 |
28 |
29 | none
30 | false
31 |
32 |
33 |
39 |
40 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/Directory.Build.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2025 Myvas Foundation
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Myvas.AspNetCore.Authentication Family
2 |
3 | * QQConnect: [Here](https://github.com/myvas/AspNetCore.Authentication.QQConnect)
4 |
5 | [](https://github.com/myvas/AspNetCore.Authentication.QQConnect)
6 | [](https://github.com/myvas/AspNetCore.Authentication.QQConnect/actions/workflows/test.yml)
7 | [](https://github.com/myvas/AspNetCore.Authentication.QQConnect/actions/workflows/publish.yml)
8 | [](https://www.nuget.org/packages/Myvas.AspNetCore.Authentication.QQConnect)
9 |
10 | * WeixinOpen: [Here](https://github.com/myvas/AspNetCore.Authentication.WeixinOpen)
11 |
12 | [](https://github.com/myvas/AspNetCore.Authentication.WeixinOpen)
13 | [](https://github.com/myvas/AspNetCore.Authentication.WeixinOpen/actions/workflows/test.yml)
14 | [](https://github.com/myvas/AspNetCore.Authentication.WeixinOpen/actions/workflows/publish.yml)
15 | [](https://www.nuget.org/packages/Myvas.AspNetCore.Authentication.WeixinOpen)
16 |
17 | * WeixinAuth: _this repo_
18 |
19 | [](https://github.com/myvas/AspNetCore.Authentication.WeixinAuth)
20 | [](https://github.com/myvas/AspNetCore.Authentication.WeixinAuth/actions/workflows/test.yml)
21 | [](https://github.com/myvas/AspNetCore.Authentication.WeixinAuth/actions/workflows/publish.yml)
22 | [](https://www.nuget.org/packages/Myvas.AspNetCore.Authentication.WeixinAuth)
23 |
24 |
25 | # What's this?
26 | An ASP.NET Core authentication middleware for https://mp.weixin.qq.com (微信公众平台/网页授权登录)
27 | * 须微信公众平台(mp.weixin.qq.com)已认证的服务号(或测试号)。
28 | * 用户可在微信客户端访问网站时自动登入网站。换而言之,用户在微信客户端中访问网页时,可以通过此组件Challenge获取用户的OpenId或UnionId,据此可以识别用户。
29 |
30 | # How to Use?
31 | ## 0.Create account
32 | (1)在微信公众平台(https://mp.weixin.qq.com)上创建账号。
33 |
34 | 微信公众平台/网页授权获取用户信息,须在微信公众平台(mp.weixin.qq.com)上开通服务号,并认证。
35 | ___注意:订阅号无网页授权权限,即使是已认证的订阅号也不行!___
36 |
37 | (2)配置功能权限:微信公众平台-已认证服务号/开发/接口权限/...
38 | - 开通功能:网页服务/网页授权获取用户基本信息。
39 | - 设置网页授权域名:例如,auth.myvas.com。
40 | - 将文件MP_verify_xxxxxxxxx.txt上传至`wwwroot`目录下。
41 |
42 | (3)当然,也可以在公众平台测试号上测试:微信公众平台-测试账号/开发/开发者工具/公众平台测试号/...
43 | - 开通功能:网页服务/网页授权获取用户基本信息。
44 | - 设置授权回调页面域名:例如,auth.myvas.com。
45 |
46 | ## 1.nuget
47 | * [Myvas.AspNetCore.Authentication.WeixinAuth](https://www.nuget.org/packages/Myvas.AspNetCore.Authentication.WeixinAuth)
48 |
49 | ## 2.Configure
50 | ```csharp
51 | app.UseAuthentication();
52 | ```
53 |
54 |
55 | ## 3.ConfigureServices
56 | ```csharp
57 | services.AddAuthentication()
58 | // using Myvas.AspNetCore.Authentication;
59 | .AddWeixinAuth(options =>
60 | {
61 | options.AppId = Configuration["WeixinAuth:AppId"];
62 | options.AppSecret = Configuration["WeixinAuth:AppSecret"];
63 |
64 | options.SilentMode = false; // default is true
65 | };
66 | ```
67 |
68 |
69 | ```
70 | 说明:
71 | (1)同一用户在同一微信公众号即使重复多次订阅/退订,其OpenId也不会改变。
72 | (2)同一用户在不同微信公众号中的OpenId是不一样的。
73 | (3)若同时运营了多个微信公众号,可以在微信开放平台上开通开发者账号,并在“管理中心/公众账号”中将这些公众号添加进去,就可以获取到同一用户在这些公众号中保持一致的UnionId。
74 | ```
75 |
76 | # Dev
77 | * [Visual Studio 2022](https://visualstudio.microsoft.com)
78 | * [.NET 9.0, 8.0, 7.0, 6.0, 5.0, 3.1](https://dotnet.microsoft.com/en-us/download/dotnet)
79 | * [微信开发者工具](https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/download.html)
80 |
81 | # Demo
82 | * [Here](https://demo.auth.myvas.com)
83 |
--------------------------------------------------------------------------------
/WeixinAuth.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.1.32319.34
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{672FEA18-F072-4549-9C4C-DBD1F9CDC7BB}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_", "_", "{E9754587-13F5-4E3A-9F3F-71C98EF97990}"
9 | ProjectSection(SolutionItems) = preProject
10 | .gitignore = .gitignore
11 | Changelog.md = Changelog.md
12 | delete_all_bin_and_obj.cmd = delete_all_bin_and_obj.cmd
13 | Directory.Build.props = Directory.Build.props
14 | Directory.Build.targets = Directory.Build.targets
15 | global.json = global.json
16 | LICENSE.txt = LICENSE.txt
17 | README.md = README.md
18 | EndProjectSection
19 | EndProject
20 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{73FCFCF4-3A1C-4D4D-939A-9CABDC2341DC}"
21 | EndProject
22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WeixinAuth", "src\WeixinAuth\WeixinAuth.csproj", "{009C886C-3B18-44F3-8509-5EAF6731E276}"
23 | EndProject
24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WeixinAuth.UnitTest", "test\WeixinAuth.UnitTest\WeixinAuth.UnitTest.csproj", "{94ABBE67-3755-4DD1-A25E-2407FB32C60E}"
25 | EndProject
26 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
27 | ProjectSection(SolutionItems) = preProject
28 | .github\workflows\build-and-test.yml = .github\workflows\build-and-test.yml
29 | .github\dependabot.yml = .github\dependabot.yml
30 | .github\workflows\pack-and-publish.yml = .github\workflows\pack-and-publish.yml
31 | .github\workflows\publish.yml = .github\workflows\publish.yml
32 | .github\workflows\test.yml = .github\workflows\test.yml
33 | EndProjectSection
34 | EndProject
35 | Global
36 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
37 | Debug|Any CPU = Debug|Any CPU
38 | Release|Any CPU = Release|Any CPU
39 | EndGlobalSection
40 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
41 | {009C886C-3B18-44F3-8509-5EAF6731E276}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
42 | {009C886C-3B18-44F3-8509-5EAF6731E276}.Debug|Any CPU.Build.0 = Debug|Any CPU
43 | {009C886C-3B18-44F3-8509-5EAF6731E276}.Release|Any CPU.ActiveCfg = Release|Any CPU
44 | {009C886C-3B18-44F3-8509-5EAF6731E276}.Release|Any CPU.Build.0 = Release|Any CPU
45 | {94ABBE67-3755-4DD1-A25E-2407FB32C60E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
46 | {94ABBE67-3755-4DD1-A25E-2407FB32C60E}.Debug|Any CPU.Build.0 = Debug|Any CPU
47 | {94ABBE67-3755-4DD1-A25E-2407FB32C60E}.Release|Any CPU.ActiveCfg = Release|Any CPU
48 | {94ABBE67-3755-4DD1-A25E-2407FB32C60E}.Release|Any CPU.Build.0 = Release|Any CPU
49 | EndGlobalSection
50 | GlobalSection(SolutionProperties) = preSolution
51 | HideSolutionNode = FALSE
52 | EndGlobalSection
53 | GlobalSection(NestedProjects) = preSolution
54 | {009C886C-3B18-44F3-8509-5EAF6731E276} = {672FEA18-F072-4549-9C4C-DBD1F9CDC7BB}
55 | {94ABBE67-3755-4DD1-A25E-2407FB32C60E} = {73FCFCF4-3A1C-4D4D-939A-9CABDC2341DC}
56 | {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} = {E9754587-13F5-4E3A-9F3F-71C98EF97990}
57 | EndGlobalSection
58 | GlobalSection(ExtensibilityGlobals) = postSolution
59 | SolutionGuid = {2AEDFD1F-BBE1-4727-9978-2FB04DCE84AF}
60 | EndGlobalSection
61 | EndGlobal
62 |
--------------------------------------------------------------------------------
/delete_all_bin_and_obj.cmd:
--------------------------------------------------------------------------------
1 | @REM https://stackoverflow.com/questions/755382/i-want-to-delete-all-bin-and-obj-folders-to-force-all-projects-to-rebuild-everyt
2 | @ECHO *************
3 | @ECHO ** WARNING!
4 | @ECHO ** This will delete all bin and obj folders!
5 | @ECHO ** Press Ctrl-C to Cancel
6 | @ECHO *************
7 | @ECHO.
8 | @PAUSE
9 | @ECHO *************
10 | @ECHO.
11 |
12 | FOR /F "tokens=*" %%G IN ('DIR /B /AD /S bin') DO RMDIR /S /Q "%%G"
13 | FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G"
14 |
15 | @ECHO.
16 | @ECHO *************
17 | @ECHO ** Completed! All bin and obj folders are deleted.
18 | @ECHO *************
19 | @ECHO.
20 | @PAUSE
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "9.0.100",
4 | "rollForward": "latestFeature",
5 | "allowPrerelease": false
6 | }
7 | }
--------------------------------------------------------------------------------
/src/WeixinAuth/Apis/IWeixinAuthApi.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.OAuth;
2 | using System.Net.Http;
3 | using System.Text.Json;
4 | using System.Threading;
5 | using System.Threading.Tasks;
6 |
7 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
8 | {
9 | internal interface IWeixinAuthApi
10 | {
11 | Task GetToken(HttpClient backchannel, string tokenEndpoint, string appId, string appSecret, string code, CancellationToken cancellationToken);
12 | Task GetUserInfo(HttpClient backchannel, string userInformationEndpoint, string accessToken, string openid, CancellationToken cancellationToken, WeixinAuthLanguageCodes languageCode = WeixinAuthLanguageCodes.zh_CN);
13 | }
14 | }
--------------------------------------------------------------------------------
/src/WeixinAuth/Apis/WeixinAuthApi.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.OAuth;
2 | using Microsoft.AspNetCore.WebUtilities;
3 | using Microsoft.Extensions.Logging;
4 | using Microsoft.Extensions.Options;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Net.Http;
8 | using System.Text;
9 | using System.Text.Json;
10 | using System.Threading;
11 | using System.Threading.Tasks;
12 |
13 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
14 | {
15 | internal class WeixinAuthApi : IWeixinAuthApi
16 | {
17 | protected ILogger Logger { get; }
18 | protected IOptionsMonitor OptionsMonitor;
19 |
20 | public WeixinAuthApi(IOptionsMonitor optionsMonitor, ILoggerFactory loggerFactory)
21 | {
22 | Logger = loggerFactory?.CreateLogger() ?? throw new ArgumentNullException(nameof(loggerFactory));
23 | OptionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));
24 | }
25 |
26 | private static async Task Display(HttpResponseMessage response)
27 | {
28 | var output = new StringBuilder();
29 | output.Append("Status: " + response.StatusCode + ";");
30 | output.Append("Headers: " + response.Headers.ToString() + ";");
31 | output.Append("Body: " + await response.Content.ReadAsStringAsync() + ";");
32 | return output.ToString();
33 | }
34 |
35 | ///
36 | /// 通过code换取网页授权access_token。通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(该access_token用于调用其他接口)不同。
37 | ///
38 | /// refresh_token拥有较长的有效期(30天),当refresh_token失效的后,需要用户重新授权,所以,请开发者在refresh_token即将过期时(如第29天时),进行定时的自动刷新并保存好它。
39 | /// 尤其注意:由于公众号的secret和获取到的access_token安全级别都非常高,必须只保存在服务器,不允许传给客户端。后续刷新access_token、通过access_token获取用户信息等步骤,也必须从服务器发起。
40 | ///
41 | public async Task GetToken(HttpClient backchannel, string tokenEndpoint, string appId, string appSecret, string code, CancellationToken cancellationToken)
42 | {
43 | var tokenRequestParameters = new Dictionary()
44 | {
45 | ["appid"] = appId,
46 | ["secret"] = appSecret,
47 | ["code"] = code,
48 | ["grant_type"] = "authorization_code"
49 | };
50 |
51 | var requestUrl = QueryHelpers.AddQueryString(tokenEndpoint, tokenRequestParameters);
52 |
53 | var response = await backchannel.GetAsync(requestUrl, cancellationToken);
54 | if (!response.IsSuccessStatusCode)
55 | {
56 | var error = "OAuth token endpoint failure: " + await Display(response);
57 | Logger.LogError(error);
58 | return OAuthTokenResponse.Failed(new Exception(error));
59 | }
60 |
61 | var content = await response.Content.ReadAsStringAsync();
62 | // {
63 | // "access_token":"ACCESS_TOKEN",
64 | // "expires_in":7200,
65 | // "refresh_token":"REFRESH_TOKEN",
66 | // "openid":"OPENID",
67 | // "scope":"SCOPE",
68 | // "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
69 | //}
70 | var payload = JsonDocument.Parse(content);
71 | int errorCode = WeixinAuthHandlerHelper.GetErrorCode(payload);
72 | if (errorCode != 0)
73 | {
74 | var error = "OAuth token endpoint failure: " + await Display(response);
75 | Logger.LogError(error);
76 | return OAuthTokenResponse.Failed(new Exception(error));
77 | }
78 |
79 | //payload.Add("token_type", "");
80 | return OAuthTokenResponse.Success(payload);
81 | }
82 |
83 |
84 | ///
85 | /// 刷新或续期access_token使用。由于access_token有效期(目前为2个小时)较短,当access_token超时后,可以使用refresh_token进行刷新。
86 | ///
87 | /// refresh_token拥有较长的有效期(30天),当refresh_token失效的后,需要用户重新授权,所以,请开发者在refresh_token即将过期时(如第29天时),进行定时的自动刷新并保存好它。
88 | ///
89 | public async Task RefreshToken(HttpClient backchannel, string refreshTokenEndpoint, string appId, string refreshToken, CancellationToken cancellationToken)
90 | {
91 | var tokenRequestParameters = new Dictionary()
92 | {
93 | ["appid"] = appId,
94 | ["grant_type"] = "refresh_token",
95 | ["refresh_token"] = refreshToken
96 | };
97 |
98 | var requestUrl = QueryHelpers.AddQueryString(refreshTokenEndpoint, tokenRequestParameters);
99 |
100 | var response = await backchannel.GetAsync(requestUrl, cancellationToken);
101 | if (!response.IsSuccessStatusCode)
102 | {
103 | var error = "OAuth refresh token endpoint failure: " + await Display(response);
104 | Logger.LogError(error);
105 | return OAuthTokenResponse.Failed(new Exception(error));
106 | }
107 |
108 | var content = await response.Content.ReadAsStringAsync();
109 | //{
110 | // "access_token":"ACCESS_TOKEN",
111 | // "expires_in":7200,
112 | // "refresh_token":"REFRESH_TOKEN",
113 | // "openid":"OPENID",
114 | // "scope":"SCOPE"
115 | //}
116 | var payload = JsonDocument.Parse(content);
117 | int errorCode = WeixinAuthHandlerHelper.GetErrorCode(payload);
118 | if (errorCode != 0)
119 | {
120 | var error = "OAuth refresh token endpoint failure: " + await Display(response);
121 | Logger.LogError(error);
122 | return OAuthTokenResponse.Failed(new Exception(error));
123 | }
124 |
125 | return OAuthTokenResponse.Success(payload);
126 | }
127 |
128 | ///
129 | /// 检验授权凭证(access_token)是否有效。
130 | ///
131 | ///
132 | ///
133 | public async Task ValidateToken(HttpClient backchannel, string validateTokenEndpoint, string appId, string accessToken, CancellationToken cancellationToken)
134 | {
135 | var tokenRequestParameters = new Dictionary()
136 | {
137 | ["appid"] = appId,
138 | ["access_token"] = accessToken
139 | };
140 |
141 | var requestUrl = QueryHelpers.AddQueryString(validateTokenEndpoint, tokenRequestParameters);
142 |
143 | var response = await backchannel.GetAsync(requestUrl, cancellationToken);
144 | if (!response.IsSuccessStatusCode)
145 | {
146 | var error = "OAuth validate token endpoint failure: " + await Display(response);
147 | Logger.LogError(error);
148 | return false;
149 | }
150 |
151 | var content = await response.Content.ReadAsStringAsync();
152 | var payload = JsonDocument.Parse(content);
153 | try
154 | {
155 | var errcode = payload.RootElement.GetInt32("errcode", 0);
156 | return (errcode == 0);
157 | }
158 | catch { }
159 | return false;
160 | }
161 |
162 | ///
163 | /// 获取用户个人信息(UnionID机制)
164 | ///
165 | ///
166 | ///
167 | public async Task GetUserInfo(HttpClient backchannel, string userInformationEndpoint, string accessToken, string openid, CancellationToken cancellationToken, WeixinAuthLanguageCodes languageCode = WeixinAuthLanguageCodes.zh_CN)
168 | {
169 | var tokenRequestParameters = new Dictionary()
170 | {
171 | ["access_token"] = accessToken,
172 | ["openid"] = openid,
173 | ["lang"] = languageCode.ToString()
174 | };
175 |
176 | var requestUrl = QueryHelpers.AddQueryString(userInformationEndpoint, tokenRequestParameters);
177 |
178 | var response = await backchannel.GetAsync(requestUrl, cancellationToken);
179 | if (!response.IsSuccessStatusCode)
180 | {
181 | var error = "OAuth userinformation endpoint failure: " + await Display(response);
182 | Logger.LogError(error);
183 | return null;
184 | }
185 |
186 | var content = await response.Content.ReadAsStringAsync();
187 | //{
188 | // "openid":"OPENID",
189 | // "nickname":"NICKNAME",
190 | // "sex":1,
191 | // "province":"PROVINCE",
192 | // "city":"CITY",
193 | // "country":"COUNTRY",
194 | // "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
195 | // "privilege":[
196 | // "PRIVILEGE1",
197 | // "PRIVILEGE2"
198 | // ],
199 | // "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
200 | //}
201 | var payload = JsonDocument.Parse(content);
202 |
203 | int errorCode = WeixinAuthHandlerHelper.GetErrorCode(payload);
204 | if (errorCode != 0)
205 | {
206 | var error = "OAuth user information endpoint failure: " + await Display(response);
207 | Logger.LogError(error);
208 | return null;
209 | }
210 |
211 | return payload;
212 | }
213 | }
214 | }
--------------------------------------------------------------------------------
/src/WeixinAuth/ClaimActions/ClaimActionCollectionMapExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.OAuth.Claims;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 |
6 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
7 | {
8 | internal static class ClaimActionCollectionMapExtensions
9 | {
10 | public static void MapJsonKeyArray(this ClaimActionCollection collection, string claimType, string jsonKey)
11 | {
12 | collection.Add(new JsonKeyArrayClaimAction(claimType, null, jsonKey));
13 | }
14 |
15 | public static void MapJsonKeyArray(this ClaimActionCollection collection, string claimType, string jsonKey, string valueType)
16 | {
17 | collection.Add(new JsonKeyArrayClaimAction(claimType, valueType, jsonKey));
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/src/WeixinAuth/ClaimActions/JsonKeyArrayClaimAction.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.OAuth.Claims;
2 | using System.Security.Claims;
3 | using System.Text.Json;
4 |
5 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
6 | {
7 | internal class JsonKeyArrayClaimAction : ClaimAction
8 | {
9 | public JsonKeyArrayClaimAction(string claimType, string valueType)
10 | : base(claimType, valueType)
11 | {
12 | JsonKey = claimType.ToLower();
13 | }
14 |
15 | ///
16 | /// Creates a new JsonKeyArrayClaimAction.
17 | ///
18 | /// The value to use for Claim.Type when creating a Claim.
19 | /// The value to use for Claim.ValueType when creating a Claim.
20 | /// The top level key to look for in the json user data.
21 | public JsonKeyArrayClaimAction(string claimType, string valueType, string jsonKey) : base(claimType, valueType)
22 | {
23 | JsonKey = jsonKey;
24 | }
25 |
26 | ///
27 | /// The top level key to look for in the json user data.
28 | ///
29 | public string JsonKey { get; }
30 |
31 | #region removed from 3.0, JObject replaced by JsonElement
32 | //public override void Run(JObject userData, ClaimsIdentity identity, string issuer)
33 | //{
34 | // var values = userData?[JsonKey];
35 | // if (!(values is JArray)) return;
36 |
37 | // foreach (var value in values)
38 | // {
39 | // identity.AddClaim(new Claim(ClaimType, value.ToString(), ValueType, issuer));
40 | // }
41 | //}
42 | #endregion
43 |
44 | public override void Run(JsonElement userData, ClaimsIdentity identity, string issuer)
45 | {
46 | var isArray = userData.GetArrayLength() > 0;
47 | if (isArray)
48 | {
49 | var arr = userData.GetStringArray(JsonKey);
50 | foreach (var value in arr)
51 | identity.AddClaim(new Claim(ClaimType, value.ToString(), ValueType, issuer));
52 | }
53 | else
54 | {
55 | var s = userData.GetString(JsonKey);
56 | identity.AddClaim(new Claim(ClaimType, s, ValueType, issuer));
57 | }
58 | }
59 | }
60 | }
--------------------------------------------------------------------------------
/src/WeixinAuth/Extensions/AuthenticationPropertiesExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication;
2 | using System.Threading.Tasks;
3 |
4 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
5 | {
6 | internal static class AuthenticationPropertiesExtensions
7 | {
8 | public static string GetCorrelationId(this AuthenticationProperties properties)
9 | {
10 | return WeixinAuthAuthenticationPropertiesHelper.GetCorrelationId(properties);
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/WeixinAuth/Extensions/ClaimsExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Claims;
3 |
4 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
5 | {
6 | internal static class WeixinAuthClaimsExtensions
7 | {
8 | public static ClaimsIdentity AddOptionalClaim(this ClaimsIdentity identity,
9 | string type, string value, string issuer)
10 | {
11 | if (identity == null)
12 | {
13 | throw new ArgumentNullException(nameof(identity));
14 | }
15 |
16 | // Don't update the identity if the claim cannot be safely added.
17 | if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(value))
18 | {
19 | return identity;
20 | }
21 |
22 | identity.AddClaim(new Claim(type, value, ClaimValueTypes.String, issuer ?? ClaimsIdentity.DefaultIssuer));
23 | return identity;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/WeixinAuth/Extensions/JsonDocumentAuthExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Text;
3 | using System.Text.Json;
4 |
5 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
6 | {
7 | internal static class JsonDocumentAuthExtensions
8 | {
9 | public static string GetString(this JsonElement element, string key)
10 | {
11 | if (element.TryGetProperty(key, out var property) && property.ValueKind != JsonValueKind.Null)
12 | {
13 | return property.ToString();
14 | }
15 |
16 | return null;
17 | }
18 |
19 | public static string GetString(this JsonDocument doc, string key)
20 | {
21 | return doc.RootElement.GetString(key);
22 | }
23 |
24 | public static int GetInt32(this JsonElement element, string key, int defaultValue = 0)
25 | {
26 | var s = element.GetString(key);
27 | try { return int.Parse(s); } catch { return defaultValue; }
28 | }
29 |
30 | public static string[] GetStringArray(this JsonElement element, string key)
31 | {
32 | var s = element.GetString(key);
33 | try { return s.Split(',', System.StringSplitOptions.RemoveEmptyEntries); } catch { return null; }
34 | }
35 |
36 | public static JsonDocument AppendElement(this JsonDocument doc, string name, string value)
37 | {
38 | using (var ms = new MemoryStream())
39 | {
40 | using (var writer = new Utf8JsonWriter(ms))
41 | {
42 | writer.WriteStartObject();
43 |
44 | foreach (var existElement in doc.RootElement.EnumerateObject())
45 | {
46 | existElement.WriteTo(writer);
47 | }
48 |
49 | // Append new element
50 | writer.WritePropertyName(name);
51 | writer.WriteStringValue(value);
52 |
53 | writer.WriteEndObject();
54 | }
55 |
56 | var resultJson = Encoding.UTF8.GetString(ms.ToArray());
57 | return JsonDocument.Parse(resultJson);
58 | }
59 | }
60 | public static JsonDocument AppendElement(this JsonDocument doc, JsonElement element)
61 | {
62 | using (var ms = new MemoryStream())
63 | {
64 | using (var writer = new Utf8JsonWriter(ms))
65 | {
66 | writer.WriteStartObject();
67 |
68 | foreach (var existElement in doc.RootElement.EnumerateObject())
69 | {
70 | existElement.WriteTo(writer);
71 | }
72 |
73 | element.WriteTo(writer);
74 |
75 | writer.WriteEndObject();
76 | }
77 |
78 | var resultJson = Encoding.UTF8.GetString(ms.ToArray());
79 | return JsonDocument.Parse(resultJson);
80 | }
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/WeixinAuth/Extensions/LoggingExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Logging;
2 | using System;
3 |
4 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
5 | {
6 | internal static class LoggingExtensions
7 | {
8 | private static Action _handleChallenge;
9 |
10 | static LoggingExtensions()
11 | {
12 | _handleChallenge = LoggerMessage.Define(
13 | eventId: new EventId(1, "HandleChallenge"),
14 | logLevel: LogLevel.Debug,
15 | formatString: "HandleChallenge with Location: {Location}; and Set-Cookie: {Cookie}.");
16 | }
17 |
18 | public static void HandleChallenge(this ILogger logger, string location, string cookie)
19 | => _handleChallenge(logger, location, cookie, null);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/WeixinAuth/Extensions/OAuthTokenResponseExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.OAuth;
2 |
3 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
4 | {
5 | internal static class OAuthTokenResponseExtensions
6 | {
7 | public static string GetUnionId(this OAuthTokenResponse response)
8 | {
9 | return response.Response.RootElement.GetString("unionid");
10 | }
11 |
12 | public static string GetOpenId (this OAuthTokenResponse response)
13 | {
14 | return response.Response.RootElement.GetString("openid");
15 | }
16 |
17 | public static string GetScope(this OAuthTokenResponse response)
18 | {
19 | return response.Response.RootElement.GetString("scope");
20 | }
21 |
22 | public static string GetErrorCode(this OAuthTokenResponse response)
23 | {
24 | return response.Response.RootElement.GetString("errcode");
25 | }
26 |
27 | public static string GetErrorMsg(this OAuthTokenResponse response)
28 | {
29 | return response.Response.RootElement.GetString("errmsg");
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/WeixinAuth/Helpers/CompressionExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.IO.Compression;
5 | using System.Linq;
6 | using System.Runtime.Serialization.Formatters.Binary;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 | using System.Xml.Serialization;
10 |
11 | namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
12 | {
13 | ///
14 | /// ref. https://stackoverflow.com/questions/7343465/compression-decompression-string-with-c-sharp
15 | ///
16 | static internal class CompressionExtensions
17 | {
18 | public static async Task> Zip(this object obj)
19 | {
20 | byte[] bytes = obj.Serialize();
21 |
22 | using (MemoryStream msi = new MemoryStream(bytes))
23 | using (MemoryStream mso = new MemoryStream())
24 | {
25 | using (var gs = new GZipStream(mso, CompressionMode.Compress))
26 | await msi.CopyToAsync(gs);
27 |
28 | return mso.ToArray().AsEnumerable();
29 | }
30 | }
31 |
32 | public static async Task