DependencyInjection.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. using Application.Abstractions.Authentication;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.Chat;
  4. using Application.Abstractions.Crypto;
  5. using Application.Abstractions.Data;
  6. using Application.Abstractions.Hub;
  7. using Application.Abstractions.Identity;
  8. using Application.Abstractions.Forum;
  9. using Application.Abstractions.Messaging.Email;
  10. using Application.Abstractions.Notification;
  11. using Application.Abstractions.Payment;
  12. using Application.Abstractions.YouTube;
  13. using Application.Helpers;
  14. using Infrastructure.Authentication;
  15. using Infrastructure.Crypto;
  16. using Infrastructure.Payment;
  17. using Infrastructure.Forum;
  18. using Infrastructure.Cache;
  19. using Infrastructure.Chat;
  20. using Infrastructure.Messaging.Email;
  21. using Infrastructure.Persistence;
  22. using Infrastructure.Persistence.Identity;
  23. using Infrastructure.StockData;
  24. using Infrastructure.Storage;
  25. using Infrastructure.YouTube;
  26. using Microsoft.AspNetCore.Authentication;
  27. using Microsoft.AspNetCore.Authentication.JwtBearer;
  28. using Microsoft.AspNetCore.DataProtection;
  29. using Microsoft.AspNetCore.Identity;
  30. using Microsoft.AspNetCore.Identity.UI.Services;
  31. using Microsoft.EntityFrameworkCore;
  32. using Microsoft.EntityFrameworkCore.Diagnostics;
  33. using Microsoft.Extensions.Configuration;
  34. using Microsoft.Extensions.DependencyInjection;
  35. using Microsoft.Extensions.Options;
  36. using Microsoft.IdentityModel.Tokens;
  37. using SharedKernel;
  38. using SharedKernel.Storage;
  39. using StackExchange.Redis;
  40. using System.Text;
  41. namespace Infrastructure;
  42. public static class DependencyInjection
  43. {
  44. // SQL Server
  45. private static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration)
  46. {
  47. var dbConn = configuration.GetConnectionString("DefaultConnection");
  48. if (string.IsNullOrWhiteSpace(dbConn))
  49. {
  50. throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
  51. }
  52. // Pooling: 매 request 마다 새 DbContext 생성 비용 제거. ChangeTracker 등 내부 상태는 풀 반환 시 자동 reset
  53. // ConfigureWarnings: EF 9+의 PendingModelChangesWarning을 무시 (snapshot 일관성 문제로 false-positive 발생, 마이그레이션은 별도 관리)
  54. void ConfigureAppDb(DbContextOptionsBuilder options) => options
  55. .UseSqlServer(dbConn)
  56. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning));
  57. services.AddDbContextPool<AppDbContext>(ConfigureAppDb, poolSize: 128);
  58. services.AddDbContextPool<IdentityDbContext>(options => options
  59. .UseSqlServer(dbConn)
  60. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)), poolSize: 64);
  61. services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());
  62. // Phase 1.5: out-of-band 커밋(대사 로그·동시성 재시도)용 풀링 팩토리.
  63. // 내부 등록이 전부 TryAdd 라 위 AddDbContextPool 과 같은 옵션·풀을 공유하며 중복 등록 없이 공존한다.
  64. services.AddPooledDbContextFactory<AppDbContext>(ConfigureAppDb, poolSize: 128);
  65. services.AddSingleton<IAppDbContextFactory, AppDbContextFactory>();
  66. return services;
  67. }
  68. // Redis Server
  69. public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
  70. {
  71. var settings = configuration.Get<AppSettings>()!;
  72. var redis = ConnectionMultiplexer.Connect(settings.Redis.DefaultConnection);
  73. services.AddSingleton<IConnectionMultiplexer>(redis);
  74. services.AddDataProtection()
  75. .SetApplicationName(settings.App.Name)
  76. .PersistKeysToStackExchangeRedis(redis, settings.Redis.DataProtectionKey)
  77. .ProtectKeysWithDpapi(protectToLocalMachine: true) // key를 암호화하여 저장 (로컬 머신에서만 복호화 가능, 서버간 공유 불가)
  78. .SetDefaultKeyLifetime(settings.Redis.DefaultKeyLifetime); // 기본 90일 주기
  79. // Distributed Cache 설정
  80. services.AddStackExchangeRedisCache(options =>
  81. {
  82. options.Configuration = settings.Redis.DefaultConnection;
  83. options.InstanceName = settings.Redis.CachePrefix;
  84. });
  85. return services;
  86. }
  87. private static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
  88. {
  89. var settings = configuration.Get<AppSettings>()!;
  90. services.AddHealthChecks().AddSqlServer(settings.ConnectionStrings.DefaultConnection).AddRedis(settings.Redis.DefaultConnection);
  91. return services;
  92. }
  93. // Admin/Api 둘 다 필요한 공용 서비스 (singleton/transient/scoped, HttpClient)
  94. private static IServiceCollection AddCommonServices(this IServiceCollection services, IConfiguration configuration)
  95. {
  96. // 파일 저장 위치 옵션 (deploy 영향 받지 않는 외부 경로 권장)
  97. services.Configure<StorageOptions>(configuration.GetSection(StorageOptions.SectionName));
  98. services.AddSingleton<IJwtTokenProvider, JwtTokenProvider>();
  99. services.AddSingleton<ILegacyPasswordVerifier, BcryptLegacyPasswordVerifier>();
  100. services.AddSingleton<ICacheService, RedisCacheService>();
  101. services.AddSingleton<IFieldEncryptor, AesGcmFieldEncryptor>();
  102. services.AddTransient<IEmailSender, IdentityEmailSender>();
  103. services.AddScoped<IFileStorage, LocalFileStorage>();
  104. services.AddScoped<IEditorImageService, EditorImageService>();
  105. services.AddScoped<IIdentityUserReader, IdentityUserReader>();
  106. services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
  107. services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
  108. services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();
  109. services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
  110. services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
  111. services.AddSingleton<IChatLeaderboard, RedisChatLeaderboard>();
  112. services.AddSingleton<Application.Abstractions.Paper.IPaperLeaderboardCache, Paper.PaperLeaderboardCache>();
  113. services.AddSingleton<Application.Abstractions.Stocks.IStockBoardTrendingCache, Stocks.RedisStockBoardTrendingCache>();
  114. services.AddSingleton<IChatRewardHook, RewardChatHook>(); // D3 M2 실구현 — ChatExpConfig 수치를 RewardService 로 지급 (d0 §2.2)
  115. services.AddSingleton<IPresenceTracker, Hubs.PresenceTracker>();
  116. services.AddSingleton<IVisitorTracker, Hubs.RedisVisitorTracker>();
  117. services.AddScoped<IBoardPermissionService, BoardPermissionService>();
  118. services.AddHttpClient<IGoogleTokenValidator, GoogleTokenValidator>();
  119. // 소셜 로그인 provider (개미투자 D5 — Naver/Kakao authorization code). 핸들러가 IEnumerable 에서 이름으로 해석
  120. services.AddHttpClient<NaverAuthProvider>();
  121. services.AddHttpClient<KakaoAuthProvider>();
  122. services.AddTransient<ISocialAuthProvider>(sp => sp.GetRequiredService<NaverAuthProvider>());
  123. services.AddTransient<ISocialAuthProvider>(sp => sp.GetRequiredService<KakaoAuthProvider>());
  124. // YouTube & Google OAuth (HttpClients + singletons — Admin에서도 "API 키 테스트" 등에 쓰므로 공용)
  125. services.AddSingleton<IYouTubeApiKeyProvider, YouTubeApiKeyProvider>();
  126. services.AddTransient<YouTubeApiKeyHandler>();
  127. services.AddTransient<IYouTubeApiConnectionTester, YouTubeApiConnectionTester>();
  128. services.AddHttpClient("YouTubeApi", client =>
  129. {
  130. client.Timeout = TimeSpan.FromSeconds(15);
  131. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  132. })
  133. .AddHttpMessageHandler<YouTubeApiKeyHandler>();
  134. services.AddHttpClient("PubSubHub", client =>
  135. {
  136. client.Timeout = TimeSpan.FromSeconds(15);
  137. });
  138. services.AddHttpClient("YouTubeFeed", client =>
  139. {
  140. client.Timeout = TimeSpan.FromSeconds(10);
  141. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/atom+xml"));
  142. });
  143. services.AddHttpClient<IGoogleOAuthService, GoogleOAuthService>();
  144. services.AddHttpClient<ITossPaymentService, TossPaymentService>(client =>
  145. {
  146. client.Timeout = TimeSpan.FromSeconds(60); // 토스 승인 API 권장 타임아웃 — 짧으면 통신 불명(대사 대상)만 늘어난다
  147. });
  148. services.AddSingleton<IYouTubeApiService, YouTubeApiService>();
  149. services.AddSingleton<IYouTubeChannelCache, YouTubeChannelCache>();
  150. services.AddSingleton<IYouTubeLiveStateStore, YouTubeLiveStateStore>();
  151. services.AddSingleton<YouTubeLiveChatService>();
  152. services.AddSingleton<IYouTubeLiveChatService>(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  153. services.AddSingleton<YouTubePubSubService>();
  154. services.AddSingleton<IYouTubePubSubService>(sp => sp.GetRequiredService<YouTubePubSubService>());
  155. services.AddSingleton<IYouTubeFeedPoller, YouTubeFeedPoller>();
  156. // Notification
  157. services.AddScoped<INotificationService, Notification.NotificationService>();
  158. // Feed broadcaster (SignalR)
  159. services.AddScoped<IFeedBroadcaster, Hubs.FeedBroadcaster>();
  160. // Channel status broadcaster (라이브 시작/종료/시청자 수 → AppHub 브로드캐스트)
  161. services.AddSingleton<IChannelStatusBroadcaster, Hubs.ChannelStatusBroadcaster>();
  162. return services;
  163. }
  164. // Web.Api 전용 백그라운드 서비스 (Admin에서 중복 실행되면 quota 2배/폴링 2번 문제)
  165. // appsettings.json BackgroundJobs 섹션으로 개별 토글 (기본 모두 true). 진단용 A/B 테스트에 사용
  166. private static IServiceCollection AddBackgroundServices(this IServiceCollection services, IConfiguration configuration)
  167. {
  168. // Features:Channel OFF → YouTube/채널 백그라운드 서비스 전체 미등록 (코드 보존, 기능 노출 0)
  169. var features = configuration.GetSection("Features").Get<AppSettings.FeaturesSection>() ?? new AppSettings.FeaturesSection();
  170. if (!features.Channel)
  171. {
  172. return services;
  173. }
  174. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  175. if (bg.LiveChat)
  176. {
  177. services.AddHostedService(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  178. }
  179. if (bg.PubSubRenewal)
  180. {
  181. services.AddHostedService<YouTubePubSubRenewalService>();
  182. }
  183. if (bg.FeedPolling)
  184. {
  185. services.AddHostedService<YouTubeFeedPollingService>();
  186. }
  187. if (bg.LiveViewerPoller)
  188. {
  189. services.AddHostedService<YouTubeLiveViewerPoller>();
  190. }
  191. if (bg.ChannelCacheRefresh)
  192. {
  193. services.AddHostedService<YouTubeChannelCacheRefreshService>();
  194. }
  195. if (bg.YouTubeDailyAggregator)
  196. {
  197. services.AddHostedService<YouTubeDailyAggregatorService>();
  198. }
  199. if (bg.YouTubeStaleDataPurge)
  200. {
  201. services.AddHostedService<YouTubeStaleDataPurgeService>();
  202. }
  203. return services;
  204. }
  205. // 결제 자동 대사 배치 (Toss NeedsReconciliation 재확인) — Features:Channel 게이트 밖 별도 등록, Web.Api 전용.
  206. // BackgroundJobs:PaymentReconcile 플래그로 토글 (기본 true — 대상 없으면 PG 호출 없이 skip)
  207. private static IServiceCollection AddPaymentBackgroundServices(this IServiceCollection services, IConfiguration configuration)
  208. {
  209. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  210. if (bg.PaymentReconcile)
  211. {
  212. services.AddHostedService<PaymentReconcileService>();
  213. }
  214. return services;
  215. }
  216. // 주식 데이터 수집 배치 (개미투자 D1) — Features:Channel 게이트 밖 별도 등록.
  217. // StockData 섹션 플래그로 개별 토글 (기본 모두 false — API 키 발급/운영 결정 후 활성화)
  218. private static IServiceCollection AddStockDataServices(this IServiceCollection services, IConfiguration configuration)
  219. {
  220. services.AddHttpClient(DataGoKrHttp.ClientName, client =>
  221. {
  222. client.Timeout = TimeSpan.FromSeconds(30);
  223. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  224. });
  225. // KRX OpenAPI(data-dbg.krx.co.kr) 지수 수집 클라이언트 — AUTH_KEY 헤더는 요청 단위로 부여 (KrxCoKrHttp)
  226. services.AddHttpClient(KrxCoKrHttp.ClientName, client =>
  227. {
  228. client.Timeout = TimeSpan.FromSeconds(30);
  229. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  230. });
  231. // OpenDART(opendart.fss.or.kr) 공시 수집 클라이언트 — 인증은 URL query param crtfc_key (요청 단위, OpenDartHttp)
  232. services.AddHttpClient(OpenDartHttp.ClientName, client =>
  233. {
  234. client.Timeout = TimeSpan.FromSeconds(30);
  235. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  236. });
  237. // 한국수출입은행(koreaexim.go.kr) 거시·환율 수집 클라이언트 — 인증은 URL query param authkey (요청 단위, KoreaEximHttp)
  238. services.AddHttpClient(KoreaEximHttp.ClientName, client =>
  239. {
  240. client.Timeout = TimeSpan.FromSeconds(30);
  241. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  242. });
  243. // KOSIS(kosis.kr) 거시경제지표 수집 클라이언트 — 인증은 URL query param apiKey (요청 단위, KosisHttp). 응답은 JSON
  244. services.AddHttpClient(KosisHttp.ClientName, client =>
  245. {
  246. client.Timeout = TimeSpan.FromSeconds(30);
  247. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  248. });
  249. // SEIBro OpenAPI(seibro.or.kr) 수집 클라이언트 — 인증은 URL query param key (요청 단위, SeibroHttp). 응답은 XML
  250. services.AddHttpClient(SeibroHttp.ClientName, client =>
  251. {
  252. client.Timeout = TimeSpan.FromSeconds(30);
  253. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
  254. });
  255. // Stooq(stooq.com) 무인증 CSV 시세 클라이언트 — (구) 세계지수/종목 수집. Stooq 봇차단(2026-07)으로 미사용, 등록만 보존
  256. services.AddHttpClient(StooqHttp.ClientName, client =>
  257. {
  258. client.Timeout = TimeSpan.FromSeconds(30);
  259. });
  260. // Yahoo Finance v8 chart 무인증 JSON 클라이언트 — 세계지수·종목 수집 (YahooFinanceHttp). UA 필수(없으면 거부). Stooq 대체
  261. services.AddHttpClient(YahooFinanceHttp.ClientName, client =>
  262. {
  263. client.Timeout = TimeSpan.FromSeconds(30);
  264. client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0");
  265. });
  266. // SEIBro 카테고리별 일일 호출 예산 트래커 — 같은 카테고리 배치들이 하나의 카운터를 공유 (in-memory, KST 자정 롤오버)
  267. services.AddSingleton(_ => new SeibroQuota());
  268. // 수집기 활성화/키는 DB Config(DataCollection)에서 런타임 조회 — Admin hot-manage (재배포 없이 on/off·키 교체)
  269. services.AddScoped<ICollectorSettingsProvider, CollectorSettingsProvider>();
  270. // 데이터 수집 배치는 전부 항상 등록. 활성 여부·API 키는 각 수집기가 런타임에 DB(Config.DataCollection)에서 판단(키 미설정 시 appsettings 폴백).
  271. // 예외: BackgroundJobs(PaperFill/PredictionSettlement/DailyBriefing)는 외부키 없는 내부 배치라 appsettings 게이팅 유지.
  272. services.AddHostedService<StockMasterSyncService>();
  273. services.AddHostedService<DailyPriceSyncService>();
  274. services.AddHostedService<IndexPriceSyncService>();
  275. services.AddHostedService<BondIndexPriceSyncService>();
  276. services.AddHostedService<KrxStockMasterSyncService>();
  277. services.AddHostedService<KrxDailyPriceSyncService>();
  278. services.AddHostedService<KrxEtpSyncService>();
  279. services.AddHostedService<KrxWarrantSyncService>();
  280. services.AddHostedService<KrxBondSyncService>();
  281. services.AddHostedService<KrxDerivativeSyncService>();
  282. services.AddHostedService<KrxCommoditySyncService>();
  283. services.AddHostedService<KrxEsgSyncService>();
  284. services.AddHostedService<DisclosureSyncService>();
  285. services.AddHostedService<MacroDataSyncService>();
  286. services.AddHostedService<KosisSyncService>();
  287. services.AddHostedService<SeibroIssuerSyncService>();
  288. services.AddHostedService<SeibroDividendSyncService>();
  289. services.AddHostedService<SeibroSupplySyncService>();
  290. services.AddHostedService<SeibroCorpActionSyncService>();
  291. services.AddHostedService<SeibroBondSyncService>();
  292. services.AddHostedService<SeibroDerivSyncService>();
  293. services.AddHostedService<SeibroForeignSyncService>();
  294. services.AddHostedService<WorldIndexSyncService>();
  295. services.AddHostedService<MarketQuoteSyncService>();
  296. // 모의투자 체결·스냅샷 배치 (d4 M2) — BackgroundJobs:PaperFill 플래그 (기본 false). Web.Api 전용.
  297. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  298. if (bg.PaperFill)
  299. {
  300. services.AddHostedService<PaperFillService>();
  301. }
  302. // 예측 채점 배치 (d2 M4) — BackgroundJobs:PredictionSettlement 플래그 (기본 false). Web.Api 전용.
  303. if (bg.PredictionSettlement)
  304. {
  305. services.AddHostedService<PredictionSettlementService>();
  306. }
  307. // 장전 브리핑 자동 발행 배치 (d2 M3) — BackgroundJobs:DailyBriefing 플래그 (기본 false, 07:30 KST). Web.Api 전용.
  308. if (bg.DailyBriefing)
  309. {
  310. services.AddHostedService<DailyBriefingPublisher>();
  311. }
  312. return services;
  313. }
  314. /**
  315. * ========================================================================================================================================================================================================
  316. * ========================================================================================================================================================================================================
  317. */
  318. // Admin 전용 — 백그라운드 서비스는 포함하지 않음 (Web.Api에서만 돌아야 함)
  319. // 메일은 즉시 SMTP 발송 (DirectMailService)
  320. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  321. {
  322. services.AddScoped<IMailService, DirectMailService>();
  323. return services.AddDatabase(configuration).AddRedis(configuration).AddCommonServices(configuration).AddHealthChecks(configuration);
  324. }
  325. /**
  326. * ========================================================================================================================================================================================================
  327. * ========================================================================================================================================================================================================
  328. */
  329. // API 전용 — 공용 서비스 + 백그라운드 서비스 모두 포함
  330. // 메일은 EmailLog 큐에 적재 (QueuedMailService) — MailWorker가 별도로 폴링하여 SMTP 송신
  331. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  332. {
  333. services.AddScoped<IMailService, QueuedMailService>();
  334. // 기동 시 핵심 게시판(notice/briefing/proof) 멱등 시드 — /board/* 404 방지
  335. services.AddHostedService<Forum.BoardBootstrapSeeder>();
  336. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddCommonServices(configuration).AddBackgroundServices(configuration).AddPaymentBackgroundServices(configuration).AddStockDataServices(configuration).AddHealthChecks(configuration);
  337. }
  338. private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
  339. {
  340. var settings = configuration.Get<AppSettings>()!;
  341. // 인증 정책- JWT Bearer
  342. services.AddAuthentication(options =>
  343. {
  344. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  345. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  346. })
  347. .AddJwtBearer(options =>
  348. {
  349. options.RequireHttpsMetadata = false;
  350. options.MapInboundClaims = false;
  351. options.TokenValidationParameters = new TokenValidationParameters
  352. {
  353. ValidateIssuer = true,
  354. ValidateAudience = true,
  355. ValidateLifetime = true,
  356. ValidateIssuerSigningKey = true,
  357. ValidIssuer = settings.JWT.Issuer,
  358. ValidAudience = settings.JWT.Audience,
  359. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  360. ClockSkew = TimeSpan.Zero
  361. };
  362. options.Events = new JwtBearerEvents
  363. {
  364. OnMessageReceived = context =>
  365. {
  366. var accessToken = context.Request.Query["access_token"];
  367. var path = context.HttpContext.Request.Path;
  368. if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
  369. {
  370. context.Token = accessToken;
  371. }
  372. return Task.CompletedTask;
  373. }
  374. };
  375. });
  376. services.AddAuthorization();
  377. // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
  378. services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
  379. return services;
  380. }
  381. }