具體接入identityserver請看文檔,這里只簡單列舉部分步驟
1.創建一個web項目,引入Identityserver4的nuget包
2.新建一個類,實現IResourceOwnerPasswordValidator接口
···csharp
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
VerifyUserInputDto inputDto = new VerifyUserInputDto
{
UserName = context.UserName,
Password = context.Password
};
var verifyResult = await _userService.VerifyUserPasswordAsync(inputDto);
if (verifyResult.isSuccess)
{
context.Result = new GrantValidationResult(verifyResult.userInfo.UserId.ToString(), OidcConstants.AuthenticationMethods.Password);
}
else
{
//驗證失敗
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
}
}
大致就是讀取數據庫數據,與context.username ,password,進行比對,一致則通過,不一致就是失敗。
3.Starpup中增加
···csharp
services.AddIdentityServer()
.AddInMemoryApiResources(你定義的資源)
.AddInMemoryClients(你定義的客戶端)
.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>() //主要是user這里替換我們自己的服務
.AddDeveloperSigningCredential(); // rsa密鑰,自動生產一個臨時的。
4.api項目中 配置好identityserver ,Post請求 identityserver 下connect/token 這個地址 獲取token, 記得在設置token的時候加上 Bearer 前綴 否則token是無效的!!