示例#1
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (string.IsNullOrEmpty(context.UserName))
            {
                context.SetError(ErrorOAuthCode.Invalid_Email, "邮箱不能为空");
                return;
            }

            if (string.IsNullOrEmpty(context.Password))
            {
                context.SetError(ErrorOAuthCode.Invalid_Password, "密码不能为空");
                return;
            }

            //从数据库获取用户和角色信息
            bool loginResult = userRepository.LoginApp(context.UserName, context.Password, null, null);

            if (!loginResult)
            {
                context.SetError(ErrorOAuthCode.Invalid_Account, "邮箱或者密码不正确");
                return;
            }
            var userRole = userRepository.GetUser(context.UserName);
            UserClaimsInfoModel userClaimsInfoModel = this.identityService.CreateUserClaimsInfoModelFromUserRepoModel(userRole);
            var claimsIdentity = identityService.CreateClaimsIdentity(context.Options.AuthenticationType, userClaimsInfoModel);

            var authenticationTicket = identityService.CreateAuthenticationTicket(claimsIdentity);

            context.Validated(authenticationTicket);

            await base.GrantResourceOwnerCredentials(context);
        }
示例#2
0
        public async Task <HttpResponseMessage> OAuthSuccessResponse(UserClaimsInfoModel userClaimsInfoModel)
        {
            DateTimeOffset currentUtc     = DateTimeOffset.UtcNow;
            DateTimeOffset expiresUtc     = currentUtc.Add(options.AccessTokenExpireTimeSpan);
            var            claimsIdentity = CreateClaimsIdentity(options.AuthenticationType, userClaimsInfoModel);
            var            ticket         = CreateAuthenticationTicket(claimsIdentity, null, currentUtc, expiresUtc);
            string         accessToken    = options.AccessTokenFormat.Protect(ticket);

            AuthenticationTokenCreateContext authenticationTokenCreateContext = new AuthenticationTokenCreateContext(null,
                                                                                                                     options.RefreshTokenFormat, ticket);
            await options.RefreshTokenProvider.CreateAsync(authenticationTokenCreateContext);

            string refreshToken = authenticationTokenCreateContext.Token;

            AccessTokenModel model = new AccessTokenModel();

            model.access_token  = accessToken;
            model.refresh_token = refreshToken;
            model.token_type    = "bearer";
            TimeSpan?expiresTimeSpan = expiresUtc - currentUtc;
            var      expiresIn       = (long)expiresTimeSpan.Value.TotalSeconds;

            if (expiresIn > 0)
            {
                model.expires_in = expiresIn;
            }
            return(GenerateOAuthRespose(model));
        }
示例#3
0
        //public static string CreateRefeshTokenAndSetTicketExpires(AuthenticationTicket ticket)
        //{
        //    string tokenValue = Guid.NewGuid().ToString("n");

        //    TimeSpan? expireTimeSpan = null;
        //    if (ticket.Properties.IssuedUtc.HasValue && ticket.Properties.ExpiresUtc.HasValue)
        //    {
        //        expireTimeSpan = ticket.Properties.ExpiresUtc.Value - ticket.Properties.IssuedUtc.Value;
        //        ticket.Properties.IssuedUtc = DateTimeOffset.UtcNow;
        //        ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddTicks(expireTimeSpan.Value.Ticks * 2);
        //    }
        //    return tokenValue;
        //}

        /// <summary>
        /// 创建身份声明
        /// </summary>
        /// <param name="authenticationType"></param>
        /// <param name="userRepoModel"></param>
        /// <returns></returns>
        public ClaimsIdentity CreateClaimsIdentity(string authenticationType, UserClaimsInfoModel userClaimsInfoModel)
        {
            var claimsIdentity = new ClaimsIdentity(authenticationType);

            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, userClaimsInfoModel.userID.ToString()));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, userClaimsInfoModel.mail));
            return(claimsIdentity);
        }
示例#4
0
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            string id = string.Empty;

            try
            {
                id = await AuthenticateWithThirdPartyApp(request);
            }
            catch (Exception ex)
            {
                ErrorOAtuhModel res = new ErrorOAtuhModel();
                res.error             = ErrorOAuthCode.Invalid_ThirdParty_OAuth;
                res.error_description = "第三方App认证失败";
                response = identityService.GenerateOAuthRespose(res);
                return(response);
            }
            bool loginRessult = userRepository.LoginApp(null, null, id, this.app_type);

            if (loginRessult)
            {
                var userRole = userRepository.GetUserByThirdPartyId(id, this.app_type);

                #region 当前第三方用户已经在本应用绑定过

                //根据绑定获取用户名和角色

                UserClaimsInfoModel userClaimsInfoModel = this.identityService.CreateUserClaimsInfoModelFromUserRepoModel(userRole);
                response = await identityService.OAuthSuccessResponse(userClaimsInfoModel);

                #endregion
            }
            else
            {
                #region 当前第三方用户尚未在本应用绑定过

                UnBindErrorOAuthModel res = new UnBindErrorOAuthModel();
                res.error             = ErrorOAuthCode.Invalid_bind_OAuth;
                res.error_description = "第三方App认证成功,但尚未与本地账号绑定";
                //要存储到redis中
                string relationAccountToken = Guid.NewGuid().ToString();
                RelationAccountModel relationAccountModel = new RelationAccountModel();
                relationAccountModel.from         = this.app_type;
                relationAccountModel.thirdPartyID = id;
                await relationAccountRepository.InsertRelationAccountModel(relationAccountToken, relationAccountModel, new TimeSpan(1, 0, 0));

                res.relationAccountID = relationAccountToken;
                response = identityService.GenerateOAuthRespose(res);


                #endregion
            }


            return(response);
        }
示例#5
0
        public UserClaimsInfoModel CreateUserClaimsInfoModelFromUserRepoModel(UserRepoModel userRepoModel)
        {
            UserClaimsInfoModel userClaimsInfoModel = null;

            if (userRepoModel != null)
            {
                userClaimsInfoModel        = new UserClaimsInfoModel();
                userClaimsInfoModel.userID = userRepoModel.info.userID;
                userClaimsInfoModel.mail   = userRepoModel.info.mail;
            }
            return(userClaimsInfoModel);
        }
示例#6
0
        /// <summary>
        /// 根据身份认证创建UserRepoModel对象
        /// </summary>
        /// <param name="claimsIdentity"></param>
        /// <returns></returns>
        public UserClaimsInfoModel CreateUserClaimsInfoModelFromClaimsIdentity(ClaimsIdentity claimsIdentity)
        {
            UserClaimsInfoModel userClaimsInfoModel = new UserClaimsInfoModel();

            int userID = 0;

            int.TryParse(claimsIdentity.Name, out userID);
            userClaimsInfoModel.userID = userID;

            userClaimsInfoModel.mail = claimsIdentity.FindFirst(ClaimTypes.Email).Value;

            return(userClaimsInfoModel);
        }