欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【.NET Core项目实战-统一认证平台】第十一章 授权篇-密码授权模式

程序员文章站 2022-06-25 08:17:03
" 【.NET Core项目实战 统一认证平台】开篇及目录索引 " 上篇文章介绍了基于 客户端授权的原理及如何实现自定义的客户端授权,并配合网关实现了统一的授权异常返回值和权限配置等相关功能,本篇将介绍密码授权模式,从使用场景、源码剖析到具体实现详细讲解密码授权模式的相关应用。 .netcore项目 ......

【.net core项目实战-统一认证平台】开篇及目录索引

上篇文章介绍了基于ids4客户端授权的原理及如何实现自定义的客户端授权,并配合网关实现了统一的授权异常返回值和权限配置等相关功能,本篇将介绍密码授权模式,从使用场景、源码剖析到具体实现详细讲解密码授权模式的相关应用。

.netcore项目实战交流群(637326624),有兴趣的朋友可以在群里交流讨论。

一、使用场景?

由于密码授权模式需要用户在业务系统输入账号密码,为了安全起见,对于使用密码模式的业务系统,我们认为是绝对可靠的,不存在泄漏用户名和密码的风险,所以使用场景定位为公司内部系统或集团内部系统或公司内部app等内部应用,非内部应用,尽量不要开启密码授权模式,防止用户账户泄漏。

  • 这种模式适用于用户对应用程序高度信任的情况。比如是用户系统的一部分。

二、ids4密码模式的默认实现剖析

在我们使用密码授权模式之前,我们需要理解密码模式是如何实现的,在上一篇中,我介绍了客户端授权的实现及源码剖析,相信我们已经对ids4客户端授权已经熟悉,今天继续分析密码模式是如何获取到令牌的。

ids4的所有授权都在tokenendpoint方法中,密码模式授权也是先校验客户端授权,如果客户端校验失败,直接返回删除信息,如果客户端校验成功,继续校验用户名和密码,详细实现代码如下。

  • 1、校验是否存在granttype,然后根据不同的类型启用不同的校验方式。

    // tokenrequestvalidator.cs
    public async task<tokenrequestvalidationresult> validaterequestasync(namevaluecollection parameters, clientsecretvalidationresult clientvalidationresult)
    {
      _logger.logdebug("start token request validation");
    
      _validatedrequest = new validatedtokenrequest
      {
          raw = parameters ?? throw new argumentnullexception(nameof(parameters)),
          options = _options
      };
    
      if (clientvalidationresult == null) throw new argumentnullexception(nameof(clientvalidationresult));
    
      _validatedrequest.setclient(clientvalidationresult.client, clientvalidationresult.secret, clientvalidationresult.confirmation);
    
      /////////////////////////////////////////////
      // check client protocol type
      /////////////////////////////////////////////
      if (_validatedrequest.client.protocoltype != identityserverconstants.protocoltypes.openidconnect)
      {
          logerror("client {clientid} has invalid protocol type for token endpoint: expected {expectedprotocoltype} but found {protocoltype}",
                   _validatedrequest.client.clientid,
                   identityserverconstants.protocoltypes.openidconnect,
                   _validatedrequest.client.protocoltype);
          return invalid(oidcconstants.tokenerrors.invalidclient);
      }
    
      /////////////////////////////////////////////
      // check grant type
      /////////////////////////////////////////////
      var granttype = parameters.get(oidcconstants.tokenrequest.granttype);
      if (granttype.ismissing())
      {
          logerror("grant type is missing");
          return invalid(oidcconstants.tokenerrors.unsupportedgranttype);
      }
    
      if (granttype.length > _options.inputlengthrestrictions.granttype)
      {
          logerror("grant type is too long");
          return invalid(oidcconstants.tokenerrors.unsupportedgranttype);
      }
    
      _validatedrequest.granttype = granttype;
    
      switch (granttype)
      {
          case oidcconstants.granttypes.authorizationcode:
              return await runvalidationasync(validateauthorizationcoderequestasync, parameters);
          case oidcconstants.granttypes.clientcredentials:
              return await runvalidationasync(validateclientcredentialsrequestasync, parameters);
          case oidcconstants.granttypes.password:  //1、密码授权模式调用方法
              return await runvalidationasync(validateresourceownercredentialrequestasync, parameters);
          case oidcconstants.granttypes.refreshtoken:
              return await runvalidationasync(validaterefreshtokenrequestasync, parameters);
          default:
              return await runvalidationasync(validateextensiongrantrequestasync, parameters);
      }
    }
  • 2、启用密码授权模式校验规则,首先校验传输的参数和scope是否存在,然后校验用户名密码是否准确,最后校验用户是否可用。

    private async task<tokenrequestvalidationresult> validateresourceownercredentialrequestasync(namevaluecollection parameters)
    {
        _logger.logdebug("start resource owner password token request validation");
    
        /////////////////////////////////////////////
        // 校验授权模式
        /////////////////////////////////////////////
        if (!_validatedrequest.client.allowedgranttypes.contains(granttype.resourceownerpassword))
        {
            logerror("{clientid} not authorized for resource owner flow, check the allowedgranttypes of client", _validatedrequest.client.clientid);
            return invalid(oidcconstants.tokenerrors.unauthorizedclient);
        }
    
        /////////////////////////////////////////////
        // 校验客户端是否允许这些scope
        /////////////////////////////////////////////
        if (!(await validaterequestedscopesasync(parameters)))
        {
            return invalid(oidcconstants.tokenerrors.invalidscope);
        }
    
        /////////////////////////////////////////////
        // 校验参数是否为定义的用户名或密码参数
        /////////////////////////////////////////////
        var username = parameters.get(oidcconstants.tokenrequest.username);
        var password = parameters.get(oidcconstants.tokenrequest.password);
    
        if (username.ismissing() || password.ismissing())
        {
            logerror("username or password missing");
            return invalid(oidcconstants.tokenerrors.invalidgrant);
        }
    
        if (username.length > _options.inputlengthrestrictions.username ||
            password.length > _options.inputlengthrestrictions.password)
        {
            logerror("username or password too long");
            return invalid(oidcconstants.tokenerrors.invalidgrant);
        }
    
        _validatedrequest.username = username;
    
    
        /////////////////////////////////////////////
        // 校验用户名和密码是否准确
        /////////////////////////////////////////////
        var resourceownercontext = new resourceownerpasswordvalidationcontext
        {
            username = username,
            password = password,
            request = _validatedrequest
        };
        //默认使用的是 testuserresourceownerpasswordvalidator
        await _resourceownervalidator.validateasync(resourceownercontext);
    
        if (resourceownercontext.result.iserror)
        {
            if (resourceownercontext.result.error == oidcconstants.tokenerrors.unsupportedgranttype)
            {
                logerror("resource owner password credential grant type not supported");
                await raisefailedresourceownerauthenticationeventasync(username, "password grant type not supported");
    
                return invalid(oidcconstants.tokenerrors.unsupportedgranttype, customresponse: resourceownercontext.result.customresponse);
            }
    
            var errordescription = "invalid_username_or_password";
    
            if (resourceownercontext.result.errordescription.ispresent())
            {
                errordescription = resourceownercontext.result.errordescription;
            }
    
            loginfo("user authentication failed: {error}", errordescription ?? resourceownercontext.result.error);
            await raisefailedresourceownerauthenticationeventasync(username, errordescription);
    
            return invalid(resourceownercontext.result.error, errordescription, resourceownercontext.result.customresponse);
        }
    
        if (resourceownercontext.result.subject == null)
        {
            var error = "user authentication failed: no principal returned";
            logerror(error);
            await raisefailedresourceownerauthenticationeventasync(username, error);
    
            return invalid(oidcconstants.tokenerrors.invalidgrant);
        }
    
        /////////////////////////////////////////////
        // 设置用户可用,比如用户授权后被锁定,可以通过此方法实现 默认实现 testuserprofileservice
        /////////////////////////////////////////////
        var isactivectx = new isactivecontext(resourceownercontext.result.subject, _validatedrequest.client, identityserverconstants.profileisactivecallers.resourceownervalidation);
        await _profile.isactiveasync(isactivectx);
    
        if (isactivectx.isactive == false)
        {
            logerror("user has been disabled: {subjectid}", resourceownercontext.result.subject.getsubjectid());
            await raisefailedresourceownerauthenticationeventasync(username, "user is inactive");
    
            return invalid(oidcconstants.tokenerrors.invalidgrant);
        }
    
        _validatedrequest.username = username;
        _validatedrequest.subject = resourceownercontext.result.subject;
    
        await raisesuccessfulresourceownerauthenticationeventasync(username, resourceownercontext.result.subject.getsubjectid());
        _logger.logdebug("resource owner password token request validation success.");
        return valid(resourceownercontext.result.customresponse);
    }
  • 3、运行自定义上下文验证

    private async task<tokenrequestvalidationresult> runvalidationasync(func<namevaluecollection, task<tokenrequestvalidationresult>> validationfunc, namevaluecollection parameters)
    {
        // 执行步骤2验证
        var result = await validationfunc(parameters);
        if (result.iserror)
        {
            return result;
        }
    
        // 运行自定义验证,ids4 默认有个 defaultcustomtokenrequestvalidator 实现,如果需要扩充其他验证,可以集成icustomtokenrequestvalidator单独实现。
        _logger.logtrace("calling into custom request validator: {type}", _customrequestvalidator.gettype().fullname);
    
        var customvalidationcontext = new customtokenrequestvalidationcontext { result = result };
        await _customrequestvalidator.validateasync(customvalidationcontext);
    
        if (customvalidationcontext.result.iserror)
        {
            if (customvalidationcontext.result.error.ispresent())
            {
                logerror("custom token request validator error {error}", customvalidationcontext.result.error);
            }
            else
            {
                logerror("custom token request validator error");
            }
    
            return customvalidationcontext.result;
        }
    
        logsuccess();
        return customvalidationcontext.result;
    }

    通过源码剖析可以发现,ids4给了我们很多的验证方式,并且默认也实现的验证和自定义的扩展,这样如果我们需要使用密码授权模式,就可以重写iresourceownerpasswordvalidator来实现系统内部用户系统的验证需求。如果需要确认用户在登录以后是否被注销时,可以重写iprofileservice接口实现,这个验证主要是生成token校验时检查。

  • 4、最终生成token

    根据不同的授权模式,生成不同的token记录。

    /// <summary>
    /// processes the response.
    /// </summary>
    /// <param name="request">the request.</param>
    /// <returns></returns>
    public virtual async task<tokenresponse> processasync(tokenrequestvalidationresult request)
    {
        switch (request.validatedrequest.granttype)
        {
            case oidcconstants.granttypes.clientcredentials:
                return await processclientcredentialsrequestasync(request);
            case oidcconstants.granttypes.password: //生成密码授权模式token
                return await processpasswordrequestasync(request);
            case oidcconstants.granttypes.authorizationcode:
                return await processauthorizationcoderequestasync(request);
            case oidcconstants.granttypes.refreshtoken:
                return await processrefreshtokenrequestasync(request);
            default:
                return await processextensiongrantrequestasync(request);
        }
    }
    
    /// <summary>
    /// creates the response for a password request.
    /// </summary>
    /// <param name="request">the request.</param>
    /// <returns></returns>
    protected virtual task<tokenresponse> processpasswordrequestasync(tokenrequestvalidationresult request)
    {
        logger.logtrace("creating response for password request");
    
        return processtokenrequestasync(request);
    }
    
    /// <summary>
    /// creates the response for a token request.
    /// </summary>
    /// <param name="validationresult">the validation result.</param>
    /// <returns></returns>
    protected virtual async task<tokenresponse> processtokenrequestasync(tokenrequestvalidationresult validationresult)
    {
        (var accesstoken, var refreshtoken) = await createaccesstokenasync(validationresult.validatedrequest);
        var response = new tokenresponse
        {
            accesstoken = accesstoken,
            accesstokenlifetime = validationresult.validatedrequest.accesstokenlifetime,
            custom = validationresult.customresponse
        };
    
        if (refreshtoken.ispresent())
        {
            response.refreshtoken = refreshtoken;
        }
    
        return response;
    }

    根据请求的scope判断是否生成refreshtoken,如果标记了offline_access,则生成refreshtoken,否则不生成。

    /// <summary>
    /// creates the access/refresh token.
    /// </summary>
    /// <param name="request">the request.</param>
    /// <returns></returns>
    /// <exception cref="system.invalidoperationexception">client does not exist anymore.</exception>
    protected virtual async task<(string accesstoken, string refreshtoken)> createaccesstokenasync(validatedtokenrequest request)
    {
        tokencreationrequest tokenrequest;
        bool createrefreshtoken;
      //授权码模式
        if (request.authorizationcode != null)
        {//是否包含refreshtoken
            createrefreshtoken = request.authorizationcode.requestedscopes.contains(identityserverconstants.standardscopes.offlineaccess);
    
            // load the client that belongs to the authorization code
            client client = null;
            if (request.authorizationcode.clientid != null)
            {
                client = await clients.findenabledclientbyidasync(request.authorizationcode.clientid);
            }
            if (client == null)
            {
                throw new invalidoperationexception("client does not exist anymore.");
            }
    
            var resources = await resources.findenabledresourcesbyscopeasync(request.authorizationcode.requestedscopes);
    
            tokenrequest = new tokencreationrequest
            {
                subject = request.authorizationcode.subject,
                resources = resources,
                validatedrequest = request
            };
        }
        else
        {//是否包含refreshtoken
            createrefreshtoken = request.validatedscopes.containsofflineaccessscope;
    
            tokenrequest = new tokencreationrequest
            {
                subject = request.subject,
                resources = request.validatedscopes.grantedresources,
                validatedrequest = request
            };
        }
    
        var at = await tokenservice.createaccesstokenasync(tokenrequest);
        var accesstoken = await tokenservice.createsecuritytokenasync(at);
    
        if (createrefreshtoken)
        {
            var refreshtoken = await refreshtokenservice.createrefreshtokenasync(tokenrequest.subject, at, request.client);
            return (accesstoken, refreshtoken);
        }
    
        return (accesstoken, null);
    }
  • 5、refreshtoken持久化

    当我们使用了offline_access时,就需要生成refreshtoken并进行持久化,详细的实现代码如下。

    public virtual async task<string> createrefreshtokenasync(claimsprincipal subject, token accesstoken, client client)
    {
        _logger.logdebug("creating refresh token");
    
        int lifetime;
        if (client.refreshtokenexpiration == tokenexpiration.absolute)
        {
            _logger.logdebug("setting an absolute lifetime: " + client.absoluterefreshtokenlifetime);
            lifetime = client.absoluterefreshtokenlifetime;
        }
        else
        {
            _logger.logdebug("setting a sliding lifetime: " + client.slidingrefreshtokenlifetime);
            lifetime = client.slidingrefreshtokenlifetime;
        }
    
        var refreshtoken = new refreshtoken
        {
            creationtime = clock.utcnow.utcdatetime,
            lifetime = lifetime,
            accesstoken = accesstoken
        };
      //存储refreshtoken并返回值
        var handle = await refreshtokenstore.storerefreshtokenasync(refreshtoken);
        return handle;
    }
    
    /// <summary>
    /// 存储refreshtoken并返回
    /// </summary>
    /// <param name="refreshtoken">the refresh token.</param>
    /// <returns></returns>
    public async task<string> storerefreshtokenasync(refreshtoken refreshtoken)
    {
        return await createitemasync(refreshtoken, refreshtoken.clientid, refreshtoken.subjectid, refreshtoken.creationtime, refreshtoken.lifetime);
    }
    
    /// <summary>
    /// 创建item
    /// </summary>
    /// <param name="item">the item.</param>
    /// <param name="clientid">the client identifier.</param>
    /// <param name="subjectid">the subject identifier.</param>
    /// <param name="created">the created.</param>
    /// <param name="lifetime">the lifetime.</param>
    /// <returns></returns>
    protected virtual async task<string> createitemasync(t item, string clientid, string subjectid, datetime created, int lifetime)
    {
        var handle = await handlegenerationservice.generateasync(); //生成随机值
        await storeitemasync(handle, item, clientid, subjectid, created, created.addseconds(lifetime)); //存储
        return handle;
    }
    
    /// <summary>
    /// 存储refreshtoken
    /// </summary>
    /// <param name="key">the key.</param>
    /// <param name="item">the item.</param>
    /// <param name="clientid">the client identifier.</param>
    /// <param name="subjectid">the subject identifier.</param>
    /// <param name="created">the created.</param>
    /// <param name="expiration">the expiration.</param>
    /// <returns></returns>
    protected virtual async task storeitemasync(string key, t item, string clientid, string subjectid, datetime created, datetime? expiration)
    {
        key = gethashedkey(key);
    
        var json = serializer.serialize(item);
    
        var grant = new persistedgrant
        {
            key = key,
            type = granttype,
            clientid = clientid,
            subjectid = subjectid,
            creationtime = created,
            expiration = expiration,
            data = json
        };
    
        await store.storeasync(grant);
    }
    
    //ipersistedgrantstore 我们在dapper持久化时已经实现了storeasync方式,是不是都关联起来了。

    至此,我们整个密码授权模式全部讲解完成,相信大家跟我一样完全掌握了授权的整个流程,如果需要持久化如何进行持久化流程。

理解了完整的密码授权模式流程后,使用自定义的用户体系就得心应手了,下面就开始完整的实现自定义帐户授权。

三、设计自定义的账户信息并应用

为了演示方便,我这里就设计简单的用户帐户信息,作为自定义的哦帐户基础,如果正式环境中使用,请根据各自业务使用各自的帐户体系即可。

-- 创建用户表
create table czarusers
(
    uid int identity(1,1),            --用户主键    
    uaccount varchar(11),             --用户账号
    upassword varchar(200),           --用户密码
    unickname varchar(50),            --用户昵称
    umobile varchar(11),              --用户手机号
    uemail varchar(100),              --用户邮箱
    ustatus int not null default(1)   -- 用户状态 1 正常 0 不可用
)

添加用户实体代码如下所示。

/// <summary>
/// 授权用户信息
/// </summary>
public class czarusers
{
    public czarusers() { }

    public int uid { get; set; }
    public string uaccount { get; set; }
    public string upassword { get; set; }
    public string unickname { get; set; }
    public string umobile { get; set; }
    public string uemail { get; set; }
    public string ustatus { get; set; }
}

下面开始密码授权模式开发,首先需要重新实现iresourceownerpasswordvalidator接口,使用我们定义的用户表来验证请求的用户名和密码信息。

/// <summary>
/// 金焰的世界
/// 2018-12-18
/// 自定义用户名密码校验
/// </summary>
public class czarresourceownerpasswordvalidator : iresourceownerpasswordvalidator
    {
        private readonly iczarusersservices _czarusersservices;
        public czarresourceownerpasswordvalidator(iczarusersservices czarusersservices)
        {
            _czarusersservices = czarusersservices;
        }
        /// <summary>
        /// 验证用户身份
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public task validateasync(resourceownerpasswordvalidationcontext context)
        {
            var user = _czarusersservices.finduserbyuaccount(context.username, context.password);
            if (user != null)
            {
                context.result = new grantvalidationresult(
                    user.uid.tostring(),
                    oidcconstants.authenticationmethods.password, 
                    datetime.utcnow);
            }
            return task.completedtask;
        }
    }

编写完自定义校验后,我们需要注入到具体的实现,详细代码如下。

public void configureservices(iservicecollection services)
{
    services.addsingleton(configuration);
    services.configure<czarconfig>(configuration.getsection("czarconfig"));
    services.addidentityserver(option=> {
        option.publicorigin = configuration["czarconfig:publicorigin"];
    })
        .adddevelopersigningcredential()
        .adddapperstore(option =>
                        {
                            option.dbconnectionstrings = configuration["czarconfig:dbconnectionstrings"];
                        })
        //使用自定义的密码校验
        .addresourceownervalidator<czarresourceownerpasswordvalidator>()
        ;
    //  .usemysql();


    services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1);
}

剩下的就是把iczarusersservices接口实现并注入即可。详细代码如下。

/// <summary>
/// 金焰的世界
/// 2018-12-18
/// 用户服务接口
/// </summary>
public interface iczarusersservices
{
    /// <summary>
    /// 根据账号密码获取用户实体
    /// </summary>
    /// <param name="uaccount">账号</param>
    /// <param name="upassword">密码</param>
    /// <returns></returns>
    czarusers finduserbyuaccount(string uaccount, string upassword);

    /// <summary>
    /// 根据用户主键获取用户实体
    /// </summary>
    /// <param name="sub">用户标识</param>
    /// <returns></returns>
    czarusers finduserbyuid(string sub);
}

/// <summary>
/// 金焰的世界
/// 2018-12-18
/// 用户服务实现
/// </summary>
public class czarusersservices : iczarusersservices
    {
        private readonly iczarusersrepository _czarusersrepository;
        public czarusersservices(iczarusersrepository czarusersrepository)
        {
            _czarusersrepository = czarusersrepository;
        }

        /// <summary>
        /// 根据账号密码获取用户实体
        /// </summary>
        /// <param name="uaccount">账号</param>
        /// <param name="upassword">密码</param>
        /// <returns></returns>
        public czarusers finduserbyuaccount(string uaccount, string upassword)
        {
            return _czarusersrepository.finduserbyuaccount(uaccount, upassword);
        }

        /// <summary>
        /// 根据用户主键获取用户实体
        /// </summary>
        /// <param name="sub">用户标识</param>
        /// <returns></returns>
        public czarusers finduserbyuid(string sub)
        {
            return _czarusersrepository.finduserbyuid(sub);
        }
    }

最后我们实现仓储接口和方法,即可完成校验流程。

/// <summary>
/// 金焰的世界
/// 2018-12-18
/// 用户仓储接口
/// </summary>
public interface iczarusersrepository
{
    /// <summary>
    /// 根据账号密码获取用户实体
    /// </summary>
    /// <param name="uaccount">账号</param>
    /// <param name="upassword">密码</param>
    /// <returns></returns>
    czarusers finduserbyuaccount(string uaccount, string upassword);

    /// <summary>
    /// 根据用户主键获取用户实体
    /// </summary>
    /// <param name="sub">用户标识</param>
    /// <returns></returns>
    czarusers finduserbyuid(string sub);
}

/// <summary>
/// 金焰的世界
/// 2018-12-18
/// 用户实体基于sqlserver的实现
/// </summary>
public class czarusersrepository : iczarusersrepository
    {
        private readonly string dbconn = "";
        public czarusersrepository(ioptions<czarconfig> czarconfig)
        {
            dbconn = czarconfig.value.dbconnectionstrings;
        }
        /// <summary>
        /// 根据账号密码获取用户实体
        /// </summary>
        /// <param name="uaccount">账号</param>
        /// <param name="upassword">密码</param>
        /// <returns></returns>
        public czarusers finduserbyuaccount(string uaccount, string upassword)
        {
            using (var connection = new sqlconnection(dbconn))
            {
                string sql = @"select * from czarusers where uaccount=@uaccount and upassword=upassword and ustatus=1";
                var result = connection.queryfirstordefault<czarusers>(sql, new { uaccount, upassword = secrethelper.tomd5(upassword) });
                return result;
            }
        }

        /// <summary>
        /// 根据用户主键获取用户实体
        /// </summary>
        /// <param name="sub">用户标识</param>
        /// <returns></returns>
        public czarusers finduserbyuid(string sub)
        {
            using (var connection = new sqlconnection(dbconn))
            {
                string sql = @"select * from czarusers where uid=@uid";
                var result = connection.queryfirstordefault<czarusers>(sql, new { uid=sub });
                return result;
            }
        }
    }

现在万事俱备,之前注入和插入测试用户数据进行测试了,为了方便注入,我们采用autofac程序集注册。

/// <summary>
/// 金焰的世界
/// 2018-12-18
/// 使用程序集注册
/// </summary>
public class czarmodule : autofac.module
    {
        protected override void load(containerbuilder builder)
        {
            //注册repository程序集
            builder.registerassemblytypes(typeof(czarusersrepository).gettypeinfo().assembly).asimplementedinterfaces().instanceperlifetimescope();
            //注册services程序集
            builder.registerassemblytypes(typeof(czarusersservices).gettypeinfo().assembly).asimplementedinterfaces().instanceperlifetimescope();
        }
    }

然后需要修改configureservices代码如下,就完成了仓储和服务层的注入。

public iserviceprovider configureservices(iservicecollection services)
{
    services.addsingleton(configuration);
    services.configure<czarconfig>(configuration.getsection("czarconfig"));
    services.addidentityserver(option=> {
        option.publicorigin = configuration["czarconfig:publicorigin"];
    })
        .adddevelopersigningcredential()
        .adddapperstore(option =>
                        {
                            option.dbconnectionstrings = configuration["czarconfig:dbconnectionstrings"];
                        })
        .addresourceownervalidator<czarresourceownerpasswordvalidator>()
        ;
    //  .usemysql();


    services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1);

    //使用autofac进行注入
    var container = new containerbuilder();
    container.registermodule(new czarmodule());
    container.populate(services);
    return new autofacserviceprovider(container.build());
}

为了验证密码授权模式信息,这里需要往数据库插入测试的用户数据,插入脚本如下。

--密码123456  md5加密结果
insert into czarusers values('13888888888','e10adc3949ba59abbe56e057f20f883e','金焰的世界','13888888888','541869544@qq.com',1); 

四、测试密码授权模式

注意:测试密码授权模式之前,我们需要对测试的客户端clientgranttypes表添加password授权方式。

打开我们的测试神器postman,然后开始调试密码授权模式,测试结果如下图所示。
【.NET Core项目实战-统一认证平台】第十一章 授权篇-密码授权模式

是不是很完美,得到了我们想要的授权结果,那我们查看下这个access_token是什么信息,可以使用查看到详细的内容,发现除了客户端信息和用户主键无其他附加信息,那如何添加自定义的claim信息呢?
【.NET Core项目实战-统一认证平台】第十一章 授权篇-密码授权模式

先修改下czarusers实体,增加如下代码,如果有其他属性可自行扩展。

public list<claim> claims
        {
            get
            {
                return new list<claim>() {
                    new claim("nickname",unickname??""),
                    new claim("email",uemail??""),
                    new claim("mobile",umobile??"")
                };
            }
        }

再修改校验方法,增加claim输出,czarresourceownerpasswordvalidator修改代码如下。

/// <summary>
/// 验证用户身份
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public task validateasync(resourceownerpasswordvalidationcontext context)
{
    var user = _czarusersservices.finduserbyuaccount(context.username, context.password);
    if (user != null)
    {
        context.result = new grantvalidationresult(
            user.uid.tostring(),
            oidcconstants.authenticationmethods.password, 
            datetime.utcnow,
            user.claims);
    }
    return task.completedtask;
}

然后需要把用户的claims应用到token,这里我们需要重写iprofileservice,然后把用户的claim输出,实现代码如下。

public class czarprofileservice : iprofileservice
    {
        public task getprofiledataasync(profiledatarequestcontext context)
        {
            //把用户返回的claims应用到返回
            context.issuedclaims = context.subject.claims.tolist();
            return task.completedtask;
        }

        /// <summary>
        /// 验证用户是否有效
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public task isactiveasync(isactivecontext context)
        {
            context.isactive = true;
            return task.completedtask;
        }
    }

然后别忘了注入.addprofileservice<czarprofileservice>(),好了现在我们再次测试下授权,最终得到的结果如下所示。
【.NET Core项目实战-统一认证平台】第十一章 授权篇-密码授权模式

奈斯,得到了我们预期授权结果。

那如何获取refresh_token呢?通过前面的介绍,我们需要增加scopeoffline_access,并且需要设置客户端支持,因此allowofflineaccess属性需要设置为true,现在来测试下获取的授权结果。
【.NET Core项目实战-统一认证平台】第十一章 授权篇-密码授权模式

最终完成了refresh_token的获取,至此整个密码授权模式全部讲解并实现完成。

五、总结及思考

本篇文章我们从密码授权模式使用场景、源码剖析、自定义用户授权来讲解了密码授权模式的详细思路和代码实现,从中不难发现ids4设计的巧妙,在默认实现的同时也预留了很多自定义扩展,本篇的自定义用户体系也是重新实现接口然后注入就完成集成工作。本篇主要难点就是要理解ids4的实现思路和数据库的相关配置,希望通过本篇的讲解让我们熟练掌握密码验证的流程,便于应用到实际生产环境。

上篇的客户端授权模式和本篇的密码授权模式都讲解完可能有人会存在以下几个疑问。

  • 1、如何校验令牌信息的有效性?
  • 2、如何强制有效令牌过期?
  • 3、如何实现单机登录?

下篇文章我将会从这3个疑问出发,来详细讲解下这三个问题的实现思路和代码。
【.NET Core项目实战-统一认证平台】第十一章 授权篇-密码授权模式