繼上一篇的密碼授權模式,這篇會繼續實現自定義授權模式
這里呢以微信小程序登錄為例
首先打開授權中心在Validator添加WXAppletsGrantValidator.cs
實現IExtensionGrantValidator
//wxappletsgrant自定義的授權類型
public string GrantType => "wxappletsgrant";
public async Task ValidateAsync(ExtensionGrantValidationContext context)
{
try
{
#region 參數獲取 直接把授權后的openId 拿過來授權是不安全的,這里僅僅是一個Demo
//var openId = context.Request.Raw[ParamConstants.OpenId];
//var unionId = context.Request.Raw[ParamConstants.UnionId];
//var userName = context.Request.Raw[ParamConstants.UserName];
#endregion
var openId = "xxxxxxssss";
var unionId = "hgghgghg";
#region 通過openId和unionId 參數來進行數據庫的相關驗證
var claimList = await ValidateUserAsync(openId, unionId);
#endregion
#region 授權通過
//授權通過返回
context.Result = new GrantValidationResult
(
subject: "111",
authenticationMethod: "custom",
claims: claimList.ToArray()
);
#endregion
}
catch (Exception ex)
{
context.Result = new GrantValidationResult()
{
IsError = true,
Error = ex.Message
};
}
}
#region Private Method
/// <summary>
/// 驗證用戶
/// </summary>
/// <param name="loginName"></param>
/// <param name="password"></param>
/// <returns></returns>
private Task<List<Claim>> ValidateUserAsync(string openId, string unionId)
{
//這里可以通過openId 和unionId 來查詢用戶信息,我這里為了方便測試還是直接寫測試的openId 相關信息用戶
var user = "";
if (user == null)
{
//注冊用戶
}
return Task.FromResult(new List<Claim>()
{
new Claim(ClaimTypes.Name, $"hyq"),
new Claim(ClaimTypes.Country,"CHN"),
new Claim(ClaimTypes.Email,"hyq@hyq.com"),
});
}
#endregion
添加GrantTypeConstants類並編輯
public static ICollection<string> ResourceWXappletsGrant => new string[1]
{
"wxappletsgrant",
};
修改Config.cs 添加Client
new Client
{
ClientId = "wxappletsgrant_Client",
ClientName = "Client WxAppletsGrant_Client",
ClientSecrets = { new Secret("wxappletsgrantclient".Sha256()) },
AllowedGrantTypes = GrantTypeConstants.ResourceWXappletsGrant,//自定義登錄
AllowedScopes = {
"invoice_read",
IdentityServerConstants.StandardScopes.OfflineAccess//如果要獲取refresh_tokens ,必須在scopes中加上OfflineAccess
},
AllowOfflineAccess = true,// 是否需要同意授權 (默認是false)
RefreshTokenUsage = TokenUsage.ReUse,
AccessTokenLifetime = 60*5,
RefreshTokenExpiration = TokenExpiration.Absolute,
AbsoluteRefreshTokenLifetime = 300,
}
注冊服務
在startup.cs中ConfigureServices方法添加如下代碼:
builder.AddExtensionGrantValidator<WXAppletsGrantValidator>();
啟動調試