IdentityServiceRegistration.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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;
  8. using MTWorkHR.Identity.DBContext;
  9. using MTWorkHR.Identity.Models;
  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. // services.Configure<JwtSettings>(configuration.GetSection("JwtSettings"));
  23. //var vv = config.GetSection("ConnectionString:MTWorkHRConnectionString").Value;
  24. var vv = config.ConnectionStrings.MTWorkHRConnectionString;// ("ConnectionString:MTWorkHRConnectionString").Value;
  25. services.AddDbContext<HRIdentityDBContext>(options =>
  26. options.UseSqlServer(config.ConnectionStrings.MTWorkHRConnectionString
  27. //configuration.GetSection("ConnectionString:MTWorkHRConnectionString").Value
  28. ));
  29. services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<HRIdentityDBContext>().AddDefaultTokenProviders();
  30. services.AddAuthentication(options => {
  31. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; // "bearer"
  32. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  33. }).AddJwtBearer(o=> o.TokenValidationParameters = new TokenValidationParameters
  34. {
  35. ValidateIssuerSigningKey = true,
  36. ValidateIssuer = true,
  37. ValidateAudience = true,
  38. ValidateLifetime = true,
  39. ClockSkew = TimeSpan.Zero,
  40. //ValidIssuer = configuration["JwtSettings:Issuer"],
  41. //ValidAudience = configuration["JwtSettings:Audience"],
  42. ValidIssuer = config.JwtSettings.Issuer,
  43. ValidAudience = config.JwtSettings.Audience,
  44. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.JwtSettings.SecretKey))
  45. }) ;
  46. return services;
  47. }
  48. }
  49. }