IdentityServer4 实现自定义 GrantType 授权模式

OAuth 2.0 默认四种授权模式(GrantType):

  • 授权码模式(authorization_code
  • 简化模式(implicit
  • 密码模式(password
  • 客户端模式(client_credentials

使用 IdentityServer4,我们可以自定义授权模式吗?答案是可以的,比如我们自定义实现一个 my_sms_auth_code 授权模式

public class Config
{
    /// 
    /// 这个方法返回微服务中的API资源
    /// 
    /// 
    public static IEnumerable GetApiResources()
    {
        List resources = new List();
        resources.Add(new ApiResource("UsersService", "用户服务API"));
        resources.Add(new ApiResource("ProductService", "产品服务API"));
        return resources;
    }
	
	
    /// 
    /// 这个方法返回我们所有的客户资源
    /// 
    /// 
    public static IEnumerable GetClients()
    {
	List clients = new List();
        new Client
        {
            ClientId = "client1",
            AllowedGrantTypes = new List { "my_sms_auth_code" }, //一个 Client 可以配置多个 GrantType
            AllowOfflineAccess = true,
            AccessTokenLifetime = 3600 * 6, //6小时
            SlidingRefreshTokenLifetime = 1296000, //15天
            ClientSecrets = { new Secret("123".Sha256()) },
            AllowedScopes = new List { "UsersService" }
        };
	return clients;
    }
}

自定义个类

/// 
/// 我们自定义实现一个anonymous授权模式(匿名访问)
/// 
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
    {
        new IdentityResources.OpenId(), //必须要添加,否则报无效的scope错误 
        new IdentityResources.Profile()
    };
    services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddInMemoryIdentityResources(idResources)
        .AddInMemoryApiResources(Config.GetApiResources()) //从内存中加载API资源(我们也可设置从数据库中加载)
        .AddInMemoryClients(Config.GetClients())//从内存中加载客户端资源
        //.AddResourceOwnerValidator()
        .AddExtensionGrantValidator() //这就是我们自定义验证模式
        .AddProfileService();
}

请求

IdentityServer4 实现自定义 GrantType 授权模式_第1张图片

你可能感兴趣的:(NetCore,微服务)