Guest User

Untitled

a guest
Jan 8th, 2018
656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.41 KB | None | 0 0
  1. public class AccountController : Controller
  2. {
  3. private ApplicationSignInManager _signInManager;
  4. private ApplicationUserManager _userManager;
  5.  
  6. public AccountController()
  7. {
  8. }
  9.  
  10. public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
  11. {
  12. UserManager = userManager;
  13. SignInManager = signInManager;
  14. }
  15.  
  16. public ApplicationSignInManager SignInManager
  17. {
  18. get
  19. {
  20. return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
  21. }
  22. private set
  23. {
  24. _signInManager = value;
  25. }
  26. }
  27.  
  28. public ApplicationUserManager UserManager
  29. {
  30. get
  31. {
  32. return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
  33. }
  34. private set
  35. {
  36. _userManager = value;
  37. }
  38. }
  39.  
  40. //
  41. // GET: /Account/Login
  42. [AllowAnonymous]
  43. public ActionResult Login(string returnUrl)
  44. {
  45. //Create the Admin account using setting in Web.Config(if needed)
  46. //CreateAdminIfNeeded();
  47.  
  48. //ViewBag.ReturnUrl = returnUrl;
  49. return View();
  50.  
  51. //return RedirectToAction("Index", "UserLanding");
  52. }
  53.  
  54. //
  55. // POST: /Account/Login
  56. [HttpPost]
  57. [AllowAnonymous]
  58. [ValidateAntiForgeryToken]
  59. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  60. {
  61. if (!ModelState.IsValid)
  62. {
  63. return View(model);
  64. }
  65. CreateAdminIfNeeded();
  66. // This doesn't count login failures towards account lockout
  67. // To enable password failures to trigger account lockout, change to shouldLockout: true
  68. var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
  69. switch (result)
  70. {
  71. case SignInStatus.Success:
  72. return RedirectToLocal(returnUrl);
  73. case SignInStatus.LockedOut:
  74. return View("Lockout");
  75. case SignInStatus.RequiresVerification:
  76. return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  77. case SignInStatus.Failure:
  78. ModelState.AddModelError("", "Invalid login attempt.");
  79. return View(model);
  80. default:
  81. ModelState.AddModelError("", "Invalid login attempt.");
  82. return View(model);
  83. }
  84. }
  85.  
  86. //
  87. // GET: /Account/VerifyCode
  88. [AllowAnonymous]
  89. public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
  90. {
  91. // Require that the user has already logged in via username/password or external login
  92. if (!await SignInManager.HasBeenVerifiedAsync())
  93. {
  94. return View("Error");
  95. }
  96. return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
  97. }
  98.  
  99. //
  100. // POST: /Account/VerifyCode
  101. [HttpPost]
  102. [AllowAnonymous]
  103. [ValidateAntiForgeryToken]
  104. public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
  105. {
  106. if (!ModelState.IsValid)
  107. {
  108. return View(model);
  109. }
  110.  
  111. // The following code protects for brute force attacks against the two factor codes.
  112. // If a user enters incorrect codes for a specified amount of time then the user account
  113. // will be locked out for a specified amount of time.
  114. // You can configure the account lockout settings in IdentityConfig
  115. var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
  116. switch (result)
  117. {
  118. case SignInStatus.Success:
  119. return RedirectToLocal(model.ReturnUrl);
  120. case SignInStatus.LockedOut:
  121. return View("Lockout");
  122. case SignInStatus.Failure:
  123. default:
  124. ModelState.AddModelError("", "Invalid code.");
  125. return View(model);
  126. }
  127. }
  128.  
  129. //
  130. // GET: /Account/Register
  131. [AllowAnonymous]
  132. public ActionResult Register()
  133. {
  134. return View();
  135. }
  136.  
  137. //
  138. // POST: /Account/Register
  139. [HttpPost]
  140. [AllowAnonymous]
  141. [ValidateAntiForgeryToken]
  142. public async Task<ActionResult> Register(RegisterViewModel model)
  143. {
  144. if (ModelState.IsValid)
  145. {
  146. var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  147. var result = await UserManager.CreateAsync(user, model.Password);
  148. if (result.Succeeded)
  149. {
  150. await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  151.  
  152. // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  153. // Send an email with this link
  154. // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  155. // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  156. // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href="" + callbackUrl + "">here</a>");
  157.  
  158. return RedirectToAction("Index", "Home");
  159. }
  160. AddErrors(result);
  161. }
  162.  
  163. // If we got this far, something failed, redisplay form
  164. return View(model);
  165. }
  166.  
  167. //
  168. // GET: /Account/ConfirmEmail
  169. [AllowAnonymous]
  170. public async Task<ActionResult> ConfirmEmail(string userId, string code)
  171. {
  172. if (userId == null || code == null)
  173. {
  174. return View("Error");
  175. }
  176. var result = await UserManager.ConfirmEmailAsync(userId, code);
  177. return View(result.Succeeded ? "ConfirmEmail" : "Error");
  178. }
  179.  
  180. //
  181. // GET: /Account/ForgotPassword
  182. [AllowAnonymous]
  183. public ActionResult ForgotPassword()
  184. {
  185. return View();
  186. }
  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. // Don't reveal that the user does not exist or is not confirmed
  201. return View("ForgotPasswordConfirmation");
  202. }
  203.  
  204. // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  205. // Send an email with this link
  206. // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
  207. // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  208. // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href="" + callbackUrl + "">here</a>");
  209. // return RedirectToAction("ForgotPasswordConfirmation", "Account");
  210. }
  211.  
  212. // If we got this far, something failed, redisplay form
  213. return View(model);
  214. }
  215.  
  216. //
  217. // GET: /Account/ForgotPasswordConfirmation
  218. [AllowAnonymous]
  219. public ActionResult ForgotPasswordConfirmation()
  220. {
  221. return View();
  222. }
  223.  
  224. //
  225. // GET: /Account/ResetPassword
  226. [AllowAnonymous]
  227. public ActionResult ResetPassword(string code)
  228. {
  229. return code == null ? View("Error") : View();
  230. }
  231.  
  232. //
  233. // POST: /Account/ResetPassword
  234. [HttpPost]
  235. [AllowAnonymous]
  236. [ValidateAntiForgeryToken]
  237. public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
  238. {
  239. if (!ModelState.IsValid)
  240. {
  241. return View(model);
  242. }
  243. var user = await UserManager.FindByNameAsync(model.Email);
  244. if (user == null)
  245. {
  246. // Don't reveal that the user does not exist
  247. return RedirectToAction("ResetPasswordConfirmation", "Account");
  248. }
  249. var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
  250. if (result.Succeeded)
  251. {
  252. return RedirectToAction("ResetPasswordConfirmation", "Account");
  253. }
  254. AddErrors(result);
  255. return View();
  256. }
  257.  
  258. //
  259. // GET: /Account/ResetPasswordConfirmation
  260. [AllowAnonymous]
  261. public ActionResult ResetPasswordConfirmation()
  262. {
  263. return View();
  264. }
  265.  
  266. //
  267. // POST: /Account/ExternalLogin
  268. [HttpPost]
  269. [AllowAnonymous]
  270. [ValidateAntiForgeryToken]
  271. public ActionResult ExternalLogin(string provider, string returnUrl)
  272. {
  273. // Request a redirect to the external login provider
  274. return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
  275. }
  276.  
  277. //
  278. // GET: /Account/SendCode
  279. [AllowAnonymous]
  280. public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
  281. {
  282. var userId = await SignInManager.GetVerifiedUserIdAsync();
  283. if (userId == null)
  284. {
  285. return View("Error");
  286. }
  287. var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
  288. var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
  289. return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
  290. }
  291.  
  292. //
  293. // POST: /Account/SendCode
  294. [HttpPost]
  295. [AllowAnonymous]
  296. [ValidateAntiForgeryToken]
  297. public async Task<ActionResult> SendCode(SendCodeViewModel model)
  298. {
  299. if (!ModelState.IsValid)
  300. {
  301. return View();
  302. }
  303.  
  304. // Generate the token and send it
  305. if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
  306. {
  307. return View("Error");
  308. }
  309. return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
  310. }
  311.  
  312. //
  313. // GET: /Account/ExternalLoginCallback
  314. [AllowAnonymous]
  315. public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
  316. {
  317. var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
  318. if (loginInfo == null)
  319. {
  320. return RedirectToAction("Login");
  321. }
  322.  
  323. // Sign in the user with this external login provider if the user already has a login
  324. var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
  325. switch (result)
  326. {
  327. case SignInStatus.Success:
  328. return RedirectToLocal(returnUrl);
  329. case SignInStatus.LockedOut:
  330. return View("Lockout");
  331. case SignInStatus.RequiresVerification:
  332. return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
  333. case SignInStatus.Failure:
  334. default:
  335. // If the user does not have an account, then prompt the user to create an account
  336. ViewBag.ReturnUrl = returnUrl;
  337. ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
  338. return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
  339. }
  340. }
  341.  
  342. //
  343. // POST: /Account/ExternalLoginConfirmation
  344. [HttpPost]
  345. [AllowAnonymous]
  346. [ValidateAntiForgeryToken]
  347. public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
  348. {
  349. if (User.Identity.IsAuthenticated)
  350. {
  351. return RedirectToAction("Index", "Manage");
  352. }
  353.  
  354. if (ModelState.IsValid)
  355. {
  356. // Get the information about the user from the external login provider
  357. var info = await AuthenticationManager.GetExternalLoginInfoAsync();
  358. if (info == null)
  359. {
  360. return View("ExternalLoginFailure");
  361. }
  362. var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  363. var result = await UserManager.CreateAsync(user);
  364. if (result.Succeeded)
  365. {
  366. result = await UserManager.AddLoginAsync(user.Id, info.Login);
  367. if (result.Succeeded)
  368. {
  369. await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  370. return RedirectToLocal(returnUrl);
  371. }
  372. }
  373. AddErrors(result);
  374. }
  375.  
  376. ViewBag.ReturnUrl = returnUrl;
  377. return View(model);
  378. }
  379.  
  380. //
  381. // POST: /Account/LogOff
  382. //[HttpPost]
  383. //[ValidateAntiForgeryToken]
  384. public ActionResult LogOff()
  385. {
  386. AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
  387. //System.Web.HttpContext.Current.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
  388. Session.Abandon();
  389. Session.Clear();
  390.  
  391.  
  392. return RedirectToAction("Index", "Login");
  393. }
  394.  
  395. //
  396. // GET: /Account/ExternalLoginFailure
  397. [AllowAnonymous]
  398. public ActionResult ExternalLoginFailure()
  399. {
  400. return View();
  401. }
  402.  
  403. protected override void Dispose(bool disposing)
  404. {
  405. if (disposing)
  406. {
  407. if (_userManager != null)
  408. {
  409. _userManager.Dispose();
  410. _userManager = null;
  411. }
  412.  
  413. if (_signInManager != null)
  414. {
  415. _signInManager.Dispose();
  416. _signInManager = null;
  417. }
  418. }
  419.  
  420. base.Dispose(disposing);
  421. }
  422.  
  423. #region Helpers
  424. // Used for XSRF protection when adding external logins
  425. private const string XsrfKey = "XsrfId";
  426.  
  427. private IAuthenticationManager AuthenticationManager
  428. {
  429. get
  430. {
  431. return HttpContext.GetOwinContext().Authentication;
  432. }
  433. }
  434.  
  435. private void AddErrors(IdentityResult result)
  436. {
  437. foreach (var error in result.Errors)
  438. {
  439. ModelState.AddModelError("", error);
  440. }
  441. }
  442.  
  443. private ActionResult RedirectToLocal(string returnUrl)
  444. {
  445. if (Url.IsLocalUrl(returnUrl))
  446. {
  447. return Redirect(returnUrl);
  448. }
  449. if (User.IsInRole("Administrator"))
  450. {
  451. // return RedirectToAction("Index", "AdminLanding");
  452. return RedirectToAction("Index", "Admin");
  453. }
  454. if (User.IsInRole("User"))
  455. {
  456. return RedirectToAction("Index", "Dashboard");
  457. }
  458. else
  459. return RedirectToAction("Login", "Account");
  460. }
  461.  
  462. internal class ChallengeResult : HttpUnauthorizedResult
  463. {
  464. public ChallengeResult(string provider, string redirectUri)
  465. : this(provider, redirectUri, null)
  466. {
  467. }
  468.  
  469. public ChallengeResult(string provider, string redirectUri, string userId)
  470. {
  471. LoginProvider = provider;
  472. RedirectUri = redirectUri;
  473. UserId = userId;
  474. }
  475.  
  476. public string LoginProvider { get; set; }
  477. public string RedirectUri { get; set; }
  478. public string UserId { get; set; }
  479.  
  480. public override void ExecuteResult(ControllerContext context)
  481. {
  482. var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
  483. if (UserId != null)
  484. {
  485. properties.Dictionary[XsrfKey] = UserId;
  486. }
  487. context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
  488. }
  489. }
  490. #endregion
  491.  
  492. // Utility
  493.  
  494. // Add RoleManager
  495. #region public ApplicationRoleManager RoleManager
  496. private ApplicationRoleManager _roleManager;
  497. public ApplicationRoleManager RoleManager
  498. {
  499. get
  500. {
  501. return _roleManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>();
  502. }
  503. private set
  504. {
  505. _roleManager = value;
  506. }
  507. }
  508. #endregion
  509.  
  510. // Add CreateAdminIfNeeded
  511. #region private void CreateAdminIfNeeded()
  512. private void CreateAdminIfNeeded()
  513. {
  514. // Get Admin Account
  515. string AdminUserName = ConfigurationManager.AppSettings["AdminUserName"];
  516. string AdminPassword = ConfigurationManager.AppSettings["AdminPassword"];
  517.  
  518. // See if Admin exists
  519. var objAdminUser = UserManager.FindByEmail(AdminUserName);
  520.  
  521. if (objAdminUser == null)
  522. {
  523. //See if the Admin role exists
  524. if (!RoleManager.RoleExists("Administrator"))
  525. {
  526. // Create the Admin Role (if needed)
  527. IdentityRole objAdminRole = new IdentityRole("Administrator");
  528. RoleManager.Create(objAdminRole);
  529. }
  530.  
  531. // Create Admin user
  532. var objNewAdminUser = new ApplicationUser { UserName = AdminUserName, Email = AdminUserName };
  533. var AdminUserCreateResult = UserManager.Create(objNewAdminUser, AdminPassword);
  534. // Put user in Admin role
  535. UserManager.AddToRole(objNewAdminUser.Id, "Administrator");
  536. }
  537. }
  538. #endregion
  539. }
  540.  
  541. public partial class Startup
  542. {
  543.  
  544. // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
  545. public void ConfigureAuth(IAppBuilder app)
  546. {
  547. // Configure the db context, user manager and signin manager to use a single instance per request
  548. app.CreatePerOwinContext(ApplicationDbContext.Create);
  549. app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
  550.  
  551. app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
  552.  
  553. // Add Role Manager
  554. app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
  555.  
  556. // Enable the application to use a cookie to store information for the signed in user
  557. // and to use a cookie to temporarily store information about a user logging in with a third party login provider
  558. // Configure the sign in cookie
  559. app.UseCookieAuthentication(new CookieAuthenticationOptions
  560. {
  561. AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
  562. LoginPath = new PathString("/Login"),
  563. Provider = new CookieAuthenticationProvider
  564. {
  565. // Enables the application to validate the security stamp when the user logs in.
  566. // This is a security feature which is used when you change a password or add an external login to your account.
  567. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
  568. validateInterval: TimeSpan.FromMinutes(30),
  569. regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
  570. }
  571. });
  572. app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
  573.  
  574. // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
  575. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
  576.  
  577. // Enables the application to remember the second login verification factor such as phone or email.
  578. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
  579. // This is similar to the RememberMe option when you log in.
  580. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
  581.  
  582. // Uncomment the following lines to enable logging in with third party login providers
  583. //app.UseMicrosoftAccountAuthentication(
  584. // clientId: "",
  585. // clientSecret: "");
  586.  
  587. //app.UseTwitterAuthentication(
  588. // consumerKey: "",
  589. // consumerSecret: "");
  590.  
  591. //app.UseFacebookAuthentication(
  592. // appId: "",
  593. // appSecret: "");
  594.  
  595. //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
  596. //{
  597. // ClientId = "",
  598. // ClientSecret = ""
  599. //});
  600. }
  601. }
  602.  
  603.  
  604. }
  605.  
  606. public class EmailService : IIdentityMessageService
  607. {
  608. public Task SendAsync(IdentityMessage message)
  609. {
  610. // Plug in your email service here to send an email.
  611. return Task.FromResult(0);
  612. }
  613. }
  614.  
  615. public class SmsService : IIdentityMessageService
  616. {
  617. public Task SendAsync(IdentityMessage message)
  618. {
  619. // Plug in your SMS service here to send a text message.
  620. return Task.FromResult(0);
  621. }
  622. }
  623.  
  624. // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
  625. public class ApplicationUserManager : UserManager<ApplicationUser>
  626. {
  627. public ApplicationUserManager(IUserStore<ApplicationUser> store)
  628. : base(store)
  629. {
  630. }
  631.  
  632. public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
  633. {
  634. var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
  635. // Configure validation logic for usernames
  636. manager.UserValidator = new UserValidator<ApplicationUser>(manager)
  637. {
  638. AllowOnlyAlphanumericUserNames = false,
  639. RequireUniqueEmail = true
  640. };
  641.  
  642. // Configure validation logic for passwords
  643. manager.PasswordValidator = new PasswordValidator
  644. {
  645. RequiredLength = 6,
  646. RequireNonLetterOrDigit = true,
  647. RequireDigit = true,
  648. RequireLowercase = true,
  649. RequireUppercase = true,
  650. };
  651.  
  652. // Configure user lockout defaults
  653. manager.UserLockoutEnabledByDefault = true;
  654. manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
  655. manager.MaxFailedAccessAttemptsBeforeLockout = 5;
  656.  
  657. // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
  658. // You can write your own provider and plug it in here.
  659. manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
  660. {
  661. MessageFormat = "Your security code is {0}"
  662. });
  663. manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
  664. {
  665. Subject = "Security Code",
  666. BodyFormat = "Your security code is {0}"
  667. });
  668. manager.EmailService = new EmailService();
  669. manager.SmsService = new SmsService();
  670. var dataProtectionProvider = options.DataProtectionProvider;
  671. if (dataProtectionProvider != null)
  672. {
  673. manager.UserTokenProvider =
  674. new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
  675. }
  676. return manager;
  677. }
  678. }
  679.  
  680. // Configure the application sign-in manager which is used in this application.
  681. public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
  682. {
  683. public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
  684. : base(userManager, authenticationManager)
  685. {
  686. }
  687.  
  688. public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
  689. {
  690. return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
  691. }
  692.  
  693. public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
  694. {
  695. return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
  696. }
  697. }
  698.  
  699. // Add ApplicationRoleManager to allow the management of Roles
  700. public class ApplicationRoleManager : RoleManager<IdentityRole>
  701. {
  702. public ApplicationRoleManager(IRoleStore<IdentityRole, string> store)
  703. : base(store)
  704. {
  705. }
  706. public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
  707. {
  708.  
  709. var roleStore = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>());
  710. return new ApplicationRoleManager(roleStore);
  711. }
  712. }
Add Comment
Please, Sign In to add comment