static void Main(string[] args) { SSOClient ssoClient = new SSOClient(); string ssoLoginName = ssoClient.GetCurrentLoginName(); if (!String.IsNullOrEmpty(ssoLoginName)) { string ssoPropertyName = "st"; if (!String.IsNullOrEmpty(ssoPropertyName)) { string ssoPropertyValue = ssoClient.GetProperty(ssoLoginName, ssoPropertyName); if (!String.IsNullOrEmpty(ssoPropertyValue)) { Int64 localId = Int64.Parse(ssoPropertyValue); if (localId > 0) { Console.WriteLine("ID: " + localId); Console.ReadLine(); } } } } }
public ActionResult SignIn(string code, string state) { try { if (string.IsNullOrEmpty(code)) { return(Redirect("/pages/error/error.html")); } OAuthAccessTokenResult result = OAuthApi.GetAccessToken(_appId, _secret, code); if (result.errcode != 0) { return(Redirect("/pages/error/error.html")); } SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == result.openid).FirstOrDefault(); if (userOpenId == null) { //逻辑1:跳转到绑定页面,适用于企业用户或已存在账号情况。 return(Redirect("/pages/account/bind.html?openid=" + result.openid)); //逻辑2:创建本地用户,适用公众网站,项目根据需要调整逻辑。 //var wxUser = OAuthApi.GetUserInfo(result.access_token, result.openid); //SysUser user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = wxUser.nickname; //user.UserCode = "wx" + Guid.NewGuid().ToString("N").Substring(18); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //userOpenId = new SysUserOpenId(); //userOpenId.OpenId = result.openid; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); } SSOClient.SignIn(userOpenId.UserId.Value); switch (state) { case "menu1": return(Redirect("/weixin/templates/exampleone.html")); case "menu2": return(Redirect("/weixin/templates/exampletow.html")); default: return(Redirect("/weixin/home/index.html")); } } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
static void Main(string[] args) { SSOClient ssoClient = new SSOClient(); string ssoLoginName = ssoClient.GetCurrentLoginName(); if (!String.IsNullOrEmpty(ssoLoginName)) { string ssoPropertyName = "st"; if (!String.IsNullOrEmpty(ssoPropertyName)) { string ssoPropertyValue = ssoClient.GetProperty(ssoLoginName, ssoPropertyName); if (!String.IsNullOrEmpty(ssoPropertyValue)) { Int64 localId = Int64.Parse(ssoPropertyValue); if (localId > 0) { Console.WriteLine("ID: " + localId); Console.ReadLine(); } } } } }
public ActionResult SMSCode(string account, string t) { try { if (!SSOClient.Validate(account, out SysUser user)) { return(Json(new { Code = 1, Msg = "帐号不存在,请重新输入!" })); } string code = VerifyHelper.CreateNumber(4); SMSService.Send(user.Mobile, code); dbContext.SysSmsCode.Add(new SysSmsCode() { Id = Guid.NewGuid(), Mobile = user.Mobile, CreateTime = DateTime.Now, OverTime = DateTime.Now.AddMinutes(3), IsVerify = 0, SmsCode = code, SmsSign = t }); dbContext.SaveChanges(); return(Json(new { Code = 0, Msg = "发送成功!" })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public JsonResult SMSLogin(string account, string t, string code) { try { if (!SSOClient.Validate(account, out SysUser user)) { return(Json(new { Code = 1, Msg = "帐号不存在,请重新输入!" })); } var item = dbContext.SysSmsCode.FirstOrDefault(x => x.Mobile == user.Mobile && x.SmsCode == code && x.SmsSign == t && x.OverTime > DateTime.Now); if (item == null) { return(Json(new { Code = 1, Msg = "验证码验证失败,请重新输入!" })); } item.IsVerify = 1; item.VerifyTime = DateTime.Now; dbContext.SaveChanges(); SSOClient.SignIn(user.UserId); return(Json(new { Code = 0 })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public JsonResult BindUser(string account, string password, string openId) { try { if (!SSOClient.Validate(account, password, out Guid userId)) { return(Json(new { Code = 1, Msg = "帐号或密码不正确,请重新输入!" })); } //公众号绑定 SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openId).FirstOrDefault(); if (userOpenId != null) { userOpenId.UserId = userId; userOpenId.BindTime = DateTime.Now; } else { userOpenId = new SysUserOpenId(); userOpenId.OpenId = openId; userOpenId.UserId = userId; userOpenId.CreateTime = DateTime.Now; userOpenId.BindTime = DateTime.Now; dbContext.SysUserOpenId.Add(userOpenId); } dbContext.SaveChanges(); SSOClient.SignIn(userId); return(Json(new { Code = 0 })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
private async Task Logout() { Logger.Log(DevopenspaceLoggerKeys.Logout, Category.Info, Priority.None); try { if (SSOClient != null) { await SSOClient.LogoutAsync(); } Settings.FirstName = string.Empty; Settings.LastName = string.Empty; Settings.Email = string.Empty; //this triggers login text changed! //drop favorites and feedback because we logged out. await StoreManager.FavoriteStore.DropFavorites(); await StoreManager.FeedbackStore.DropFeedback(); await StoreManager.DropEverythingAsync(); await ExecuteSyncCommandAsync(); } catch (Exception ex) { ex.Data["method"] = "ExecuteLoginCommandAsync"; Logger.Log(ex.Message, Category.Exception, Priority.High); } }
public JsonResult Login(string account, string password, string verifyCode) { try { string vcode = HttpContextCore.Current.Session.Get <string>("VerificationCode"); if (Convert.ToString(verifyCode).ToLower() != Convert.ToString(vcode).ToLower()) { return(Json(new { Code = 1, Msg = "验证码不正确,请重新输入!" })); } if (!SSOClient.Validate(account, password, out Guid userId)) { return(Json(new { Code = 1, Msg = "帐号或密码不正确,请重新输入!" })); } HttpContextCore.Current.Session.Set("VerificationCode", string.Empty); SSOClient.SignIn(userId); return(Json(new { Code = 0 })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult WeixinSignIn(string code) { try { if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } //微信互联配置信息 string appid = ""; string appkey = ""; WebClient wcl = new WebClient(); string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, appkey, code); string json = wcl.DownloadString(url); json = wcl.DownloadString(url); WeixinUser weixinUser = JsonConvert.DeserializeObject <WeixinUser>(json.Replace("\\", "")); SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == weixinUser.openid).FirstOrDefault(); if (userOpenId != null && userOpenId.UserId != Guid.Empty) { SSOClient.SignIn(userOpenId.UserId.Value); return(Redirect("/pages/home/index.html")); } return(Redirect("/pages/account/bind.html?sign=pc&openid=" + weixinUser.openid)); //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。 //url = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", access_token, appid, openId); //wcl.Encoding = Encoding.UTF8; //json = wcl.DownloadString(url); //QQUser qqUser = JsonConvert.DeserializeObject<QQUser>(json.Replace("\\", "")); //user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = qqUser.nickname; //user.UserCode = Guid.NewGuid().ToString("N").Substring(20); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //userOpenId = new SysUserOpenId(); //userOpenId.OpenId = token.openid; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); //SSOClient.SignIn(userOpenId.UserId.Value); //return Redirect("/pages/home/index.html"); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult WeixinQYHSignIn(string code) { try { if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } string corpId = "wwa26d4508575b5fe9"; string secret = "cwcclxDJ0GMIlxsn2U_3kWQUPoiDupZOZMrKFqDDcnI"; WebClient wcl = new WebClient(); string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpId, secret); string json = wcl.DownloadString(url); WeixinToken token = JsonConvert.DeserializeObject <WeixinToken>(json.Replace("\\", "")); if (token.errcode != 0) { return(Json(new { Code = 1, Msg = "获取信息失败" })); } //获取微信用户OpenId url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", token.access_token, code); json = wcl.DownloadString(url); WeixinQYHUser wxUser = JsonConvert.DeserializeObject <WeixinQYHUser>(json.Replace("\\", "")); if (wxUser.errcode != 0) { return(Json(new { Code = 1, Msg = "获取信息失败" })); } //获取微信用户信息 url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token={0}", token.access_token); json = wcl.UploadString(url, "{\"user_ticket\": \"" + wxUser.user_ticket + "\"}"); WeixinQYHUserDetail wxUserDetial = JsonConvert.DeserializeObject <WeixinQYHUserDetail>(json.Replace("\\", "")); if (wxUserDetial.errcode != 0) { return(Json(new { Code = 1, Msg = "获取信息失败" })); } SysUser user = dbContext.Set <SysUser>().Where(x => x.UserCode == wxUserDetial.userid).FirstOrDefault(); if (user == null) { return(Json(new { Code = 1, Msg = wxUserDetial.userid + "不存在!" })); } SSOClient.SignIn(user.UserId); return(Redirect("/pages/home/weixin.html")); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public bool UpdateCredentials(string username, string password) { var ssoService = new SSOClient(); var setCredentialsResult = ssoService.SSOCustomerUpdatePasswordByUserName(PersonifyVendorName, PersonifyVendorPassword, username, password); if (!setCredentialsResult.Result) { return(false); } return(true); }
public ActionResult WeixinQYHSignIn2(string code) { try { string userid = ""; string corpId = "wwa26d4508575b5fe9"; string secret = "cwcclxDJ0GMIlxsn2U_3kWQUPoiDupZOZMrKFqDDcnI"; if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } WebClient wcl = new WebClient(); string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpId, secret); string json = wcl.DownloadString(url); JObject token = JObject.Parse(json.Replace("\\", ""));//可用属性请查看官方接入文档(access_token,expires_in,refresh_token,openid,scope,errcode,errmsg) if ((int)token["errcode"] != 0) { return(Json(new { Code = 1, Msg = "获取信息失败" })); } var access_token = (string)token["access_token"]; GetUserInfoResult result = OAuth2Api.GetUserId(access_token, code); if (result.errcode.ToString() == "请求成功") { userid = result.UserId; } else { return(Json(new { Code = 1, Msg = "获取信息失败:" + result.errmsg })); } SysUser user = dbContext.Set <SysUser>().Where(x => x.UserCode == userid).FirstOrDefault(); if (user == null) { return(Json(new { Code = 1, Msg = userid + "不存在!" })); } SSOClient.SignIn(user.UserId); return(Redirect("/pages/home/weixin.html")); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult Login(string code) { try { string openid = string.Empty; SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openid).FirstOrDefault(); if (userOpenId != null && userOpenId.UserId != Guid.Empty) { SSOClient.SignIn(userOpenId.UserId.Value); return(Redirect("/pages/home/index.html")); } return(Redirect("/pages/account/bind.html?openid=" + openid)); //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。 //url = string.Format("https://api.weixin.qq.com//sns/userinfo?access_token={0}&openid={1}", weixin_access_token, appid, openid); //wcl.Encoding = Encoding.UTF8; //json = wcl.DownloadString(url); //JObject weixinUser = JObject.Parse(json.Replace("\\", "")); //var user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = (string)weixinUser["nickname"];//更多可用属性请查看官方接入文档(openid,nickname,sex,province,city,country,headimgurl,privilege[],unionid) //user.UserCode = Guid.NewGuid().ToString("N").Substring(20); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //userOpenId = new SysUserOpenId(); //userOpenId.OpenId = openid; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); //SSOClient.SignIn(userOpenId.UserId.Value); //return Redirect("/pages/home/index.html"); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public JsonResult Login(string account, string password) { try { if (!SSOClient.Validate(account, password, out Guid userId)) { return(Json(new { Code = 1, Msg = "帐号或密码不正确,请重新输入!" })); } SSOClient.SignIn(userId); return(Json(new { Code = 0 })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult Login(string account, string password, string verifyCode) { try { string vcode = HttpContextCore.Current.Session.Get <string>("VerificationCode"); if (Convert.ToString(verifyCode).ToLower() != Convert.ToString(vcode).ToLower()) { return(Json(new { Code = 1, Msg = "验证码不正确,请重新输入!" })); } HttpContextCore.Current.Session.Set("VerificationCode", string.Empty); if (account == "admin") { if (!SSOClient.Validate(account, password, out Guid userId)) { return(Json(new { Code = 1, Msg = "帐号或密码不正确,请重新输入!" })); } SSOClient.SignIn(userId); } else { PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName, account, password); if (!context.ValidateCredentials(account + "@" + domainName, password, ContextOptions.SimpleBind)) { return(Json(new { Code = 1, Msg = "帐号或密码不正确,请重新输入!" })); } var userModel = dbContext.SysUser.FirstOrDefault(t => t.UserCode == account); if (userModel == null) { return(Json(new { Code = 1, Msg = "验证成功但用户不存在,请同步用户信息!" })); } SSOClient.SignIn(userModel.UserId); } return(Json(new { Code = 0, Msg = "登录成功!" })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public JsonResult AppAuthLogin(string openId) { try { SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openId).FirstOrDefault(); if (userOpenId == null || userOpenId.UserId == Guid.Empty) { return(Json(new { Code = -1, Msg = "用户未绑定!" })); } SSOClient.SignIn(userOpenId.UserId.Value); return(Json(new { Code = 0, User = userOpenId.UserId })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public JsonResult FaceLogin(string account, string imgStr) { try { if (!SSOClient.Validate(account, out SysUser user)) { return(Json(new { Code = 1, Msg = "帐号不存在,请重新输入!" })); } //百度Api调整,已无法验证,直接通过。 //if (!FaceHelper.Verify(account, imgStr)) // return Json(new { Code = 1, Msg = "验证不通过!" }); SSOClient.SignIn(user.UserId); return(Json(new { Code = 0, Msg = "登录成功!" })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult SignIn(string code, string state) { try { if (string.IsNullOrEmpty(code)) { return(Redirect("/pages/error/error.html")); } var token = CommonApi.GetToken(_corpId, _secret); if (token.errcode != 0) { return(Redirect("/pages/error/error.html")); } GetUserInfoResult result = OAuth2Api.GetUserId(token.access_token, code); if (result.errcode != 0) { return(Redirect("/pages/error/error.html")); } SysUser user = dbContext.Set <SysUser>().Where(x => x.UserCode == result.UserId).FirstOrDefault(); if (user == null) { //没有账号:根据业务调整 return(Redirect("/pages/error/error.html")); } SSOClient.SignIn(user.UserId); return(ToMenu(state)); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
private Session GetClientSession(SSOClient client, User user, ServerSession session) { var userRoles = repoUserRole.Query(o => o.UserId == user.UserId); var roles = userRoles.Select(o => o.RoleId).ToArray(); var rolePermissions = repoRolePermission.Query(o => userRoles.Any(ur => ur.RoleId == o.RoleId)).ToArray(); var appUris = GetAppProtectedUris(); var sps = appProtectedUris.Select(o => new SimplePermission() { ClientId = o.Item1, PermissionType = o.Item2, ProtectedUris = o.Item3.Select(p => p.Uri).ToArray(), AllowedUris = o.Item3.Where(u => rolePermissions.HasPermitted(u)).Select(u => u.Uri).ToArray() }).ToArray(); return(new Session() { ClientId = client.ClientId, ClientName = client.ClientName, ClientBaseUrl = client.BaseUrl, SessionId = session.SessionId, AccessToken = session.AccessToken, User = user.ToUserSession(), Roles = roles, DeviceId = session.DeviceId, DeviceInfo = session.DeviceInfo, Theme = string.IsNullOrEmpty(user.Theme) ? "Default" : user.Theme, Skin = string.IsNullOrEmpty(user.Skin) ? "Default" : user.Skin, Locale = string.IsNullOrEmpty(user.Locale) ? System.Threading.Thread.CurrentThread.CurrentCulture.Name : user.Locale, TimeZone = user.TimeZone, Permissions = sps }); }
private string PostLogin(string flowExecutionKey) { var request = BuildAuthRequest(Method.POST); NameValueCollection formData = new NameValueCollection { { "username", UserName }, { "password", Password }, { "embed", "true" } }; string formDataStr = ""; foreach (var key in formData.AllKeys) { formDataStr += key + "=" + formData[key] + "&"; } var formDataBytes = Encoding.UTF8.GetBytes(formDataStr); request.AddParameter("application/x-www-form-urlencoded", formDataStr, ParameterType.RequestBody); request.AddHeader("Referer", REFERER); IRestResponse response = SSOClient.Execute(request); return(response.Content); }
public ActionResult QQSignIn(string code) { try { /* 作者说明:续期功能未测试,有谁帮忙测一下。 */ if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } //QQ互联配置信息 string appid = "101107448"; string appkey = "ae7af6e66a8655f5dce06dce7fe20859"; string status = ""; string reurl = "https%3A%2F%2Fwww.bitadmincore.com%2Fauth%2Fqqsignin"; string url, json; WebClient wcl = new WebClient(); /*access_token有次数限制,不能每次都取一个新的,在有效期内可以使用,过了有效期则续期就可以了。*/ if (string.IsNullOrEmpty(qq_access_token)) { url = string.Format("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&state={3}&redirect_uri={4}", appid, appkey, code, status, reurl); json = wcl.DownloadString(url); //string token = "access_token=06B07A1CA3144B67BB8ECE03577E4DC5&expires_in=7776000&refresh_token=8DB41D424D74B1F79322946F0E3A17B0"; var param = QueryHelpers.ParseQuery(json); qq_access_token = param["access_token"]; qq_refresh_token = param["refresh_token"]; qq_expires_time = DateTime.Now.AddSeconds(Convert.ToInt32(param["expires_in"].ToString())); } else if (qq_expires_time < DateTime.Now.AddMinutes(30))//提前30分钟续期 { url = string.Format("https://graph.qq.com/oauth2.0/token?grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", appid, appkey, qq_refresh_token); json = wcl.DownloadString(url); //string token = "access_token=06B07A1CA3144B67BB8ECE03577E4DC5&expires_in=7776000&refresh_token=8DB41D424D74B1F79322946F0E3A17B0"; var param = QueryHelpers.ParseQuery(json); qq_access_token = param["access_token"]; qq_refresh_token = param["refresh_token"]; qq_expires_time = DateTime.Now.AddSeconds(Convert.ToInt32(param["expires_in"].ToString())); } url = "https://graph.qq.com/oauth2.0/me?access_token=" + qq_access_token; json = wcl.DownloadString(url); //json = "callback( {\"client_id\":\"101107448\",\"openid\":\"1B09CF38A9D917645272095DFF8B6074\"} );"; var mc = new Regex("(?<=\\u0028).*?(?= \\u0029)", RegexOptions.None).Matches(json)[0];//提取出json对象 JObject me = JObject.Parse(mc.Value); string client_id = (string)me["client_id"]; string openId = (string)me["openid"]; SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openId).FirstOrDefault(); if (userOpenId != null && userOpenId.UserId != Guid.Empty) { SSOClient.SignIn(userOpenId.UserId.Value); return(Redirect("/pages/home/index.html")); } return(Redirect("/pages/account/bind.html?sign=pc&openid=" + openId)); //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。 //url = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", access_token, appid, openId); //wcl.Encoding = Encoding.UTF8; //json = wcl.DownloadString(url); //JObject qqUser = JObject.Parse(json.Replace("\\", "")); //var user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = (string)qqUser["nickname"];//更多可用属性请查看官方接入文档 //user.UserCode = Guid.NewGuid().ToString("N").Substring(20); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //userOpenId = new SysUserOpenId(); //userOpenId.OpenId = openId; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); //SSOClient.SignIn(userOpenId.UserId.Value); //return Redirect("/pages/home/index.html"); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult WeixinGZHSignIn(string code) { try { if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } string appId = "wx806943202a75a124"; string appSecret = "d52257abea1018eec3a798005ba4f841"; WebClient wcl = new WebClient(); string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, appSecret, code); string json = wcl.DownloadString(url); WeixinToken token = JsonConvert.DeserializeObject <WeixinToken>(json.Replace("\\", "")); LogHelper.SaveLog("wxgzhsignin", url); LogHelper.SaveLog("wxgzhsignin", json); if (token.errcode != null) { return(Json(new { Code = 1, Msg = "获取信息失败" })); } SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == token.openid).FirstOrDefault(); if (userOpenId != null && userOpenId.UserId != Guid.Empty) { SSOClient.SignIn(userOpenId.UserId.Value); return(Redirect("/pages/home/weixin.html")); } else { return(Redirect("/pages/account/bind.html?sign=wx&openid=" + token.openid)); } //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。 //url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", token.access_token, token.openid); //json = wcl.DownloadString(url); //WeixinGZHUser wxUser = JsonConvert.DeserializeObject<WeixinGZHUser>(json.Replace("\\", "")); //if (wxUser.errcode != null) // return Json(new { Code = 1, Msg = "获取信息失败" }); //SysUser user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = wxUser.nickname; //user.UserCode = Guid.NewGuid().ToString("N").Substring(20); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //userOpenId = new SysUserOpenId(); //userOpenId.OpenId = token.openid; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); //SSOClient.SignIn(userOpenId.UserId.Value); //return Redirect("/pages/home/weixin.html"); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult WeixinSignIn(string code) { try { /* 作者说明:因没有账号,本功能未测试。 * * 作者疑问?? * 微信互联登录access_token逻辑感觉有问题:请求access_token时返回openid,那么access_token是跟appid绑定?还是跟openid绑定? * 如果是跟openid绑定,那么需要维护一个access_token与openid关系及时效表,用户关闭应用重新启动登录时,只能重新获取code再获取openid,意义何在? */ if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } //微信互联配置信息 string appid = ""; string appkey = ""; string url, json, openid = string.Empty, unionid = string.Empty;//你要用openid还是用unionid请详读官网说明。 WebClient wcl = new WebClient(); /*access_token有次数限制,不能每次都取一个新的,在有效期内可以使用,过了有效期则续期就可以了。*/ if (string.IsNullOrEmpty(weixin_access_token)) { url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, appkey, code); json = wcl.DownloadString(url); JObject weixinToken = JObject.Parse(json.Replace("\\", "")); openid = (string)weixinToken["openid"];//更多可用属性请查看官方接入文档(access_token,expires_in,refresh_token,openid,scope,unionid) unionid = (string)weixinToken["unionid"]; weixin_access_token = (string)weixinToken["access_token"]; weixin_refresh_token = (string)weixinToken["refresh_token"]; weixin_expires_time = DateTime.Now.AddSeconds(Convert.ToInt32(weixinToken["expires_in"].ToString())); } else if (weixin_expires_time < DateTime.Now.AddMinutes(30))//提前30分钟续期 { url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?grant_type=refresh_token&appid={0}&refresh_token={1}", appid, weixin_refresh_token); json = wcl.DownloadString(url); //string token = "access_token=06B07A1CA3144B67BB8ECE03577E4DC5&expires_in=7776000&refresh_token=8DB41D424D74B1F79322946F0E3A17B0"; var param = QueryHelpers.ParseQuery(json); weixin_access_token = param["access_token"]; weixin_refresh_token = param["refresh_token"]; weixin_expires_time = DateTime.Now.AddSeconds(Convert.ToInt32(param["expires_in"].ToString())); } SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openid).FirstOrDefault(); if (userOpenId != null && userOpenId.UserId != Guid.Empty) { SSOClient.SignIn(userOpenId.UserId.Value); return(Redirect("/pages/home/index.html")); } return(Redirect("/pages/account/bind.html?sign=pc&openid=" + openid)); //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。 //url = string.Format("https://api.weixin.qq.com//sns/userinfo?access_token={0}&openid={1}", weixin_access_token, appid, openid); //wcl.Encoding = Encoding.UTF8; //json = wcl.DownloadString(url); //JObject weixinUser = JObject.Parse(json.Replace("\\", "")); //var user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = (string)weixinUser["nickname"];//更多可用属性请查看官方接入文档(openid,nickname,sex,province,city,country,headimgurl,privilege[],unionid) //user.UserCode = Guid.NewGuid().ToString("N").Substring(20); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //userOpenId = new SysUserOpenId(); //userOpenId.OpenId = openid; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); //SSOClient.SignIn(userOpenId.UserId.Value); //return Redirect("/pages/home/index.html"); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
private async Task ExecuteLoginWithTwitterAsync() { if (IsBusy) { return; } try { IsBusy = true; Message = "Signing in..."; AccountResponse result = null; if (result == null) { result = await SSOClient.LoginAsync(_email); } if (result?.Success ?? false) { Message = "Updating schedule..."; Settings.FirstName = result.User?.FirstName ?? string.Empty; Settings.LastName = result.User?.LastName ?? string.Empty; Settings.Email = (_email ?? result.User?.Email ?? string.Empty).ToLowerInvariant(); EventAggregator.GetEvent <LoggedInEvent>().Publish(); Logger.Log(DevopenspaceLoggerKeys.LoginSuccess, Prism.Logging.Category.Info, Priority.None); try { await StoreManager.SyncAllAsync(true); Settings.Current.LastSync = DateTime.UtcNow; Settings.Current.HasSyncedData = true; } catch (Exception ex) { //if sync doesn't work don't worry it is alright we can recover later Logger.Log(ex.Message, Prism.Logging.Category.Exception, Priority.High); } await Finish(); Settings.FirstRun = false; } else { Logger.Log($"{DevopenspaceLoggerKeys.LoginFailure}, Reason, {result.Error}", Prism.Logging.Category.Warn, Priority.Medium); await PageDialogService.DisplayAlertAsync("Unable to Sign in", result.Error, "OK"); } } catch (Exception ex) { Logger.Log($"{DevopenspaceLoggerKeys.LoginFailure}, Reason, {ex?.Message ?? string.Empty}", Prism.Logging.Category.Exception, Priority.High); await PageDialogService.DisplayAlertAsync("Unable to Sign in", "The email or password provided is incorrect.", "OK"); } finally { Message = string.Empty; IsBusy = false; } }
public ActionResult Login() { string[] allowed = MvcApplication.Config("allowed").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); //if (!allowed.Contains(HttpContext.Request.UserHostAddress.ToString())) //{ // Response.Redirect("http://www.shekelgroup.co.il/"); //} //string[] temp = Convert.ToString(WindowsIdentity.GetCurrent().Name).Split('\\'); //ViewBag.login_name = temp[1]; var model = new LoginFormModel(); //SSO string ssoConfig = MvcApplication.Config("sso.enabled"); if (!String.IsNullOrEmpty(ssoConfig)) { bool ssoEnabled = bool.Parse(ssoConfig); if (ssoEnabled) { using (HostingEnvironment.Impersonate()) { SSOClient ssoClient = new SSOClient(); //string ssoLoginName = ssoClient.GetCurrentLoginName(); string ssoLoginName = User.Identity.Name; if (ssoLoginName.Contains("\\")) { ssoLoginName = ssoLoginName.Split('\\')[1]; } if (!String.IsNullOrEmpty(ssoLoginName)) { string ssoPropertyName = MvcApplication.Config("sso.id_property"); if (!String.IsNullOrEmpty(ssoPropertyName)) { string ssoPropertyValue = ssoClient.GetProperty(ssoLoginName, ssoPropertyName); if (!String.IsNullOrEmpty(ssoPropertyValue)) { //Int64 localId = 2065; Int64 localId = Int64.Parse(ssoPropertyValue); if (localId > 0) { var emp = GetSession.QueryOver<Employee>().Where(x => x.Id == localId).SingleOrDefault(); if (emp != null) { if (String.IsNullOrWhiteSpace(emp.Email) || emp.Email.Equals("*****@*****.**", StringComparison.InvariantCultureIgnoreCase) || String.IsNullOrWhiteSpace(emp.Username)) { return View(new LoginFormModel()); } else { return Login(new LoginFormModel() { Username = emp.Email, Password = emp.Password }); } } } } } } } } } return View(new LoginFormModel()); }
public ActionResult WeixinQYHSignIn(string code) { try { if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } string corpId = "wwa26d4508575b5fe9"; string secret = "cwcclxDJ0GMIlxsn2U_3kWQUPoiDupZOZMrKFqDDcnI"; WebClient wcl = new WebClient(); string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpId, secret); string json = wcl.DownloadString(url); JObject token = JObject.Parse(json.Replace("\\", ""));//可用属性请查看官方接入文档(access_token,expires_in,refresh_token,openid,scope,errcode,errmsg) if ((int)token["errcode"] != 0) { return(Json(new { Code = 1, Msg = "获取信息失败" })); } var access_token = (string)token["access_token"]; //获取微信用户OpenId url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", access_token, code); json = wcl.DownloadString(url); JObject wxUser = JObject.Parse(json.Replace("\\", ""));//可用属性请查看官方接入文档(expires_in,UserId,DeviceId,user_ticket,OpenId,errcode,errmsg) if ((int)wxUser["errcode"] != 0) { return(Json(new { Code = 1, Msg = "获取信息失败" })); } var user_ticket = (string)wxUser["user_ticket"]; //获取微信用户信息 url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token={0}", access_token); json = wcl.UploadString(url, "{\"user_ticket\": \"" + user_ticket + "\"}"); JObject wxUserDetial = JObject.Parse(json.Replace("\\", ""));//可用属性请查看官方接入文档(userid,name,department[int],position,mobile,gender,email,avatar,errcode,errmsg) if ((int)wxUserDetial["errcode"] != 0) { return(Json(new { Code = 1, Msg = "获取信息失败" })); } var userid = (string)wxUserDetial["userid"]; SysUser user = dbContext.Set <SysUser>().Where(x => x.UserCode == userid).FirstOrDefault(); if (user == null) { return(Json(new { Code = 1, Msg = userid + "不存在!" })); } SSOClient.SignIn(user.UserId); return(Redirect("/pages/home/weixin.html")); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult WeixinGZHSignIn2(string code) { try { string openid = ""; OAuthAccessTokenResult result = OAuthApi.GetAccessToken("wx806943202a75a124", "d52257abea1018eec3a798005ba4f841", code); if (result.errcode.ToString() == "请求成功") { openid = result.openid; } else { return(Json(new { Code = 1, Msg = "获取信息失败:" + result.errmsg })); } if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openid).FirstOrDefault(); if (userOpenId != null && userOpenId.UserId != Guid.Empty) { SSOClient.SignIn(userOpenId.UserId.Value); return(Redirect("/pages/home/weixin.html")); } else { return(Redirect("/pages/account/bind.html?sign=wx&openid=" + openid)); } //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。 //url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid); //json = wcl.DownloadString(url); //JObject wxUser = JObject.Parse(json.Replace("\\", ""));//可用属性请查看官方接入文档(openid,nickname,sex,province,city,country,headimgurl,privilege[],unionid,errcode,errmsg) //if (!string.IsNullOrEmpty((string)wxUser["errcode"])) // return Json(new { Code = 1, Msg = "获取信息失败" }); //SysUser user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = (string)wxUser["nickname"]; //user.UserCode = Guid.NewGuid().ToString("N").Substring(20); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //var userOpenId = new SysUserOpenId(); //userOpenId.OpenId = openid; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); //SSOClient.SignIn(userOpenId.UserId.Value); //return Redirect("/pages/home/weixin.html"); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public ActionResult QqSignIn(string code) { try { if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } //QQ互联配置信息 string appid = "101107448"; string appkey = "ae7af6e66a8655f5dce06dce7fe20859"; string status = ""; string reurl = "http%3A%2F%2Fbit.bitdao.cn%2Faccount%2Fqqsignin"; WebClient wcl = new WebClient(); string url = string.Format("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&state={3}&redirect_uri={4}", appid, appkey, code, status, reurl); string json = wcl.DownloadString(url); //string token = "access_token=06B07A1CA3144B67BB8ECE03577E4DC5&expires_in=7776000&refresh_token=8DB41D424D74B1F79322946F0E3A17B0"; string[] gtoken = json.Split('&'); string access_token = gtoken[0].Split('=')[1]; string expires_in = gtoken[1].Split('=')[1]; string refresh_token = gtoken[2].Split('=')[1]; url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token; json = wcl.DownloadString(url); //json = "callback( {\"client_id\":\"101107448\",\"openid\":\"1B09CF38A9D917645272095DFF8B6074\"} );"; Regex re = new Regex("(?<=\").*?(?=\")", RegexOptions.None); MatchCollection mc = re.Matches(json); List <string> list = new List <string>(); foreach (Match ma in mc) { list.Add(ma.Value); } string client_id = list[2]; string openId = list[6]; SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openId).FirstOrDefault(); if (userOpenId != null && userOpenId.UserId != Guid.Empty) { SSOClient.SignIn(userOpenId.UserId.Value); return(Redirect("/pages/home/index.html")); } return(Redirect("/pages/account/bind.html?sign=pc&openid=" + openId)); //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。 //url = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", access_token, appid, openId); //wcl.Encoding = Encoding.UTF8; //json = wcl.DownloadString(url); //QQUser qqUser = JsonConvert.DeserializeObject<QQUser>(json.Replace("\\", "")); //user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = qqUser.nickname; //user.UserCode = Guid.NewGuid().ToString("N").Substring(20); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //userOpenId = new SysUserOpenId(); //userOpenId.OpenId = token.openid; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); //SSOClient.SignIn(userOpenId.UserId.Value); //return Redirect("/pages/home/index.html"); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
/// <summary> /// 登录出 /// </summary> /// <returns></returns> public ActionResult SignOut() { SSOClient.SignOut(); return(Json(new { Code = 0 })); }
public IEncryptionProvider GetClientEncryptor(SSOClient client) { return(new AESEncryptionProvider(client.EncryptKey, client.EncryptScrect)); }
public ActionResult Login() { string[] allowed = MvcApplication.Config("allowed").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); //if (!allowed.Contains(HttpContext.Request.UserHostAddress.ToString())) //{ // Response.Redirect("http://www.shekelgroup.co.il/"); //} //string[] temp = Convert.ToString(WindowsIdentity.GetCurrent().Name).Split('\\'); //ViewBag.login_name = temp[1]; var model = new LoginFormModel(); //SSO string ssoConfig = MvcApplication.Config("sso.enabled"); if (!String.IsNullOrEmpty(ssoConfig)) { bool ssoEnabled = bool.Parse(ssoConfig); if (ssoEnabled) { using (HostingEnvironment.Impersonate()) { SSOClient ssoClient = new SSOClient(); //string ssoLoginName = ssoClient.GetCurrentLoginName(); string ssoLoginName = User.Identity.Name; if (ssoLoginName.Contains("\\")) { ssoLoginName = ssoLoginName.Split('\\')[1]; } if (!String.IsNullOrEmpty(ssoLoginName)) { string ssoPropertyName = MvcApplication.Config("sso.id_property"); if (!String.IsNullOrEmpty(ssoPropertyName)) { string ssoPropertyValue = ssoClient.GetProperty(ssoLoginName, ssoPropertyName); if (!String.IsNullOrEmpty(ssoPropertyValue)) { //Int64 localId = 2065; Int64 localId = Int64.Parse(ssoPropertyValue); if (localId > 0) { var emp = GetSession.QueryOver <Employee>().Where(x => x.Id == localId).SingleOrDefault(); if (emp != null) { if (String.IsNullOrWhiteSpace(emp.Email) || emp.Email.Equals("*****@*****.**", StringComparison.InvariantCultureIgnoreCase) || String.IsNullOrWhiteSpace(emp.Username)) { return(View(new LoginFormModel())); } else { return(Login(new LoginFormModel() { Username = emp.Email, Password = emp.Password })); } } } } } } } } } return(View(new LoginFormModel())); }