Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
- ApplicationDbContext context, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
- {
- if (env.IsDevelopment())
- {
- app
- .UseDeveloperExceptionPage()
- .UseDatabaseErrorPage();
- }
- else
- {
- app
- .UseExceptionHandler("/Home/Error")
- .UseHsts();
- }
- app
- .UseAuthentication()
- .UseHttpsRedirection()
- .UseStaticFiles()
- .UseSpaStaticFiles();
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
- app.UseSpa(spa =>
- {
- spa.Options.SourcePath = "VueApp";
- if (env.IsDevelopment())
- {
- spa.UseVueCliServer("serve");
- }
- });
- DbInitializer.Initialize(context, roleManager, userManager, env, loggerFactory);
- }
- public void ConfigureServices(IServiceCollection services)
- {
- services
- .AddLogging(builder => builder
- .AddConsole()
- .AddDebug());
- services
- .AddMvc()
- .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
- .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
- // In production, the Vue files will be served from this directory
- services
- .AddSpaStaticFiles(configuration =>
- {
- configuration.RootPath = "wwwroot";
- });
- services
- .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection")))
- .AddIdentity<ApplicationUser, IdentityRole>(options =>
- {
- // Password settings
- options.Password.RequireDigit = true;
- options.Password.RequiredLength = 8;
- options.Password.RequireNonAlphanumeric = true;
- // Lockout settings
- options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
- options.Lockout.MaxFailedAccessAttempts = 10;
- // User settings
- options.User.RequireUniqueEmail = true;
- })
- .AddRoleManager<RoleManager<IdentityRole>>()
- .AddSignInManager<SignInManager<ApplicationUser>>() // Not sure I need this - added to see if it made things better but it didn't
- .AddEntityFrameworkStores<ApplicationDbContext>()
- .AddDefaultTokenProviders();
- services
- .ConfigureEntityServices()
- .ConfigureIdentityDependencies()
- .ConfigureDomainServices();
- services.AddAuthentication(options =>
- {
- options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
- options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
- options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
- }).AddCookie(options =>
- {
- options.SlidingExpiration = true;
- options.Events.OnRedirectToLogin = cxt =>
- {
- cxt.Response.StatusCode = 401;
- return Task.CompletedTask;
- };
- options.Events.OnRedirectToAccessDenied = cxt =>
- {
- cxt.Response.StatusCode = 403;
- return Task.CompletedTask;
- };
- options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
- });
- }
- public async Task<ActionResult<CurrentUserJsonModel>> LogIn(LoginJsonModel model)
- {
- if (model == null) return BadRequest();
- if (!ModelState.IsValid) return BadRequest(ModelState);
- var result = await authService.LogInAsync(model.UserName, model.Password);
- if (!result.Succeeded)
- return BadRequest(result.Errors.Select(e => new ErrorJsonModel(e)).ToArray());
- var principal = User;
- return new CurrentUserJsonModel
- {
- UserName = result.UserName,
- Roles = await authService.GetRolesAsync(model.UserName, model.Password)
- };
- }
- public async Task<AuthResult> LogInAsync(ApplicationUser user)
- {
- if (user != null)
- {
- await identityService.SignOutAsync();
- await identityService.SignInAsync(user);
- }
- return user != null
- ? new AuthResult(user)
- : new AuthResult("Password or Email address incorrect.");
- }
- public async Task SignInAsync(ApplicationUser user, bool isPersistent = true, string authenticationMethod = null)
- => await signInManager.SignInAsync(user, isPersistent, authenticationMethod);
- [Authorize]
- [HttpGet]
- [ProducesResponseType(StatusCodes.Status401Unauthorized)]
- [ProducesResponseType(StatusCodes.Status403Forbidden)]
- public async Task<ActionResult<CurrentUserJsonModel>> Get()
- {
- if (HttpContextAccessor.HttpContext.User != null)
- {
- if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
- return new CurrentUserJsonModel
- {
- UserName = HttpContextAccessor.HttpContext.User.Identity.Name,
- Roles = await authService.GetRolesAsync(HttpContextAccessor.HttpContext.User)
- };
- return Forbid();
- }
- return Unauthorized();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement