Beispiel #1
0
        /// <summary>
        /// 对具体用户账号与密码进行授权
        /// 客户端访问方式必须是"grant_type" = "password"
        /// 通过客户端的context.UserName与context.Password获取客户端传递的用户验证信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //var tenantId = context.Request.Query["tenantId"];

            //此处只做简单判断验证,可以添加自定义的验证逻辑
            if (string.IsNullOrEmpty(context.UserName))
            {
                context.SetError("未提供用户账号信息.");
                context.Rejected();
                return;
            }
            //password验证需要通过 UserName 以及 Password获取,因此需要重新添加到到clientId与clientSecret便于生成restoken
            context.OwinContext.Set <string>("clientId", context.UserName);
            context.OwinContext.Set <string>("clientSecret", context.Password);

            #region 验证登录信息
            //获取登录用户信息
            UserInfo userModel = _userInfoRepository.GetUserInfoByUserCode(context.UserName);
            //验证用户信息
            if (userModel == null)
            {
                throw new UserFriendlyException(nameof(LoginResultType.InvalidUserNameOrEmailAddress), "用户账号无效!");
            }
            //未激活的用户不做登录
            if (!userModel.IsActive)
            {
                throw new UserFriendlyException(nameof(LoginResultType.UserIsNotActive), "用户未激活!");
            }
            //验证登录的密码
            var verificationResult = _userInfoManager.VerifyPassword(userModel.Password, context.Password);
            if (!verificationResult)
            {
                throw new UserFriendlyException(nameof(LoginResultType.InvalidPassword), "用户密码无效!");
            }
            SysLoginResult <UserInfo> sysLoginResult = await _userInfoManager.CreateIdentityAsync(userModel);

            #endregion

            //设置登录验证成功后获取到的授权信息
            var oAuthIdentity = new ClaimsIdentity(sysLoginResult.Identity);
            //var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            //授权安全令牌后,记录当前授权用户id 到安全令牌对象中
            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "as:clientId", context.UserName }
            });
            //
            var ticket = new AuthenticationTicket(oAuthIdentity, props);
            context.Validated(ticket);
            //return Task.FromResult<object>(null);
            //return await base.GrantResourceOwnerCredentials(context);
        }