public ActionResult OAuth2(string corpid, string accesstoken, string reurl, string scope = "snsapi_base") { #region 校验 if (string.IsNullOrEmpty(reurl)) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:reurl为空", corpid)); return(Content("非法访问")); } var account = GetAccount(corpid); if (account == null) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:企业号不存在", corpid)); return(Content("非法访问")); } var passtoken = GetPassToken(account, accesstoken); if (passtoken == null) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:accesstoken错误", corpid)); return(Content("非法访问")); } if (!ValidateOauth2Domain(passtoken, Base64Helper.DecodeBase64(reurl.Replace(" ", "+")))) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:reurl{1}错误", corpid, reurl)); return(Content("非法访问")); } #endregion string CorpID = account.CorpID; var domain = Request.Url.Authority; var url = OAuth2Api.GetCode(CorpID, "http://" + domain + "/wechatservice/wxapi/OAuth2Callback?corpid=" + corpid + "&accesstoken=" + accesstoken + "&scope=" + scope + "&reurl=" + reurl, "JeffreySu", account.AgentId == null ? "" : account.AgentId.ToString(), scope: scope); return(Redirect(url)); }
public static string AddUser(string Userstr) { string str = string.Empty; try { tbUser tb = JsonConvert.DeserializeObject <tbUser>(Userstr); string passWord = Base64Helper.DecodeBase64(tb.Password); string password = Md5Helper.GetMD5String(passWord); tbUser newtb = new tbUser() { AccountName = tb.AccountName, CreateBy = tb.CreateBy, CreateTime = DateTime.Now, Description = tb.Description, Email = tb.Email, IfChangePwd = tb.IfChangePwd, IsAble = tb.IsAble, MobilePhone = tb.MobilePhone, Password = password, RealName = tb.RealName, UpdateTime = DateTime.Now, UpdateBy = tb.CreateBy }; AchieveDBEntities myDbContext = new AchieveDBEntities(); int DataCount = myDbContext.tbUser.Where(p => p.AccountName == newtb.AccountName).Count <tbUser>(); if (DataCount > 0) { throw new Exception(string.Format("帐号名:{0}重复,请重新输入", newtb.AccountName)); } DataCount = myDbContext.tbUser.Where(p => p.Email == newtb.Email).Count <tbUser>(); if (DataCount > 0) { throw new Exception(string.Format("邮箱:{0}重复,请重新输入", newtb.Email)); } DataCount = myDbContext.tbUser.Where(p => p.MobilePhone == newtb.MobilePhone).Count <tbUser>(); if (DataCount > 0) { throw new Exception(string.Format("手机号:{0}重复,请重新输入", newtb.MobilePhone)); } myDbContext.tbUser.Add(newtb); myDbContext.SaveChanges(); str = ResponseHelper.ResponseMsg("1", "保存成功", ""); } catch (Exception ex) { str = ResponseHelper.ResponseMsg("-1", ex.Message, ""); } return(str); }
public static string UpdateUserAllinfo(string Userstr) { string str = string.Empty; try { tbUser tb = JsonConvert.DeserializeObject <tbUser>(Userstr); AchieveDBEntities myDbContext = new AchieveDBEntities(); tbUser data = myDbContext.tbUser.Where(p => p.ID == tb.ID).FirstOrDefault(); string passWord = Base64Helper.DecodeBase64(tb.Password); string password = Md5Helper.GetMD5String(passWord); data.AccountName = tb.AccountName; data.Description = tb.Description; data.Email = tb.Email; data.IfChangePwd = tb.IfChangePwd; data.IsAble = tb.IsAble; data.MobilePhone = tb.MobilePhone; data.Password = password; data.RealName = tb.RealName; data.UpdateBy = tb.UpdateBy; data.UpdateTime = DateTime.Now; int DataCount = myDbContext.tbUser.Where(p => p.AccountName == data.AccountName && p.ID != data.ID).Count <tbUser>(); if (DataCount > 0) { throw new Exception(string.Format("帐号名:{0}重复,请重新输入", data.AccountName)); } DataCount = myDbContext.tbUser.Where(p => p.Email == data.Email && p.ID != data.ID).Count <tbUser>(); if (DataCount > 0) { throw new Exception(string.Format("邮箱:{0}重复,请重新输入", data.Email)); } DataCount = myDbContext.tbUser.Where(p => p.MobilePhone == data.MobilePhone && p.ID != data.ID).Count <tbUser>(); if (DataCount > 0) { throw new Exception(string.Format("手机号:{0}重复,请重新输入", data.MobilePhone)); } myDbContext.SaveChanges(); str = ResponseHelper.ResponseMsg("1", "更新成功", ""); } catch (Exception ex) { str = ResponseHelper.ResponseMsg("-1", ex.Message, ""); } return(str); }
public ActionResult JssdkJsonP(string mpid) { var account = GetAccount(mpid); if (account == null) { LogWriter.Info(string.Format("mpid为“{0}”的jssdk获取失败,原因:公众号不存在", mpid)); return(Content("公众号不存在")); } var wxFO = Formula.FormulaHelper.CreateFO <WxFO>(); var ticket = wxFO.GetJsApiTicket(mpid); var url = Request.QueryString["callurl"] ?? ""; if (string.IsNullOrEmpty(url)) { url = Request.UrlReferrer == null?Request.Url.ToString() : Request.UrlReferrer.ToString(); } else { var constr = string.IsNullOrEmpty(Request.QueryString["constr"]) ? "@" : Request.QueryString["constr"]; url = url.Replace(constr, "&"); var urlmode = Request.QueryString["urlmode"] ?? ""; if (urlmode.ToLower().Trim() == "base64") { url = Base64Helper.DecodeBase64(url.Replace(" ", "+")); } } string timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now)); string nonceStr = createNonceStr(); string rawstring = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url; string signature = SHA1_Hash(rawstring); var callback = Request.QueryString["callback"] ?? ""; return(Content(string.IsNullOrEmpty(callback) ? "" : string.Format("{0}({1})", callback, new JavaScriptSerializer().Serialize( new { appId = account.AppID, nonceStr = nonceStr, timestamp = timestamp, url = url, signature = signature, rawString = rawstring, })))); }
public ActionResult JssdkJsonP(string corpid, string accesstoken, string callurl, string callback) { #region 校验 var account = GetAccount(corpid); if (account == null) { LogWriter.Info(string.Format("corpid为“{0}”的JSSDK获取失败,原因:企业号不存在", corpid)); return(Json(new { errorcode = "500", errormsg = "企业号不存在", })); } if (GetPassToken(account, accesstoken) == null) { LogWriter.Info(string.Format("corpid为“{0}”的JSSDK获取失败,原因:accesstoken错误", corpid)); return(Json(new { errorcode = "500", errormsg = "非法访问", })); } #endregion var wxFO = Formula.FormulaHelper.CreateFO <WxFO>(); var ticket = wxFO.GetJsApiTicket(corpid); var url = callurl ?? ""; url = Base64Helper.DecodeBase64(url.Replace(" ", "+")); string timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now)); string nonceStr = createNonceStr(); string rawstring = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url; string signature = SHA1_Hash(rawstring); return(Content(string.IsNullOrEmpty(callback) ? "" : string.Format("{0}({1})", callback, new JavaScriptSerializer().Serialize( new { errcode = "0", errormsg = "ok", appId = account.CorpID, nonceStr = nonceStr, timestamp = timestamp, url = url, signature = signature, rawString = rawstring, })))); }
public ActionResult OAuth2UserInfo(string mpid) { var account = GetAccount(mpid); if (account == null) { LogWriter.Info(string.Format("mpid为“{0}”的认证授权失败,原因:公众号不存在", mpid)); return(Content("公众号不存在")); } var reurl = Request.QueryString["reurl"]; if (string.IsNullOrEmpty(reurl)) { LogWriter.Info(string.Format("mpid为“{0}”的静默授权失败,原因:reurl为空", mpid)); return(Content("reurl为空")); } var urlmode = Request.QueryString["urlmode"] ?? ""; if (account.MpOAuth2WhiteList.Where(c => c.Domain == "*").Count() == 0) { Uri ru = null; try { ru = new Uri(urlmode.ToLower().Trim() == "base64" ? Base64Helper.DecodeBase64(reurl.Replace(" ", "+")) : reurl); } catch (Exception ex) { LogWriter.Error(ex, string.Format("mpid为“{0}”的静默授权失败,原因:解析reurl“{1}”错误", mpid, reurl)); return(Content("reurl不正确")); } var redomain = ru.Authority.ToLower(); if (account.MpOAuth2WhiteList.Where(c => c.Domain == redomain).Count() == 0) { LogWriter.Info(string.Format("mpid为“{0}”的静默授权失败,原因:域名{1}不在白名单中", mpid, redomain)); return(Content("您的域名未授权调用该接口")); } } string appId = account.AppID; string secret = account.AppSecret; var constr = Request.QueryString["constr"] ?? ""; var url = OAuthApi.GetAuthorizeUrl(appId, $"{Request.Url.Scheme}://{Request.Url.Host}/wechatservice/wxapi/OAuth2UserInfoCallback?mpid=" + mpid + "&reurl=" + reurl + "&constr=" + constr + "&urlmode=" + urlmode, "JeffreySu", OAuthScope.snsapi_userinfo); return(Redirect(url)); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var basePath = PlatformServices.Default.Application.ApplicationBasePath; // 使用内存存储的密钥,客户端和API资源来配置ids4。 services.AddIdentityServer() .AddSigningCredential(new X509Certificate2(Path.Combine(basePath, "zhoulikey.pfx"), Base64Helper.DecodeBase64("OTkwMTIyNjYxOWxs"))) .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryClients(Config.GetClients()); //配置跨域 services.AddCors(options => options.AddPolicy("Zhouli.Identity.Certification", builder => builder.AllowAnyOrigin(). AllowAnyMethod(). AllowAnyHeader()) ); }
public ActionResult OAuth2UserInfoCallback(string mpid) { var constr = string.IsNullOrEmpty(Request.QueryString["constr"]) ? "@" : Request.QueryString["constr"]; string url = (Request.QueryString["reurl"] ?? "").Replace(constr, "&"); string code = Request.QueryString["code"]; string state = Request.QueryString["state"]; string urlmode = Request.QueryString["urlmode"] ?? ""; if (urlmode.ToLower().Trim() == "base64") { url = Base64Helper.DecodeBase64(url.Replace(" ", "+")); } if (string.IsNullOrEmpty(code)) { LogWriter.Info(string.Format("mpid为“{0}”的认证授权失败,原因:拒绝了授权,Url:{1}", mpid, Request.Url.ToString())); return(Content("您拒绝了授权!")); } if (state != "JeffreySu" && state != "JeffreySu?10000skip=true") { //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下 //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证 LogWriter.Info(string.Format("mpid为“{0}”的认证授权失败,原因:验证失败,Url:{1}", mpid, Request.Url.ToString())); return(Content("验证失败!请从正规途径进入!")); } //通过,用code换取access_token var account = GetAccount(mpid); if (account == null) { LogWriter.Info(string.Format("mpid为“{0}”的认证授权失败,原因:公众号不存在", mpid)); return(Content("公众号不存在")); } OAuthAccessTokenResult result = null; try { result = OAuthApi.GetAccessToken(account.AppID, account.AppSecret, code); } catch (Exception ex) { LogWriter.Info(string.Format("mpid为“{0}”的认证授权在通过code获取token时异常,原因:{1}", mpid, result.errmsg)); return(Content("错误:" + ex.Message)); } if (result.errcode != ReturnCode.请求成功) { LogWriter.Info(string.Format("mpid为“{0}”的认证授权在通过code获取token时失败,原因:{1}", mpid, result.errmsg)); return(Content("错误:" + result.errmsg)); } //因为这里还不确定用户是否关注本微信,所以只能试探性地获取一下 OAuthUserInfo userInfo = null; try { //已关注,可以得到详细信息 userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid); url = string.Format("{0}{1}openid={2}&nickname={3}&headimgurl={4}" , url, url.Contains('?') ? "&" : "?", result.openid, userInfo.nickname, userInfo.headimgurl); return(Redirect(url)); } catch (ErrorJsonResultException ex) { LogWriter.Info(string.Format("mpid为“{0}”的认证授权失败,原因:{1}", mpid, ex.Message)); return(Content("错误:" + ex.Message)); } }
public static string GetUserByAccountName(string accountName, string passWord, string address, string port) { string str = string.Empty; try { passWord = Base64Helper.DecodeBase64(passWord); string md5passWord = Md5Helper.GetMD5String(passWord); IsoDateTimeConverter timeFormat = new IsoDateTimeConverter(); timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; UserInfoModel temp = new UserInfoModel(); AchieveDBEntities myDbContext = new AchieveDBEntities(); List <tbUser> templist = myDbContext.tbUser.Where(p => p.AccountName == accountName).ToList(); if (templist != null && templist.Count > 0) { tbUser tempUser = templist[0]; if (tempUser.Password == md5passWord) { if (tempUser.IsAble != 1) { throw new Exception("帐号未启用!"); } string Token = Guid.NewGuid().ToString(); DateTime newDataTime = DateTime.Now; List <tbUserToken> tempOldTokenlist = myDbContext.tbUserToken.Where(p => p.UserId == tempUser.ID && p.IsLoginOut != 1).ToList(); foreach (var st in tempOldTokenlist) { st.IsLoginOut = 1; } tbUserToken newtb = new tbUserToken(); newtb.UserId = tempUser.ID; newtb.Token = Token; newtb.CreateTime = newDataTime; newtb.UpdateTime = newDataTime; newtb.Address = address; newtb.Port = port; newtb.IsLoginOut = 0; myDbContext.tbUserToken.Add(newtb); myDbContext.SaveChanges(); temp.ID = tempUser.ID; temp.AccountName = tempUser.AccountName; temp.CreateTime = DateTime.Now; temp.RealName = tempUser.RealName; temp.Token = Token; temp.CreateTime = newDataTime; str = JsonConvert.SerializeObject(temp, Formatting.Indented, timeFormat); str = ResponseHelper.ResponseMsg("1", "取数成功", str); } else { str = JsonConvert.SerializeObject(temp, Formatting.Indented, timeFormat); str = ResponseHelper.ResponseMsg("-1", "密码错误", str); } } else { str = JsonConvert.SerializeObject(temp, Formatting.Indented, timeFormat); str = ResponseHelper.ResponseMsg("-1", "用户不存在", str); } } catch (Exception ex) { str = ResponseHelper.ResponseMsg("-1", ex.Message, ""); } return(str); }
public ActionResult OAuth2Callback(string corpid, string accesstoken, string scope, string reurl, string code, string state) { //LogWriter.Info("OAuth2Callback:"); string url = reurl ?? ""; url = Base64Helper.DecodeBase64(url.Replace(" ", "+")); if (string.IsNullOrEmpty(code)) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:拒绝了授权", corpid)); return(Content("您拒绝了授权!")); } if (state != "JeffreySu" && state != "JeffreSu?10000skip=true") { //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下 //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证 LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:验证失败", corpid)); return(Content("验证失败!请从正规途径进入!")); } #region 校验 if (string.IsNullOrEmpty(reurl)) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2Base获取失败,原因:reurl为空", corpid)); return(Content("非法访问")); } var account = GetAccount(corpid); if (account == null) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2Base获取失败,原因:企业号不存在", corpid)); return(Content("非法访问")); } var passtoken = GetPassToken(account, accesstoken); if (passtoken == null) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2Base获取失败,原因:accesstoken错误", corpid)); return(Content("非法访问")); } if (!ValidateOauth2Domain(passtoken, reurl)) { LogWriter.Info(string.Format("qyid为“{0}”的OAuth2Base获取失败,原因:reurl{1}错误", corpid, reurl)); return(Content("非法访问")); } #endregion //通过,用code换取access_token GetUserInfoResult result = null; var wxFO = Formula.FormulaHelper.CreateFO <WxFO>(); try { result = OAuth2Api.GetUserId(wxFO.GetAccessToken(corpid), code); //LogWriter.Info("OAuth2Callback:GetUserId" + JsonHelper.ToJson(result)); } catch (Exception ex) { LogWriter.Error(ex, string.Format("qyid为{0}的静默授权在通过code获取token时异常", corpid)); result = OAuth2Api.GetUserId(wxFO.GetAccessToken(corpid, true), code); } if (result.errcode != ReturnCode_QY.请求成功) { LogWriter.Info(string.Format("qyid为{0}的静默授权在通过code获取token时异常,原因:{1}", corpid, result.errmsg)); return(Content("错误:" + result.errmsg)); } if (!string.IsNullOrEmpty(result.user_ticket) && !string.IsNullOrEmpty(result.UserId) && (scope == "snsapi_userinfo" || scope == "snsapi_privateinfo")) { GetUserDetailResult resultDetail = null; try { resultDetail = CommonJsonSend.Send <GetUserDetailResult>(wxFO.GetAccessToken(corpid), "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token={0}", new { user_ticket = result.user_ticket, }); //LogWriter.Info("OAuth2Callback:Send" + JsonHelper.ToJson(resultDetail)); } catch (Exception ex) { LogWriter.Error(ex, string.Format("qyid为{0}的认证授权在通过ticket获取详情时异常", corpid)); } if (resultDetail != null && resultDetail.userid != null) { url = string.Format("{0}{1}userinfo={2}" , url, url.Contains('?') ? "&" : "?", Base64Helper.EncodeBase64(JsonHelper.ToJson(new { userid = result.UserId, openid = result.OpenId, name = resultDetail.name, department = resultDetail.department, position = resultDetail.position, mobile = resultDetail.mobile, gender = resultDetail.gender, email = resultDetail.email, avatar = resultDetail.avatar, }))); //LogWriter.Info("OAuth2Callback:url1:" + url); return(Redirect(url)); } } url = string.Format("{0}{1}userinfo={2}" , url, url.Contains('?') ? "&" : "?", Base64Helper.EncodeBase64(JsonHelper.ToJson(new { userid = result.UserId, openid = result.OpenId }))); //LogWriter.Info("OAuth2Callback:url2:" + url); return(Redirect(url)); }