一、判定是否在企业微信里面,如果是则跳转到自动登录地址

[AllowAnonymous]
public IActionResult Login(string returnUrl)
{
    Request.Headers.TryGetValue("User-Agent", out var userAgent);
    if (userAgent.Where(m => m.Contains("wxwork")).Any())
    {
        return Redirect($"/WeixinWork/RedirectToOauth?redirectUrl={returnUrl}");
    }

    return Content($"User-Agent:{userAgent}");
}

二、获得oauth2.0 code

WeixinWorkController

public IActionResult RedirectToOauth(string redirectUrl)
{
    var returnUrl = $"{globalSettings.Host}/WeixinWork/OauthCallBack?redirectUrl={redirectUrl}";
    var state = "";
    var agentId = "";
    // https://developer.work.weixin.qq.com/document/path/98151
    // 构建url,跳转到企业微信,等企业微信那边再跳转回来
    var url = Senparc.Weixin.Work.AdvancedAPIs.OAuth2Api.GetCode(wxWorkSettings.CorpId, returnUrl, state, agentId);
    return Redirect(url);
}

三、根据code获得当前用户信息,然后自行实现登录

WeixinWorkController

public async Task<IActionResult> OauthCallBackAsync(string code,string redirectUrl)
{
    if (string.IsNullOrEmpty(redirectUrl))
    {
        redirectUrl = "/Member";
    }
    string corpId = wxWorkSettings.CorpId;
    string corpSecret = wxWorkSettings.CrmAgentSecret;

    string accessToken = Senparc.Weixin.Work.Containers.AccessTokenContainer.GetToken(corpId, corpSecret);
    
    // 获得用户信息,这个用户信息即是用于匹配自建系统的应用

    var user = Senparc.Weixin.Work.AdvancedAPIs.OAuth2Api.GetUserId(accessToken, code);
    var member = Senparc.Weixin.Work.AdvancedAPIs.MailListApi.GetMember(accessToken, user.UserId);
    
    // 这里是使用cookie登录的过程,也可以使用jwt


    List<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, member.userid, ClaimValueTypes.String, null),
        new Claim(ClaimTypes.MobilePhone, member.mobile, ClaimValueTypes.String, null),
        new Claim("User-Agent", "WxWork", ClaimValueTypes.String, null),
    };

    var userIdentity = new ClaimsIdentity("Form");
    userIdentity.AddClaims(claims);

    var principal = new ClaimsPrincipal(userIdentity);

    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

    return Redirect(redirectUrl);
}