public ActionResult Login(string returnUrl, string verifykey) { //宣告 HongHwa.Sso sso = new HongHwa.Sso(); //傳入此網頁的System.Web.HttpContextBase型別 sso.AllowCrossReferrer(this.HttpContext); if (string.IsNullOrWhiteSpace(verifykey)) { Uri uri = HongHwa.Settings.SsoWebDevelop; string url = uri.AbsoluteUri; ViewBag.SSOUrl = url; return(View("SSORedirect")); } else { //設定取得Sso認證後的帳號 string account; //呼叫Sso並取得認證結果 //請視環境選用相對應的SSO Uri,此處範例為正式環境,故選用HongHwa.Settings.SsoWeb if (sso.Authorize(HongHwa.Settings.SsoWebDevelop, verifykey, out account)) { //認證成功 logger.Info($"sso.Authorize is true, account = {account}"); //有取得帳號名稱 前往View 把帳號Post然後做非同步處理 if (!string.IsNullOrWhiteSpace(account)) { logger.Info("go to SSOLogin"); SSOViewModel model = new SSOViewModel { Verifykey = verifykey }; return(View("SSOLogin", model)); } else { logger.Info("SSO fail"); return(RedirectToAction("Index", "Home")); } } else { logger.Info("SSO fail"); return(RedirectToAction("Index", "Home")); } } }
public async Task <ActionResult> Login(SSOViewModel model) { if (!ModelState.IsValid) { return(RedirectToAction("Index", "Home")); } logger.Info($"SSO接回後Post進來 vkey = {model.Verifykey}"); string account; HongHwa.Sso sso = new HongHwa.Sso(); //傳遞vkey再取帳號應該比較安全? if (sso.Authorize(HongHwa.Settings.SsoWebDevelop, model.Verifykey, out account)) { var user = new ApplicationUser { Id = account, UserName = account }; //沒帳號直接登入會跳錯 if (UserManager.FindById(account) != null) { SignInManager.SignIn(user, isPersistent: false, rememberBrowser: false); logger.Info($"登入成功"); TempData["AlertMsg"] = "登入成功"; } if (UserManager.FindById(account) == null) { var createResult = await UserManager.CreateAsync(user); foreach (var error in createResult.Errors) { logger.Debug($"ERROR = {error}"); } if (createResult.Succeeded) { logger.Info($"無帳號 建立帳號成功"); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); //角色存在判斷 var roleName = "一般使用者"; if (RoleManager.RoleExists(roleName) == false) { var role = new IdentityRole(roleName); await RoleManager.CreateAsync(role); } //將使用者加入角色 await UserManager.AddToRoleAsync(user.Id, roleName); TempData["AlertMsg"] = "登入成功"; return(RedirectToAction("Index", "Home")); } else { logger.Info($"無帳號 建立帳號失敗 嘗試登入"); TempData["AlertMsg"] = "登入失敗,請重新操作"; } } } else { TempData["AlertMsg"] = "登入失敗,請重新操作"; } return(RedirectToAction("Index", "Home")); }