OAuth 2.0 默认四种授权模式(GrantType):
- 授权码模式(
authorization_code
) - 简化模式(
implicit
) - 密码模式(
password
) - 客户端模式(
client_credentials
)
使用 IdentityServer4,我们可以自定义授权模式吗?答案是可以的,比如我们自定义实现一个 my_sms_auth_code 授权模式
public class Config
{
/// <summary>
/// 这个方法返回微服务中的API资源
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources()
{
List<ApiResource> resources = new List<ApiResource>();
resources.Add(new ApiResource("UsersService", "用户服务API"));
resources.Add(new ApiResource("ProductService", "产品服务API"));
return resources;
}
/// <summary>
/// 这个方法返回我们所有的客户资源
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
List<Client> clients = new List<Client>();
new Client
{
ClientId = "client1",
AllowedGrantTypes = new List<string> { "my_sms_auth_code" }, //一个 Client 可以配置多个 GrantType
AllowOfflineAccess = true,
AccessTokenLifetime = 3600 * 6, //6小时
SlidingRefreshTokenLifetime = 1296000, //15天
ClientSecrets = { new Secret("123".Sha256()) },
AllowedScopes = new List<string> { "UsersService" }
};
return clients;
}
}
自定义个类
/// <summary>
/// 我们自定义实现一个anonymous授权模式(匿名访问)
/// </summary>
public class MyExtensionGrantValidator : IExtensionGrantValidator
{
public string GrantType => "my_sms_auth_code";
public async Task ValidateAsync(ExtensionGrantValidationContext context)
{
var phone = context.Request.Raw["phone"]; //手机号
var code = context.Request.Raw["auth_code"];//验证码
var errorvalidationResult = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
if (string.IsNullOrWhiteSpace(phone) || string.IsNullOrWhiteSpace(code))
{
context.Result = errorvalidationResult;
return;
}
if (phone != "18620997009" || code != "1234") //根据手机号码,验证验证码是否正确
{
context.Result = errorvalidationResult;
return;
}
//如果验证成功了,这里则是注册用户
//var userid = _userService.Create(phone);
var userid = 5; //假设上一步创建成功了,并且得到一个用户id=5;
if (userid <= 0)
{
context.Result = errorvalidationResult;
return;
}
context.Result = new GrantValidationResult(userid.ToString(), GrantType);
}
}
3
public void ConfigureServices(IServiceCollection services)
{
//加载API资源和客户端资源
var idResources = new List<IdentityResource>
{
new IdentityResources.OpenId(), //必须要添加,否则报无效的scope错误
new IdentityResources.Profile()
};
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(idResources)
.AddInMemoryApiResources(Config.GetApiResources()) //从内存中加载API资源(我们也可设置从数据库中加载)
.AddInMemoryClients(Config.GetClients())//从内存中加载客户端资源
//.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()
.AddExtensionGrantValidator<MyExtensionGrantValidator>() //这就是我们自定义验证模式
.AddProfileService<ProfileService>();
}
请求