.NET Core+QQ第三方授權登錄

安裝包

dotnet add package AspNet.Security.OAuth.QQ

申請過程不介紹了,申請者資料,個人也是可以申請成功的。

這時候有二個參數就是clientid clientsecret

APP ID:xxxx
APP Key:xxxxxx

其中平台資訊,這個申請審核通過後,不要修改,千萬不要隨便修改,一修改就要重新審核。

網站回調域:可以隨便修改,並且可以寫多個,中間用英文逗號分隔即可。
比如,網站地址填的://api.igeekfan.cn,下面如果是localhost,是可以的,但如果是域名,便只能是//api.igeekfan.cn這個域名下的路徑。

網站回調域配置,後台是運行在//localhost:5001埠上。

//api.igeekfan.cn/signin-qq;//localhost:5001/signin-qq

介面介紹

server-side模式,是OAuth2.0認證的一種模式,又稱Web Server Flow;

image

獲取Authorization Code
//graph.qq.com/oauth2.0/authorize

通過Authorization Code獲取Access Token
//graph.qq.com/oauth2.0/token

獲取用戶OpenID_OAuth2.0
//graph.qq.com/oauth2.0/me

獲取用戶個人資訊
//graph.qq.com/user/get_user_info

使用Authorization_Code獲取Access_Token

接入流程如下:

  1. 先獲取Authorization Code;
  2. 通過Authorization Code獲取Access Token

1.Step1:獲取Authorization Code

GET

//graph.qq.com/oauth2.0/authorize?response_type=code&client_id=client_id&redirect_uri=//localhost:5001/signin-qq&state=123abc

具體參數可查看官網。

state由用戶自己創建一個隨機數,以防止CSRF攻擊。

如果用戶成功登錄並授權,則會跳轉到指定的回調地址,並在redirect_uri地址後帶上Authorization Code和原始的state值。如:

//localhost:5001/signin-qq?code=B6D497755EACE4635115FC82BE24F280&state=123abc

後台先根據state驗證是自己發出的請求,判斷是否相同,不相同,則代表非本項目發出的授權登錄請求。

  1. 根據code獲取access_token

GET

//graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=client_id&client_secret=client_secret&code=B6D497755EACE4635115FC82BE24F280&redirect_uri=//localhost:5001/signin-qq

這時候你會得到

access_token=1B6E45FA99BA3D6B347713440C9BCEFE&expires_in=7776000&refresh_token=8DB1D48D95C85D3EF593936B8ACE5EE0

獲取用戶OpenID_OAuth2.0

GET

//graph.qq.com/oauth2.0/me?access_token=1B6E45FA99BA3D6B347713440C9BCEFE

openid是此網站上唯一對應用戶身份的標識

callback( {"client_id":"101867513","openid":"951560F5C7A5AA9E5E599CF9B4ECFFB2"} );

獲取用戶的其他資訊

用戶資訊

//graph.qq.com/user/get_user_info?access_token=1B6E45FA99BA3D6B347713440C9BCEFE&oauth_consumer_key=YOUR_APP_ID&openid=951560F5C7A5AA9E5E599CF9B4ECFFB2

{
"ret": 0, 
"msg": "", 
"is_lost":0, 
"nickname": "、天上有木月OvO", 
"gender": "xxx", 
"gender_type": 1, 
"province": "xxx", 
"city": "xxx", 
"year": "2019", 
"constellation": "", 
"figureurl": "http:\/\/qzapp.qlogo.cn\/qzapp\/101867513\/951560F5C7A5AA9E5E599CF9B4ECFFB2\/30", 
"figureurl_1": "http:\/\/qzapp.qlogo.cn\/qzapp\/101867513\/951560F5C7A5AA9E5E599CF9B4ECFFB2\/50", 
"figureurl_2": "http:\/\/qzapp.qlogo.cn\/qzapp\/101867513\/951560F5C7A5AA9E5E599CF9B4ECFFB2\/100", 
"figureurl_qq_1": "//thirdqq.qlogo.cn/g?b=oidb&k=bjXoWmdlu8fk1m80MCkibMg&s=40&t=1559108425", 
"figureurl_qq_2": "//thirdqq.qlogo.cn/g?b=oidb&k=bjXoWmdlu8fk1m80MCkibMg&s=100&t=1559108425", "figureurl_qq": "//thirdqq.qlogo.cn/g?b=oidb&k=bjXoWmdlu8fk1m80MCkibMg&s=640&t=1559108425"
}

程式碼

services.AddAuthentication(xxx)
.AddGitHub(xxx)
加上AddQQ的配置項
.AddQQ(options =>
{
   options.ClientId = Configuration["Authentication:QQ:ClientId"];
   options.ClientSecret = Configuration["Authentication:QQ:ClientSecret"];
})

appsettings.json中配置項

  "Authentication": {
   //下面為新增項
   "QQ": {
     "ClientId": "xx",
     "ClientSecret": "xxx"
   }
 }

對,沒錯,QQ登錄,已經結束了。接下來就是把這些用戶的資訊保存到資料庫,生成token的過程。

這裡

[HttpGet("signin-callback")]
public async Task<IActionResult> Home(string provider, string redirectUrl = "")
{

   AuthenticateResult authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
   if (!authenticateResult.Succeeded) return Redirect(redirectUrl);
   var openIdClaim = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier);
   if (openIdClaim == null || string.IsNullOrWhiteSpace(openIdClaim.Value))
       return Redirect(redirectUrl);
       
       
   ClaimsPrincipal principal=authenticateResult.Principal;
   //根據provider,處理用戶的基礎資訊,
   
   long id =SaveQQAsync(principal, openIdClaim.Value)
   
   //xxx
   
}       

openIdClaimopenIdClaim是唯一值

lin_user表

欄位 類型 備註
Id long 主鍵
Username varchar(50) 用戶名
Avatar varchar(50) 頭像

lin_user_identity表

用戶授權資訊表,用於存儲不同登錄類型的用戶資訊,如手機號、郵件、用戶名、第三方應用(微信、QQ、GitHub)的登錄

欄位 類型 備註
Id long 主鍵
IdentityType varchar(50) 認證類型,如 Password,GitHub、QQ、WeiXin等
Identifier varchar(24) 認證者,例如 用戶名(PassWord認證類型),授權得到的昵稱(QQ),授權得到的用戶名(唯一,GitHub)
Credential varchar(50) 憑證,例如 密碼,存OpenId、Id,同一IdentityType的OpenId的值是唯一的
CreateUserId long 綁定的用戶Id

根據openId,判斷lin_user_identity表中是否存在這一第三方授權資訊,如果存在,則返回當前用戶lin_user表中的id,如果不存在,則創建一個新的用戶資訊,插入lin_user、lin_user_identity表中。


public async Task<long> SaveQQAsync(ClaimsPrincipal principal, string openId)
{
   string nickname = principal.FindFirst(ClaimTypes.Name)?.Value;
   string gender = principal.FindFirst(ClaimTypes.Gender)?.Value;
   string picture = principal.FindFirst(QQAuthenticationConstants.Claims.PictureUrl)?.Value;
   string picture_medium = principal.FindFirst(QQAuthenticationConstants.Claims.PictureMediumUrl)?.Value;
   string picture_full = principal.FindFirst(QQAuthenticationConstants.Claims.PictureFullUrl)?.Value;
   string avatar = principal.FindFirst(QQAuthenticationConstants.Claims.AvatarUrl)?.Value;
   string avatar_full = principal.FindFirst(QQAuthenticationConstants.Claims.AvatarFullUrl)?.Value;
   
    Expression<Func<LinUserIdentity, bool>> expression = r => 
               r.IdentityType == LinUserIdentity.QQ&& r.Credential == openId;

   LinUserIdentity linUserIdentity =await _userIdentityRepository.Where(expression).FirstAsync();

   long userId = 0;
   if (linUserIdentity == null)
   {
       LinUser user = new LinUser
       {
           Avatar = avatar_full,
           Nickname = nickname,
           Username = "",
           LinUserIdentitys = new List<LinUserIdentity>()
           {
               new LinUserIdentity
               {
                   CreateTime = DateTime.Now,
                   Credential = openId,
                   IdentityType = LinUserIdentity.GitHub,
                   Identifier = nickname,
               }
           }
       };
       await _userRepository.InsertAsync(user);
       userId = user.Id;
   }
   else
   {
       userId = linUserIdentity.CreateUserId;
   }
   return userId;
}

上文中的CreateToken,直接將 authenticateResult.Principal.Claims.ToList(),生成token值,會缺少一些系統需要的值,比如鍵為ClaimTypes.NameIdentifier,應為用戶的id,用戶的其他資訊,如角色/分組,昵稱。不同平台的授權登錄,鍵有所不同,所以這裡需要二次處理。

[HttpGet("signin-callback")]
public async Task<IActionResult> Home(string provider, string redirectUrl = "")
{
 
    //xxx
        
        
    ClaimsPrincipal principal=authenticateResult.Principal;
    
    List<Claim> authClaims = principal.Claims.ToList();
    
    long id =SaveQQAsync(principal, openIdClaim.Value)
    
    LinUser user =await _userRepository.Select.IncludeMany(r => r.LinGroups)
        .WhereCascade(r => r.IsDeleted == false).Where(r => r.Id == id).FirstAsync();

    List<Claim> claims = new List<Claim>()
    {
        new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
        new Claim(ClaimTypes.GivenName,user.Nickname??""),
        new Claim(ClaimTypes.Name,user.Username??""),
    };
        
    user.LinGroups?.ForEach(r =>
    {
        claims.Add(new Claim(LinCmsClaimTypes.Groups, r.Id.ToString()));
    });

    claims.AddRange(authClaims);
    string token = this.CreateToken(claims);
    return Redirect($"{redirectUrl}?token={token}#login-result");
 }       

前台login-result路由,解析到token值,並保存起來,與用戶密碼登錄後的流程相同。

項目源碼