IdentityServer4_密码模式
IdentityServer4_密码模式
模拟用户:
注入服务:
public void ConfigureServices(IServiceCollection services)
{
//services.AddControllers();
var build = services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.GetClients)
.AddTestUsers(Config.GetUsers()); ;
}
配置password模式
public static partial class Config
{
///定义API范围
public static IEnumerable<ApiScope> ApiScopes =>
new List<ApiScope>
{
new ApiScope("api1", "My API")
};
public static IEnumerable<Client> GetClients => new List<Client> {
new Client{
ClientId="client",
ClientSecrets={
new Secret("secret".Sha256()),
},
AllowedScopes={"api1"},
AllowedGrantTypes=GrantTypes.ResourceOwnerPassword
}
};
}
添加模拟用户
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "alice",
Password = "password"
},
new TestUser
{
SubjectId = "2",
Username = "bob",
Password = "password"
}
};
}

验证真实用户:
添加ResourceOwnerPasswordValidator类集成IResourceOwnerPasswordValidator接口
重写 ValidateAsync(ResourceOwnerPasswordValidationContext context)方法
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
await Task.Run(() =>
{
try
{
var userName = context.UserName;
var password = context.Password;
if (userName == "zhangsan" && password == "lisi")
{
//context.Request.ClientId = userName;
// 验证账号
context.Result = new GrantValidationResult
(
subject: userName,
authenticationMethod: "authentication"
);
}
else {
context.Result = new GrantValidationResult()
{
IsError = true,
Error = "错误"
};
}
}
catch (Exception ex)
{
//验证异常结果
context.Result = new GrantValidationResult()
{
IsError = true,
Error = ex.Message
};
}
});
}
}
注入服务:
public void ConfigureServices(IServiceCollection services)
{
//services.AddControllers();
var build = services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.GetClients)
//.AddTestUsers(Config.GetUsers())
.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();
}

postman调用参数:
| key | value |
|---|---|
| client_id | client |
| grant_type | password |
| client_secret | secret |
| password | password |
| username | bob |

浙公网安备 33010602011771号