IdentityServer4 实现自定义 GrantType 授权模式

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>();
}

请求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值