Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.72 KB | None | 0 0
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
  2. ApplicationDbContext context, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
  3. {
  4. if (env.IsDevelopment())
  5. {
  6. app
  7. .UseDeveloperExceptionPage()
  8. .UseDatabaseErrorPage();
  9. }
  10. else
  11. {
  12. app
  13. .UseExceptionHandler("/Home/Error")
  14. .UseHsts();
  15. }
  16.  
  17. app
  18. .UseAuthentication()
  19. .UseHttpsRedirection()
  20. .UseStaticFiles()
  21. .UseSpaStaticFiles();
  22.  
  23. app.UseMvc(routes =>
  24. {
  25. routes.MapRoute(
  26. name: "default",
  27. template: "{controller=Home}/{action=Index}/{id?}");
  28. });
  29.  
  30. app.UseSpa(spa =>
  31. {
  32. spa.Options.SourcePath = "VueApp";
  33.  
  34. if (env.IsDevelopment())
  35. {
  36. spa.UseVueCliServer("serve");
  37. }
  38. });
  39.  
  40. DbInitializer.Initialize(context, roleManager, userManager, env, loggerFactory);
  41. }
  42.  
  43. public void ConfigureServices(IServiceCollection services)
  44. {
  45. services
  46. .AddLogging(builder => builder
  47. .AddConsole()
  48. .AddDebug());
  49.  
  50. services
  51. .AddMvc()
  52. .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
  53. .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
  54.  
  55. // In production, the Vue files will be served from this directory
  56. services
  57. .AddSpaStaticFiles(configuration =>
  58. {
  59. configuration.RootPath = "wwwroot";
  60. });
  61.  
  62. services
  63. .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection")))
  64. .AddIdentity<ApplicationUser, IdentityRole>(options =>
  65. {
  66. // Password settings
  67. options.Password.RequireDigit = true;
  68. options.Password.RequiredLength = 8;
  69. options.Password.RequireNonAlphanumeric = true;
  70.  
  71. // Lockout settings
  72. options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
  73. options.Lockout.MaxFailedAccessAttempts = 10;
  74.  
  75. // User settings
  76. options.User.RequireUniqueEmail = true;
  77. })
  78. .AddRoleManager<RoleManager<IdentityRole>>()
  79. .AddSignInManager<SignInManager<ApplicationUser>>() // Not sure I need this - added to see if it made things better but it didn't
  80. .AddEntityFrameworkStores<ApplicationDbContext>()
  81. .AddDefaultTokenProviders();
  82.  
  83. services
  84. .ConfigureEntityServices()
  85. .ConfigureIdentityDependencies()
  86. .ConfigureDomainServices();
  87.  
  88. services.AddAuthentication(options =>
  89. {
  90. options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  91. options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  92. options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  93. }).AddCookie(options =>
  94. {
  95. options.SlidingExpiration = true;
  96. options.Events.OnRedirectToLogin = cxt =>
  97. {
  98. cxt.Response.StatusCode = 401;
  99. return Task.CompletedTask;
  100. };
  101. options.Events.OnRedirectToAccessDenied = cxt =>
  102. {
  103. cxt.Response.StatusCode = 403;
  104. return Task.CompletedTask;
  105. };
  106. options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
  107. });
  108. }
  109.  
  110. public async Task<ActionResult<CurrentUserJsonModel>> LogIn(LoginJsonModel model)
  111. {
  112. if (model == null) return BadRequest();
  113. if (!ModelState.IsValid) return BadRequest(ModelState);
  114.  
  115. var result = await authService.LogInAsync(model.UserName, model.Password);
  116.  
  117. if (!result.Succeeded)
  118. return BadRequest(result.Errors.Select(e => new ErrorJsonModel(e)).ToArray());
  119.  
  120. var principal = User;
  121.  
  122. return new CurrentUserJsonModel
  123. {
  124. UserName = result.UserName,
  125. Roles = await authService.GetRolesAsync(model.UserName, model.Password)
  126. };
  127. }
  128.  
  129. public async Task<AuthResult> LogInAsync(ApplicationUser user)
  130. {
  131. if (user != null)
  132. {
  133. await identityService.SignOutAsync();
  134. await identityService.SignInAsync(user);
  135. }
  136.  
  137. return user != null
  138. ? new AuthResult(user)
  139. : new AuthResult("Password or Email address incorrect.");
  140. }
  141.  
  142. public async Task SignInAsync(ApplicationUser user, bool isPersistent = true, string authenticationMethod = null)
  143. => await signInManager.SignInAsync(user, isPersistent, authenticationMethod);
  144.  
  145. [Authorize]
  146. [HttpGet]
  147. [ProducesResponseType(StatusCodes.Status401Unauthorized)]
  148. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  149. public async Task<ActionResult<CurrentUserJsonModel>> Get()
  150. {
  151. if (HttpContextAccessor.HttpContext.User != null)
  152. {
  153. if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
  154. return new CurrentUserJsonModel
  155. {
  156. UserName = HttpContextAccessor.HttpContext.User.Identity.Name,
  157. Roles = await authService.GetRolesAsync(HttpContextAccessor.HttpContext.User)
  158. };
  159.  
  160. return Forbid();
  161. }
  162.  
  163. return Unauthorized();
  164. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement