예제 #1
0
        /// <summary>登录成功</summary>
        /// <param name="client">OAuth客户端</param>
        /// <param name="service">服务提供者。可用于获取HttpContext成员</param>
        /// <returns></returns>
        public virtual String OnLogin(OAuthClient client, IServiceProvider service)
        {
            var openid = client.OpenID;

            if (openid.IsNullOrEmpty())
            {
                openid = client.UserName;
            }

            // 根据OpenID找到用户绑定信息
            var uc = UserConnect.FindByProviderAndOpenID(client.Name, openid);

            if (uc == null)
            {
                uc = new UserConnect {
                    Provider = client.Name, OpenID = openid
                }
            }
            ;

            uc.Fill(client);

            // 强行绑定,把第三方账号强行绑定到当前已登录账号
            var forceBind = false;
            var req       = service.GetService <HttpRequest>();

            if (req != null)
            {
                forceBind = req["sso_action"].EqualIgnoreCase("bind");
            }

            // 检查绑定
            var user = Provider.FindByID(uc.UserID);

            if (forceBind || user == null || !uc.Enable)
            {
                user = OnBind(uc, client);
            }

            // 填充昵称等数据
            Fill(client, user);

            if (user is IAuthUser user3)
            {
                user3.Save();
            }
            uc.Save();

            if (!user.Enable)
            {
                throw new InvalidOperationException("用户已禁用!");
            }

            // 登录成功,保存当前用户
            Provider.Current = user;

            return(SuccessUrl);
        }
예제 #2
0
        /// <summary>登录成功</summary>
        /// <param name="client">OAuth客户端</param>
        /// <param name="context">服务提供者。可用于获取HttpContext成员</param>
        /// <returns></returns>
        public virtual String OnLogin(OAuthClient client, IServiceProvider context)
        {
            var openid = client.OpenID;

            if (openid.IsNullOrEmpty())
            {
                openid = client.UserName;
            }

            // 根据OpenID找到用户绑定信息
            var uc = UserConnect.FindByProviderAndOpenID(client.Name, openid);

            if (uc == null)
            {
                uc = new UserConnect {
                    Provider = client.Name, OpenID = openid
                }
            }
            ;

            uc.Fill(client);

            // 强行绑定,把第三方账号强行绑定到当前已登录账号
            var forceBind = false;
            var req       = context.GetService <HttpRequest>();

            if (req != null)
            {
                forceBind = req.GetRequestValue("sso_action").EqualIgnoreCase("bind");
            }

            // 检查绑定,新用户的uc.UserID为0
            var prv  = Provider;
            var user = prv.FindByID(uc.UserID);

            if (forceBind || user == null || !uc.Enable)
            {
                user = OnBind(uc, client);
            }

            // 填充昵称等数据
            Fill(client, user);

            if (user is IAuthUser user3)
            {
                user3.Logins++;
                user3.LastLogin   = DateTime.Now;
                user3.LastLoginIP = WebHelper.UserHost;
                user3.Save();
            }

            try
            {
                uc.Save();
            }
            catch (Exception ex)
            {
                //为了防止某些特殊数据导致的无法正常登录,把所有异常记录到日志当中。忽略错误
                XTrace.WriteException(ex);
            }

            if (!user.Enable)
            {
                throw new InvalidOperationException("用户已禁用!");
            }

            // 登录成功,保存当前用户
            //prv.Current = user;
            prv.SetCurrent(user, context);
            // 单点登录不要保存Cookie,让它在Session过期时请求认证中心
            //prv.SaveCookie(user);
            var set = Setting.Current;

            if (set.SessionTimeout > 0)
            {
                prv.SaveCookie(user, TimeSpan.FromSeconds(set.SessionTimeout), context);
            }

            LogProvider.Provider.WriteLog(user.GetType(), client.Name, "单点登录", user.ID, user + "", req.GetDisplayUrl());//.UserHostAddress);

            return(SuccessUrl);
        }
        /// <summary>
        /// 获取或创建用户
        /// </summary>
        /// <returns></returns>
        private async Task <IManageUser> GetOrCreateUserAsync(ClaimsPrincipal user, AuthenticationProperties properties)
        {
            var options  = Options;
            var provider = properties.Items["scheme"];
            var openid   = user.FindFirstValue(OAuthSignInAuthenticationDefaults.Sub);

            var uc = UserConnect.FindByProviderAndOpenID(provider, openid);

            IManageUser appUser;

            if (uc == null)
            {
                if (!options.CreateUserOnOAuthLogin)
                {
                    throw ApiException.Common("用户不存在,请联系管理员");
                }

                uc = new UserConnect()
                {
                    Provider = provider, OpenID = openid, Enable = true
                };
                uc.Fill(user);

                appUser = new ApplicationUser {
                    Name = Guid.NewGuid().ToString().Substring(0, 8), Enable = true, RoleID = 4
                };                                                                                                            // 角色id 4 为游客

                // 此处可改用本系统服务替换,去除ApplicationUser依赖
                var result = await _userManager.CreateAsync(appUser as ApplicationUser, "123456");

                if (!result.Succeeded)
                {
                    throw ApiException.Common($"创建用户失败:{result.Errors.First().Description}");
                }

                uc.UserID = appUser.ID;
            }
            else
            {
                appUser = await _userManager.FindByIdAsync(uc.UserID.ToString());
            }

            if (!appUser.Enable)
            {
                throw ApiException.Common($"用户已被禁用");
            }

            // 填充用户信息
            Fill(appUser, user);

            if (appUser is IAuthUser user3)
            {
                user3.Logins++;
                user3.LastLogin   = DateTime.Now;
                user3.LastLoginIP = Request.Host.Host;
                user3.Save();
            }

            try
            {
                uc.Save();
            }
            catch (Exception ex)
            {
                //为了防止某些特殊数据导致的无法正常登录,把所有异常记录到日志当中。忽略错误
                XTrace.WriteException(ex);
            }

            return(appUser);
        }
예제 #4
0
        /// <summary>登录成功</summary>
        /// <param name="client">OAuth客户端</param>
        /// <param name="context">服务提供者。可用于获取HttpContext成员</param>
        /// <returns></returns>
        public virtual String OnLogin(OAuthClient client, IServiceProvider context)
        {
            var openid = client.OpenID;

            if (openid.IsNullOrEmpty())
            {
                openid = client.UserName;
            }

            // 根据OpenID找到用户绑定信息
            var uc = UserConnect.FindByProviderAndOpenID(client.Name, openid);

            if (uc == null)
            {
                uc = new UserConnect {
                    Provider = client.Name, OpenID = openid
                }
            }
            ;

            uc.Fill(client);

            // 强行绑定,把第三方账号强行绑定到当前已登录账号
            var forceBind = false;

#if __CORE__
            var httpContext = context.GetService <IHttpContextAccessor>().HttpContext;
            var req         = httpContext.Request;
            var ip          = httpContext.GetUserHost();
#else
            var req = context.GetService <HttpRequest>();
            var ip  = req.RequestContext.HttpContext.GetUserHost();
#endif
            //if (req != null) forceBind = req.Get("sso_action").EqualIgnoreCase("bind");
            if (req != null)
            {
                forceBind = req.Get("state").EndsWithIgnoreCase("_bind");
            }

            // 可能因为初始化顺序的问题,导致前面没能给Provider赋值
            var prv = Provider;
            if (prv == null)
            {
                prv = Provider = ManageProvider.Provider;
            }

            // 检查绑定,新用户的uc.UserID为0
            var user = prv.FindByID(uc.UserID);
            if (forceBind || user == null || !uc.Enable)
            {
                user = OnBind(uc, client);
            }

            // 填充昵称等数据
            Fill(client, user);

            if (user is IAuthUser user3)
            {
                user3.Logins++;
                user3.LastLogin   = DateTime.Now;
                user3.LastLoginIP = ip;
                //user3.Save();
                (user3 as IEntity).Update();
            }

            try
            {
                uc.Save();
            }
            catch (Exception ex)
            {
                //为了防止某些特殊数据导致的无法正常登录,把所有异常记录到日志当中。忽略错误
                XTrace.WriteException(ex);
            }

            // 写日志
            var log = LogProvider.Provider;
            log?.WriteLog(typeof(UserX), "SSO登录", $"[{user}]从[{client.Name}]的[{client.UserName}]登录", user.ID, user + "");

            if (!user.Enable)
            {
                throw new InvalidOperationException("用户已禁用!");
            }

            // 登录成功,保存当前用户
            //prv.Current = user;
            prv.SetCurrent(user, context);
            // 单点登录不要保存Cookie,让它在Session过期时请求认证中心
            //prv.SaveCookie(user);
            var set = Setting.Current;
            if (set.SessionTimeout > 0)
#if __CORE__
            { ManagerProviderHelper.SaveCookie(prv, user, TimeSpan.FromSeconds(set.SessionTimeout), httpContext); }
#else
            { prv.SaveCookie(user, TimeSpan.FromSeconds(set.SessionTimeout), context); }
#endif

            return(SuccessUrl);
        }
예제 #5
0
        /// <summary>
        /// 获取或创建用户
        /// </summary>
        /// <returns></returns>
        public virtual async Task <IManageUser> GetOrCreateUserAsync(ClaimsPrincipal user, AuthenticationProperties properties, bool createUserOnOAuthLogin)
        {
            var provider = properties.Items["scheme"];
            var openid   = user.FindFirstValue(OAuthSignInAuthenticationDefaults.Sub);

            var uc = UserConnect.FindByProviderAndOpenID(provider, openid);

            IManageUser appUser;

            if (uc == null)
            {
                if (!createUserOnOAuthLogin)
                {
                    throw ApiException.Common(_requestLocalizer["The user does not exist, please contact the administrator"]);
                }

                uc = new UserConnect()
                {
                    Provider = provider, OpenID = openid, Enable = true
                };
                uc.Fill(user);

                appUser = new TUser
                {
                    Name   = Guid.NewGuid().ToString().Substring(0, 8),
                    Enable = true,
                    RoleID = 4
                }; // 角色id 4 为游客

                // 通过第三方登录创建的用户设置随机密码
                var result = await _userManager.CreateAsync((TUser)appUser, Guid.NewGuid().ToString().Substring(0, 8));

                if (!result.Succeeded)
                {
                    throw ApiException.Common($"{_requestLocalizer["Failed to create user"]}:{_requestLocalizer[result.Errors.First().Description]}");
                }

                uc.UserID = appUser.ID;
            }
            else
            {
                appUser = await _userManager.FindByIdAsync(uc.UserID.ToString()) as IManageUser;
            }

            if (appUser == null)
            {
                throw ApiException.Common(_requestLocalizer["The user was not found"]);
            }

            if (!appUser.Enable)
            {
                throw ApiException.Common(_requestLocalizer["The user has been disabled"]);
            }

            // 填充用户信息
            Fill(appUser, user);

            if (appUser is IAuthUser user3)
            {
                user3.Logins++;
                user3.LastLogin = DateTime.Now;
                //user3.LastLoginIP = Request.Host.Host;
                user3.Save();
            }

            try
            {
                uc.Save();
            }
            catch (Exception ex)
            {
                //为了防止某些特殊数据导致的无法正常登录,把所有异常记录到日志当中。忽略错误
                XTrace.WriteException(ex);
            }

            return(appUser);
        }