AccountController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Security.Claims;
  5. using System.Threading.Tasks;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using Microsoft.AspNet.Identity;
  9. using Microsoft.AspNet.Identity.Owin;
  10. using Microsoft.Owin.Security;
  11. using Winsoft.GOV.XF.WX.Models;
  12. namespace Winsoft.GOV.XF.WX.Controllers
  13. {
  14. [Authorize]
  15. public class AccountController : Controller
  16. {
  17. private ApplicationSignInManager _signInManager;
  18. private ApplicationUserManager _userManager;
  19. public AccountController()
  20. {
  21. }
  22. public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
  23. {
  24. UserManager = userManager;
  25. SignInManager = signInManager;
  26. }
  27. public ApplicationSignInManager SignInManager
  28. {
  29. get
  30. {
  31. return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
  32. }
  33. private set
  34. {
  35. _signInManager = value;
  36. }
  37. }
  38. public ApplicationUserManager UserManager
  39. {
  40. get
  41. {
  42. return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
  43. }
  44. private set
  45. {
  46. _userManager = value;
  47. }
  48. }
  49. // Authorize 操作是当你访问任何
  50. // 受保护的 Web API 时调用的终结点。如果用户未登录,则将被重定向到
  51. // Login 页。在成功登录后,你可以调用 Web API。
  52. [HttpGet]
  53. public ActionResult Authorize()
  54. {
  55. var claims = new ClaimsPrincipal(User).Claims.ToArray();
  56. var identity = new ClaimsIdentity(claims, "Bearer");
  57. AuthenticationManager.SignIn(identity);
  58. return new EmptyResult();
  59. }
  60. //
  61. // GET: /Account/Login
  62. [AllowAnonymous]
  63. public ActionResult Login(string returnUrl)
  64. {
  65. ViewBag.ReturnUrl = returnUrl;
  66. return View();
  67. }
  68. //
  69. // POST: /Account/Login
  70. [HttpPost]
  71. [AllowAnonymous]
  72. [ValidateAntiForgeryToken]
  73. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  74. {
  75. if (!ModelState.IsValid)
  76. {
  77. return View(model);
  78. }
  79. // 这不会计入到为执行帐户锁定而统计的登录失败次数中
  80. // 若要在多次输入错误密码的情况下触发帐户锁定,请更改为 shouldLockout: true
  81. var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
  82. switch (result)
  83. {
  84. case SignInStatus.Success:
  85. return RedirectToLocal(returnUrl);
  86. case SignInStatus.LockedOut:
  87. return View("Lockout");
  88. case SignInStatus.RequiresVerification:
  89. return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  90. case SignInStatus.Failure:
  91. default:
  92. ModelState.AddModelError("", "无效的登录尝试。");
  93. return View(model);
  94. }
  95. }
  96. //
  97. // GET: /Account/VerifyCode
  98. [AllowAnonymous]
  99. public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
  100. {
  101. // 要求用户已通过使用用户名/密码或外部登录名登录
  102. if (!await SignInManager.HasBeenVerifiedAsync())
  103. {
  104. return View("Error");
  105. }
  106. return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
  107. }
  108. //
  109. // POST: /Account/VerifyCode
  110. [HttpPost]
  111. [AllowAnonymous]
  112. [ValidateAntiForgeryToken]
  113. public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
  114. {
  115. if (!ModelState.IsValid)
  116. {
  117. return View(model);
  118. }
  119. // 以下代码可以防范双重身份验证代码遭到暴力破解攻击。
  120. // 如果用户输入错误代码的次数达到指定的次数,则会将
  121. // 该用户帐户锁定指定的时间。
  122. // 可以在 IdentityConfig 中配置帐户锁定设置
  123. var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
  124. switch (result)
  125. {
  126. case SignInStatus.Success:
  127. return RedirectToLocal(model.ReturnUrl);
  128. case SignInStatus.LockedOut:
  129. return View("Lockout");
  130. case SignInStatus.Failure:
  131. default:
  132. ModelState.AddModelError("", "代码无效。");
  133. return View(model);
  134. }
  135. }
  136. //
  137. // GET: /Account/Register
  138. [AllowAnonymous]
  139. public ActionResult Register()
  140. {
  141. return View();
  142. }
  143. //
  144. // POST: /Account/Register
  145. [HttpPost]
  146. [AllowAnonymous]
  147. [ValidateAntiForgeryToken]
  148. public async Task<ActionResult> Register(RegisterViewModel model)
  149. {
  150. if (ModelState.IsValid)
  151. {
  152. var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Hometown = model.Hometown };
  153. var result = await UserManager.CreateAsync(user, model.Password);
  154. if (result.Succeeded)
  155. {
  156. await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  157. // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
  158. // 发送包含此链接的电子邮件
  159. // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  160. // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  161. // await UserManager.SendEmailAsync(user.Id, "确认你的帐户", "请通过单击<a href=\"" + callbackUrl + "\">此处</a>来确认你的帐户");
  162. return RedirectToAction("Index", "Home");
  163. }
  164. AddErrors(result);
  165. }
  166. // 如果我们进行到这一步时某个地方出错,则重新显示表单
  167. return View(model);
  168. }
  169. //
  170. // GET: /Account/ConfirmEmail
  171. [AllowAnonymous]
  172. public async Task<ActionResult> ConfirmEmail(string userId, string code)
  173. {
  174. if (userId == null || code == null)
  175. {
  176. return View("Error");
  177. }
  178. var result = await UserManager.ConfirmEmailAsync(userId, code);
  179. return View(result.Succeeded ? "ConfirmEmail" : "Error");
  180. }
  181. //
  182. // GET: /Account/ForgotPassword
  183. [AllowAnonymous]
  184. public ActionResult ForgotPassword()
  185. {
  186. return View();
  187. }
  188. //
  189. // POST: /Account/ForgotPassword
  190. [HttpPost]
  191. [AllowAnonymous]
  192. [ValidateAntiForgeryToken]
  193. public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
  194. {
  195. if (ModelState.IsValid)
  196. {
  197. var user = await UserManager.FindByNameAsync(model.Email);
  198. if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
  199. {
  200. // 请不要显示该用户不存在或者未经确认
  201. return View("ForgotPasswordConfirmation");
  202. }
  203. // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
  204. // 发送包含此链接的电子邮件
  205. // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
  206. // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  207. // await UserManager.SendEmailAsync(user.Id, "重置密码", "请通过单击<a href=\"" + callbackUrl + "\">此处</a>来重置你的密码");
  208. // return RedirectToAction("ForgotPasswordConfirmation", "Account");
  209. }
  210. // 如果我们进行到这一步时某个地方出错,则重新显示表单
  211. return View(model);
  212. }
  213. //
  214. // GET: /Account/ForgotPasswordConfirmation
  215. [AllowAnonymous]
  216. public ActionResult ForgotPasswordConfirmation()
  217. {
  218. return View();
  219. }
  220. //
  221. // GET: /Account/ResetPassword
  222. [AllowAnonymous]
  223. public ActionResult ResetPassword(string code)
  224. {
  225. return code == null ? View("Error") : View();
  226. }
  227. //
  228. // POST: /Account/ResetPassword
  229. [HttpPost]
  230. [AllowAnonymous]
  231. [ValidateAntiForgeryToken]
  232. public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
  233. {
  234. if (!ModelState.IsValid)
  235. {
  236. return View(model);
  237. }
  238. var user = await UserManager.FindByNameAsync(model.Email);
  239. if (user == null)
  240. {
  241. // 请不要显示该用户不存在
  242. return RedirectToAction("ResetPasswordConfirmation", "Account");
  243. }
  244. var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
  245. if (result.Succeeded)
  246. {
  247. return RedirectToAction("ResetPasswordConfirmation", "Account");
  248. }
  249. AddErrors(result);
  250. return View();
  251. }
  252. //
  253. // GET: /Account/ResetPasswordConfirmation
  254. [AllowAnonymous]
  255. public ActionResult ResetPasswordConfirmation()
  256. {
  257. return View();
  258. }
  259. //
  260. // POST: /Account/ExternalLogin
  261. [HttpPost]
  262. [AllowAnonymous]
  263. [ValidateAntiForgeryToken]
  264. public ActionResult ExternalLogin(string provider, string returnUrl)
  265. {
  266. // 请求重定向到外部登录提供程序
  267. return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
  268. }
  269. //
  270. // GET: /Account/SendCode
  271. [AllowAnonymous]
  272. public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
  273. {
  274. var userId = await SignInManager.GetVerifiedUserIdAsync();
  275. if (userId == null)
  276. {
  277. return View("Error");
  278. }
  279. var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
  280. var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
  281. return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
  282. }
  283. //
  284. // POST: /Account/SendCode
  285. [HttpPost]
  286. [AllowAnonymous]
  287. [ValidateAntiForgeryToken]
  288. public async Task<ActionResult> SendCode(SendCodeViewModel model)
  289. {
  290. if (!ModelState.IsValid)
  291. {
  292. return View();
  293. }
  294. // 生成令牌并发送该令牌
  295. if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
  296. {
  297. return View("Error");
  298. }
  299. return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
  300. }
  301. //
  302. // GET: /Account/ExternalLoginCallback
  303. [AllowAnonymous]
  304. public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
  305. {
  306. var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
  307. if (loginInfo == null)
  308. {
  309. return RedirectToAction("Login");
  310. }
  311. // 如果用户已具有登录名,则使用此外部登录提供程序将该用户登录
  312. var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
  313. switch (result)
  314. {
  315. case SignInStatus.Success:
  316. return RedirectToLocal(returnUrl);
  317. case SignInStatus.LockedOut:
  318. return View("Lockout");
  319. case SignInStatus.RequiresVerification:
  320. return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
  321. case SignInStatus.Failure:
  322. default:
  323. // 如果用户没有帐户,则提示该用户创建帐户
  324. ViewBag.ReturnUrl = returnUrl;
  325. ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
  326. return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
  327. }
  328. }
  329. //
  330. // POST: /Account/ExternalLoginConfirmation
  331. [HttpPost]
  332. [AllowAnonymous]
  333. [ValidateAntiForgeryToken]
  334. public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
  335. {
  336. if (User.Identity.IsAuthenticated)
  337. {
  338. return RedirectToAction("Index", "Manage");
  339. }
  340. if (ModelState.IsValid)
  341. {
  342. // 从外部登录提供程序中获取有关用户的信息
  343. var info = await AuthenticationManager.GetExternalLoginInfoAsync();
  344. if (info == null)
  345. {
  346. return View("ExternalLoginFailure");
  347. }
  348. var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Hometown = model.Hometown };
  349. var result = await UserManager.CreateAsync(user);
  350. if (result.Succeeded)
  351. {
  352. result = await UserManager.AddLoginAsync(user.Id, info.Login);
  353. if (result.Succeeded)
  354. {
  355. await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  356. return RedirectToLocal(returnUrl);
  357. }
  358. }
  359. AddErrors(result);
  360. }
  361. ViewBag.ReturnUrl = returnUrl;
  362. return View(model);
  363. }
  364. //
  365. // POST: /Account/LogOff
  366. [HttpPost]
  367. [ValidateAntiForgeryToken]
  368. public ActionResult LogOff()
  369. {
  370. AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
  371. return RedirectToAction("Index", "Home");
  372. }
  373. //
  374. // GET: /Account/ExternalLoginFailure
  375. [AllowAnonymous]
  376. public ActionResult ExternalLoginFailure()
  377. {
  378. return View();
  379. }
  380. protected override void Dispose(bool disposing)
  381. {
  382. if (disposing)
  383. {
  384. if (_userManager != null)
  385. {
  386. _userManager.Dispose();
  387. _userManager = null;
  388. }
  389. if (_signInManager != null)
  390. {
  391. _signInManager.Dispose();
  392. _signInManager = null;
  393. }
  394. }
  395. base.Dispose(disposing);
  396. }
  397. #region 帮助程序
  398. // 用于在添加外部登录名时提供 XSRF 保护
  399. private const string XsrfKey = "XsrfId";
  400. private IAuthenticationManager AuthenticationManager
  401. {
  402. get
  403. {
  404. return HttpContext.GetOwinContext().Authentication;
  405. }
  406. }
  407. private void AddErrors(IdentityResult result)
  408. {
  409. foreach (var error in result.Errors)
  410. {
  411. ModelState.AddModelError("", error);
  412. }
  413. }
  414. private ActionResult RedirectToLocal(string returnUrl)
  415. {
  416. if (Url.IsLocalUrl(returnUrl))
  417. {
  418. return Redirect(returnUrl);
  419. }
  420. return RedirectToAction("Index", "Home");
  421. }
  422. internal class ChallengeResult : HttpUnauthorizedResult
  423. {
  424. public ChallengeResult(string provider, string redirectUri)
  425. : this(provider, redirectUri, null)
  426. {
  427. }
  428. public ChallengeResult(string provider, string redirectUri, string userId)
  429. {
  430. LoginProvider = provider;
  431. RedirectUri = redirectUri;
  432. UserId = userId;
  433. }
  434. public string LoginProvider { get; set; }
  435. public string RedirectUri { get; set; }
  436. public string UserId { get; set; }
  437. public override void ExecuteResult(ControllerContext context)
  438. {
  439. var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
  440. if (UserId != null)
  441. {
  442. properties.Dictionary[XsrfKey] = UserId;
  443. }
  444. context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
  445. }
  446. }
  447. #endregion
  448. }
  449. }