IdentityServiceRegistration.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using Microsoft.AspNetCore.Authentication.JwtBearer;
  2. using Microsoft.AspNetCore.Identity;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.IdentityModel.Tokens;
  7. using MTWorkHR.Core.Global;
  8. using MTWorkHR.Identity.DBContext;
  9. using MTWorkHR.Identity.Entities;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. namespace MTWorkHR.Identity
  16. {
  17. public static class IdentityServiceRegistration
  18. {
  19. public static IServiceCollection AddIdentityServices(this IServiceCollection services, AppSettingsConfiguration config)
  20. {
  21. services.AddSingleton(config);
  22. var vv = config.ConnectionStrings.MTWorkHRConnectionString;
  23. services.AddDbContext<HRIdentityDBContext>(options =>
  24. options.UseSqlServer(
  25. config.ConnectionStrings.MTWorkHRConnectionString //configuration.GetSection("ConnectionString:MTWorkHRConnectionString").Value
  26. ));
  27. services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<HRIdentityDBContext>().AddDefaultTokenProviders();
  28. services.AddAuthentication(options => {
  29. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; // "bearer"
  30. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  31. }).AddJwtBearer(o=> o.TokenValidationParameters = new TokenValidationParameters
  32. {
  33. ValidateIssuerSigningKey = true,
  34. ValidateIssuer = true,
  35. ValidateAudience = true,
  36. ValidateLifetime = true,
  37. ClockSkew = TimeSpan.Zero,
  38. ValidIssuer = config.JwtSettings.Issuer,
  39. ValidAudience = config.JwtSettings.Audience,
  40. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.JwtSettings.SecretKey))
  41. }) ;
  42. return services;
  43. }
  44. }
  45. }