您所说的原生体验称为资源所有者凭据授予。
要在 IdentityServer4 中实现它,您需要实现 IResourceOwnerPasswordValidator 接口。
public class CustomResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
//Validate user's username and password. Insert your logic here.
if(context.UserName == "admin" && context.Password == "admin@123")
context.Result = new GrantValidationResult("123", OidcConstants.AuthenticationMethods.Password);
return Task.FromResult(0);
}
}
然后配置 IdentityServer4 使用它。
在 Startup.cs 中添加以下代码
var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients)
.AddResourceOwnerValidator<CustomResourceOwnerPasswordValidator>();
并将客户端配置为使用资源所有者凭据授予。
new Client
{
ClientId = "resourceownerclient",
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
AccessTokenType = AccessTokenType.Jwt,
AccessTokenLifetime = 3600,
IdentityTokenLifetime = 3600,
UpdateAccessTokenClaimsOnRefresh = true,
SlidingRefreshTokenLifetime = 30,
AllowOfflineAccess = true,
RefreshTokenExpiration = TokenExpiration.Absolute,
RefreshTokenUsage = TokenUsage.OneTimeOnly,
AlwaysSendClientClaims = true,
Enabled = true,
ClientSecrets= new List<Secret> { new Secret("dataEventRecordsSecret".Sha256()) },
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
IdentityServerConstants.StandardScopes.OfflineAccess,
"dataEventRecords"
}
}
注意AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials 行。
这里是link,可能是 IdentityServer 与 Microsoft Identity Core 的实现。
这里是演示 repository 和 blog。