说明:这不是第一个步骤,后面再补一下前面的文档
实现接口 IProfileService
/// <summary>
/// 通过此实现可以拓展相关的用户Profile信息
/// </summary>
public class PerryProfileService : IProfileService
{
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
await Task.CompletedTask;
}
public async Task IsActiveAsync(IsActiveContext context)
{
await Task.CompletedTask;
}
}
实现接口 IResourceOwnerPasswordValidator
/// <summary>
/// 通过此实现可以在返回token前自定义校验用户账号和密码
/// 这里注入了自己实现的ApplicationUserService
/// </summary>
public class PerryResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
public IApplicationUserService UserService { get; }
public PerryResourceOwnerPasswordValidator(IApplicationUserService userService)
{
UserService = userService;
}
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
var validateResult = await UserService.ValidateCredentialsAsync(context.UserName, context.Password);
if (validateResult.Result)
{
var user = await UserService.GetByUserNameAsync(context.UserName);
context.Result = new GrantValidationResult(
subject:user.Id,
authenticationMethod:"",
claims: new List<Claim>()
);
}
}
}
将上述实现类替换到IdentityServer
- Startup.cs/ConfigureServices里配置注入信息
services.AddTransient<IResourceOwnerPasswordValidator, PerryResourceOwnerPasswordValidator>();
services.AddTransient<IProfileService, PerryProfileService>();
- 使用自己实现的类
var builder = services.AddIdentityServer()
// 其他配置
// 。。。
// 其他配置
.AddResourceOwnerValidator<PerryResourceOwnerPasswordValidator>()
.AddProfileService<PerryProfileService>();
经过上述操作后,访问 https://localhost:5001/connect/token 即可进入到自己的校验并返回有效的Token
- 获取Token测试
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IkFDMjg3MjVCOTRCOTU4MDI1RDdEOUUwNjNCNjVGN0NFIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2MzI1NTEyMTgsImV4cCI6MTYzMjU1NDgxOCwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NTAwMSIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjUwMDEvcmVzb3VyY2VzIiwiY2xpZW50X2lkIjoid2ViIiwic3ViIjoiYTg4ZDUxY2ItMGU4MC00MTAwLThmYjgtMTM2MzI0ODRjYTE4IiwiYXV0aF90aW1lIjoxNjMyNTUxMjE4LCJpZHAiOiJsb2NhbCIsImp0aSI6Ijk5MjM4QjIyMTA0NDNFMUU3Njc0RjdGRDVFNTI1Q0I5IiwiaWF0IjoxNjMyNTUxMjE4LCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbIiJdfQ.hssfoHyF8zZsdgDqzDzcx4fYaEl2q6FETdA9UWxUgxuFrZhSqq6hJU5ENnWFIBmdcQfZMVgwULX4bGoyymT5glljH1I7bdIGQpTuUYEC8BHyxCjL4yrFziPTQ5pnPCk0BdeOL0KsIdoaQUDUh4wS_AGNdwT9svKw6ae3TgciHfY2XTTZRXxEvbZBCV1KwVFgO2S040_2F7D68ZRAkF0Y2Xz27iihXcnVNQ2_j8kRqfgEbLuQ2HArJiC6FUOHRLnu8EvwGS4P6ckaVbiiKREduB_B_qq5LVz2SB0L4Y7dsCNdLUvTtoE0Onm5i5fAOkp46DflXCYhzn50hX6y4JAyzw",
"expires_in": 3600,
"token_type": "Bearer",
"refresh_token": "0B27364E6504FB451DD4287D1F1B21BF12DC0FF70AC4E93267F2AB57AD7660F2",
"scope": "offline_access openid profile"
}
-
校验Token测试:没有Token
-
校验Token测试:使用上方得到的Token
评论区