Bitzsoft.Integrations.SocialAuth 1.0.0-alpha.8

This is a prerelease version of Bitzsoft.Integrations.SocialAuth.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Bitzsoft.Integrations.SocialAuth --version 1.0.0-alpha.8
                    
NuGet\Install-Package Bitzsoft.Integrations.SocialAuth -Version 1.0.0-alpha.8
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Bitzsoft.Integrations.SocialAuth" Version="1.0.0-alpha.8" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Bitzsoft.Integrations.SocialAuth" Version="1.0.0-alpha.8" />
                    
Directory.Packages.props
<PackageReference Include="Bitzsoft.Integrations.SocialAuth" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Bitzsoft.Integrations.SocialAuth --version 1.0.0-alpha.8
                    
#r "nuget: Bitzsoft.Integrations.SocialAuth, 1.0.0-alpha.8"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Bitzsoft.Integrations.SocialAuth@1.0.0-alpha.8
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Bitzsoft.Integrations.SocialAuth&version=1.0.0-alpha.8&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Bitzsoft.Integrations.SocialAuth&version=1.0.0-alpha.8&prerelease
                    
Install as a Cake Tool

Bitzsoft.Integrations.SocialAuth

统一第三方登录集成包 -- Google、GitHub、Microsoft、Apple、Slack、钉钉、企业微信、飞书、微信公众平台、微信开放平台。

功能特性

  • 10 大平台:Google、GitHub、Microsoft、Apple、Slack、钉钉、企业微信、飞书、微信公众平台(公众号网页授权)、微信开放平台(网站应用)
  • OAuth 2.0 标准流程:授权码 → Token → 用户信息,统一门面 ISocialAuthService
  • PKCE 增强流程:Google 支持 S256 PKCE,无需 ClientSecret 的安全授权
  • OIDC ID Token 验证:Google / Microsoft / Apple 自动验证 ID Token 签名(JWKS)
  • Apple Revocation:支持 Apple 特有的 Token Revoke(客户端密钥 JWT 自动签发)
  • 微信生态全支持:公众号网页授权 + 开放平台网站应用 + UnionID 打通
  • 企业通讯:钉钉扫码 + 企业微信网页授权 + 飞书网页授权
  • Client Credentials:Google 支持服务间调用 GetClientTokenAsync
  • Provider 工厂:运行时动态获取已注册 Provider,按需扩展
  • 第三方请求日志:内置 RequestLogging DelegatingHandler,记录所有出站 HTTP 请求与响应,便于问题排查
  • 统一模型SocialAuthUser + SocialAuthToken + SocialAuthResult,一套类型覆盖全部平台

安装

.NET CLI

dotnet add package Bitzsoft.Integrations.SocialAuth

PackageReference

<PackageReference Include="Bitzsoft.Integrations.SocialAuth" Version="1.0.0" />

配置

appsettings.json

{
  "SocialAuth": {
    "Providers": {
      "google": {
        "Enabled": true,
        "ClientId": "xxx.apps.googleusercontent.com",
        "ClientSecret": "GOCSPX-xxx",
        "RedirectUri": "https://yourapp.com/auth/callback/google",
        "Scopes": [ "openid", "profile", "email" ]
      },
      "github": {
        "Enabled": true,
        "ClientId": "your-github-client-id",
        "ClientSecret": "your-github-client-secret",
        "RedirectUri": "https://yourapp.com/auth/callback/github",
        "Scopes": [ "user:email" ]
      },
      "microsoft": {
        "Enabled": true,
        "ClientId": "your-azure-ad-app-id",
        "ClientSecret": "your-client-secret",
        "RedirectUri": "https://yourapp.com/auth/callback/microsoft",
        "Scopes": [ "openid", "profile", "email", "User.Read" ],
        "ExtraParams": {
          "TenantId": "common"
        }
      },
      "apple": {
        "Enabled": true,
        "ClientId": "com.yourapp.service",
        "ClientSecret": "",
        "RedirectUri": "https://yourapp.com/auth/callback/apple",
        "Scopes": [ "name", "email" ],
        "ExtraParams": {
          "TeamId": "YOUR_TEAM_ID",
          "KeyId": "YOUR_KEY_ID",
          "PrivateKeyPem": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
        }
      },
      "slack": {
        "Enabled": true,
        "ClientId": "your-slack-client-id",
        "ClientSecret": "your-slack-client-secret",
        "RedirectUri": "https://yourapp.com/auth/callback/slack",
        "Scopes": [ "identity.basic", "identity.email" ]
      },
      "dingtalk": {
        "Enabled": true,
        "ClientId": "your-dingtalk-app-key",
        "ClientSecret": "your-dingtalk-app-secret",
        "RedirectUri": "https://yourapp.com/auth/callback/dingtalk"
      },
      "wecom": {
        "Enabled": true,
        "ClientId": "your-wecom-corp-id",
        "ClientSecret": "your-wecom-agent-secret",
        "RedirectUri": "https://yourapp.com/auth/callback/wecom",
        "ExtraParams": {
          "AgentId": "your-agent-id"
        }
      },
      "feishu": {
        "Enabled": true,
        "ClientId": "your-feishu-app-id",
        "ClientSecret": "your-feishu-app-secret",
        "RedirectUri": "https://yourapp.com/auth/callback/feishu"
      },
      "wechat_open": {
        "Enabled": true,
        "ClientId": "your-wechat-open-app-id",
        "ClientSecret": "your-wechat-open-app-secret",
        "RedirectUri": "https://yourapp.com/auth/callback/wechat-open"
      },
      "wechat_mp": {
        "Enabled": true,
        "ClientId": "your-wechat-mp-app-id",
        "ClientSecret": "your-wechat-mp-app-secret"
      }
    }
  }
}
配置项 说明 必填
Providers.<id>.Enabled 是否启用该 Provider
Providers.<id>.ClientId OAuth Client ID / App Key
Providers.<id>.ClientSecret OAuth Client Secret(PKCE 流程可空)
Providers.<id>.RedirectUri 回调地址(微信公众号不需要) 大部分需要
Providers.<id>.Scopes OAuth Scopes(不填使用默认值)
Providers.<id>.ExtraParams 额外参数(如 Apple TeamId/KeyId、Microsoft TenantId) 部分需要

Provider 特有 ExtraParams

Provider 参数 说明
microsoft TenantId Azure AD 租户 ID(默认 common
apple TeamId Apple Developer Team ID
apple KeyId Apple Sign-In Key ID
apple PrivateKeyPem Apple Sign-In 私钥 PEM 内容
wecom AgentId 企业微信应用 AgentId
wechat_mp 微信公众号网页授权不需要 ExtraParams

注册服务

从 IConfiguration 绑定(推荐)

using Bitzsoft.Integrations.SocialAuth.DependencyInjection;

builder.Services.AddBitzsoftSocialAuth(
    builder.Configuration.GetSection("SocialAuth"));

委托配置

builder.Services.AddBitzsoftSocialAuth(options =>
{
    options.Providers["google"] = new()
    {
        Enabled = true,
        ClientId = "xxx.apps.googleusercontent.com",
        ClientSecret = "GOCSPX-xxx",
        RedirectUri = "https://yourapp.com/auth/callback/google",
        Scopes = ["openid", "profile", "email"]
    };
});

第三方请求日志

内置 Bitzsoft.Integrations.RequestLogging 出站请求记录管道,默认使用 NullRequestLogStore 不持久化。

// ① 默认:启用记录管道但不持久化(日志丢弃)
services.AddBitzsoftSocialAuth(options => { /* ... */ });

// ② 持久化:宿主注册 IRequestLogStore 实现后,所有出站请求自动落库
services.AddRequestLogging<MyRequestLogStore>(opts =>
{
    opts.MaxBodyLength = 8192;
    opts.SensitiveFields.Add("mySecret");
});
services.AddBitzsoftSocialAuth(options => { /* ... */ });

使用示例

授权跳转(生成授权 URL)

using Bitzsoft.Integrations.SocialAuth.Interfaces;

public class AuthController : ControllerBase
{
    private readonly ISocialAuthService _socialAuth;

    public AuthController(ISocialAuthService socialAuth) => _socialAuth = socialAuth;

    [HttpGet("login/{provider}")]
    public IActionResult Login(string provider)
    {
        // state 用于 CSRF 防护,由宿主应用生成并存储
        var state = GenerateAntiForgeryToken();
        var url = _socialAuth.GetAuthorizationUrl(provider, state);
        return Redirect(url);
    }
}

PKCE 流程(Google)

[HttpGet("login/google-pkce")]
public IActionResult LoginGooglePkce()
{
    // 获取 PKCE Provider
    var factory = HttpContext.RequestServices.GetRequiredService<IOAuthProviderFactory>();
    var provider = (IPkceProvider)factory.GetProvider("google");

    var (verifier, challenge) = provider.GeneratePkce();
    var state = GenerateAntiForgeryToken();

    // 将 verifier 存储在 Session / Cache,回调时取回
    HttpContext.Session.SetString("pkce_verifier", verifier);

    var url = provider.GetAuthorizationUrl(state, challenge);
    return Redirect(url);
}

回调认证(Code → Token → User)

using Bitzsoft.Integrations.SocialAuth.Models;

[HttpGet("auth/callback/{provider}")]
public async Task<IActionResult> Callback(
    string provider,
    string code,
    string? state = null)
{
    // 1. 验证 state(CSRF 防护)
    if (!ValidateAntiForgeryToken(state))
        return BadRequest("Invalid state");

    // 2. 认证
    var request = new SocialAuthenticateRequest
    {
        ProviderId = provider,
        Code = code,
        RedirectUri = $"https://yourapp.com/auth/callback/{provider}"
    };

    var result = await _socialAuth.AuthenticateAsync(request);

    if (!result.IsSuccess)
        return Unauthorized(result.FailReason);

    // 3. 使用用户信息
    var user = result.User!;
    // user.OpenId    -- 第三方唯一标识
    // user.Email     -- 邮箱
    // user.Username  -- 用户名
    // user.Avatar    -- 头像 URL
    // user.UnionId   -- 微信 UnionID(微信平台)

    return SignIn(...);
}

PKCE 回调

[HttpGet("auth/callback/google-pkce")]
public async Task<IActionResult> CallbackGooglePkce(string code, string? state)
{
    if (!ValidateAntiForgeryToken(state))
        return BadRequest("Invalid state");

    var verifier = HttpContext.Session.GetString("pkce_verifier");

    var request = new SocialAuthenticateRequest
    {
        ProviderId = "google",
        Code = code,
        CodeVerifier = verifier,
        RedirectUri = "https://yourapp.com/auth/callback/google-pkce"
    };

    var result = await _socialAuth.AuthenticateAsync(request);
    if (!result.IsSuccess)
        return Unauthorized(result.FailReason);

    return SignIn(...);
}

刷新 Token

var factory = HttpContext.RequestServices.GetRequiredService<IOAuthProviderFactory>();
var provider = factory.GetProvider("google");
var newToken = await provider.RefreshTokenAsync(oldRefreshToken);

获取已注册 Provider 列表

var factory = HttpContext.RequestServices.GetRequiredService<IOAuthProviderFactory>();
var ids = factory.GetRegisteredProviderIds();
// 例如: [ "google", "github", "dingtalk" ]

核心类型一览

类型 说明
ISocialAuthService 统一门面(授权 URL + Code 认证)
IOAuthProviderFactory Provider 工厂(获取已注册 Provider)
IOAuthProvider 单个 Provider 标准契约(授权 / Token / 用户信息 / 刷新)
IPkceProvider PKCE 增强流程(Google)
IClientCredentialsProvider Client Credentials 流程(Google)
SocialAuthUser 统一用户信息(OpenId / UnionId / Email / Avatar / RawData)
SocialAuthToken 统一 Token(AccessToken / RefreshToken / IdToken / ExpiresAt)
SocialAuthResult 认证结果(Success / Fail)
SocialAuthenticateRequest 认证请求(ProviderId / Code / RedirectUri / CodeVerifier)
ProviderConfig 单个 Provider 配置(ClientId / ClientSecret / RedirectUri / Scopes / ExtraParams)
SocialAuthOptions 全局配置(Providers 字典)

Provider ID 对照表

Provider ID 实现类 平台
google GoogleAuthProvider Google OAuth 2.0 + OIDC
github GitHubAuthProvider GitHub OAuth App
microsoft MicrosoftAuthProvider Azure AD / Microsoft Entra ID
apple AppleAuthProvider Sign in with Apple
slack SlackAuthProvider Slack Sign In
dingtalk DingTalkAuthProvider 钉钉扫码登录
wecom WeComAuthProvider 企业微信网页授权
feishu FeishuAuthProvider 飞书网页授权
wechat_open WechatOpenProvider 微信开放平台(网站应用)
wechat_mp WechatMpProvider 微信公众平台(公众号网页授权)

安全说明

以下安全职责由宿主应用承担,本包不内置实现。

  • State 参数(CSRF 防护):宿主应用必须生成随机 state 并在授权跳转前存储(Session / Cookie / Cache),回调时验证一致性
  • PKCE CodeVerifier:使用 PKCE 流程时,CodeVerifier 必须在授权跳转前生成并安全存储,回调时传入。切勿将 CodeVerifier 暴露在 URL 或前端
  • Nonce:OIDC 流程中 nonce 用于防重放攻击,由宿主应用生成并在 ID Token 验证时校验
  • ClientSecret:通过环境变量或 Secret Manager 注入,禁止硬编码在源代码中
  • RedirectUri:必须与 OAuth 应用注册时填写的回调地址完全一致
  • Token 存储SocialAuthToken 中的 AccessToken / RefreshToken 为敏感数据,宿主应用应加密存储

依赖

说明
Bitzsoft.Integrations.Compatibility 基础工具库
Microsoft.Extensions.Configuration.Abstractions 配置抽象
Microsoft.Extensions.Configuration.Binder 配置绑定
Microsoft.Extensions.Http IHttpClientFactory(Typed Client 连接池)
Microsoft.Extensions.Options 选项模式(IOptions<T>
Microsoft.Extensions.Options.ConfigurationExtensions Options 配置节点绑定
Microsoft.Extensions.Logging.Abstractions 日志抽象
Microsoft.IdentityModel.Protocols.OpenIdConnect OIDC Discovery(Google / Microsoft / Apple)
System.IdentityModel.Tokens.Jwt JWT / ID Token 验证

相关包

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0-alpha.10 0 7/26/2026
1.0.0-alpha.9 50 7/12/2026
1.0.0-alpha.8 56 7/1/2026
1.0.0-alpha.7 318 6/16/2026
1.0.0-alpha.6 63 6/16/2026
1.0.0-alpha.5 60 6/14/2026
1.0.0-alpha.3 65 6/7/2026