public ActionResult Authorize() { UserAppModel userAppModel = Session["app"] as UserAppModel; if (userAppModel == null) return RedirectToAction("Error", new { errorCode = 102 }); // 错误请求,Session已过期 int appKey = userAppModel.AppKey; string redirectUri = userAppModel.RedirectUri; string redirectUriInDb = repo.GetAppInfo(appKey).redirecturi; if (Server.UrlEncode(redirectUriInDb) != redirectUri) return RedirectToAction("Error", new { errorCode = 103 }); // 应用的回调地址与请求不一致 string code = RandomString.RandomStringImpl.CreateRandomString(20); // 产生授权码 redirectUri = HttpUtility.UrlDecode(redirectUri); // 将uri解码,用于重定向 Authorization auth = new Authorization { appkey = appKey, userid = userAppModel.UserId, code = code, createtime = DateTime.Now, expire = DateTime.Now.AddMinutes(1) //TODO:暂时设为1分钟过期,部署后可能需要调整 }; if (repo.InsertAuthorization(auth)) // 如果授权码成功存储,则重定向回应用的重定向URI,否则跳转到出错界面 return Redirect(redirectUri + "?code=" + code); return RedirectToAction("Error", new { errorCode = 104 }); // 未能产生合法的授权码 }
/// <summary> /// 增加授权码信息记录 /// </summary> /// <param name="authorization">要写入的授权码信息实体</param> /// <returns>指示插入是否成功</returns> public bool InsertAuthorization(Authorization authorization) { try { if (dbContext.Authorizations.Find(authorization.appkey, authorization.userid) != null) { log.WarnFormat("授权码已存在,将删除旧的授权码,appkey={0},userId={1}", authorization.appkey, authorization.userid); DeleteAuthorization(authorization.appkey, authorization.userid); } dbContext.Authorizations.Add(authorization); if (!SaveAll()) throw new DataException(); log.Info("添加了一条Authorization记录, appkey=" + authorization.appkey + ", userId=" + authorization.userid + ", code=" + authorization.code); return true; } catch (DataException ex) { log.Error("无法添加新的Authorization记录", ex); return false; } catch (Exception ex) { log.Fatal("未知异常:", ex); return false; } }