Эх сурвалжийг харах

Merge branch 'master' of http://git.fwt.com/CallCenter/callcenter

Dun.Jason 2 жил өмнө
parent
commit
ee11e5db82

+ 2 - 1
src/CallCenter.Api/CallCenter.Api.csproj

@@ -5,13 +5,14 @@
     <Nullable>enable</Nullable>
     <ImplicitUsings>enable</ImplicitUsings>
     <GenerateDocumentationFile>True</GenerateDocumentationFile>
-    <DocumentationFile>Document.xml</DocumentationFile>
+    <DocumentationFile>document.xml</DocumentationFile>
   </PropertyGroup>
 
   <ItemGroup>
     <PackageReference Include="FluentValidation.AspNetCore" Version="11.2.1" />
     <PackageReference Include="Mapster.DependencyInjection" Version="1.0.0" />
     <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="10.0.1" />
+    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.10" />
     <PackageReference Include="Microsoft.AspNetCore.SignalR.StackExchangeRedis" Version="6.0.8" />
     <PackageReference Include="NETCore.Encrypt" Version="2.1.0" />
     <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />

+ 7 - 5
src/CallCenter.Api/Controllers/TestController.cs

@@ -58,11 +58,13 @@ namespace CallCenter.Api.Controllers
         [HttpGet]
         public async Task Test1()
         {
-            var user = await _userRepository.GetAsync("08da8016-72af-48b3-8c8f-b39251229f79");
-            _cache.Add(user.Id, user, ExpireMode.None, TimeSpan.FromMinutes(1));
-            var user1 = _cache.Get(user.Id);
-            user1.NickName = "aaa";
-            _cache.Update(user.Id, d => user1);
+            var user = User;
+            var uid = _sessionContext.UserId;
+            //var user = await _userRepository.GetAsync("08da8016-72af-48b3-8c8f-b39251229f79");
+            //_cache.Add(user.Id, user, ExpireMode.None, TimeSpan.FromMinutes(1));
+            //var user1 = _cache.Get(user.Id);
+            //user1.NickName = "aaa";
+            //_cache.Update(user.Id, d => user1);
 
             //var config = new ConfigurationBuilder()
             //    .WithUpdateMode(CacheUpdateMode.Up)

+ 0 - 7
src/CallCenter.Api/Controllers/TestSdkController.cs

@@ -37,13 +37,6 @@ namespace CallCenter.Api.Controllers
             _options = options;
         }
 
-        [HttpGet("testconfig")]
-        public string Test([FromServices] IConfiguration configuration)
-        {
-            var a = configuration.GetSection("WorkTimeSettings:MorningBegin").Get<string>();
-            return a;
-        }
-
         #region  查询(Query)
 
         /// <summary>

+ 1 - 1
src/CallCenter.Api/Filters/TempTokenFilter.cs

@@ -9,7 +9,7 @@ using XF.Domain.Exceptions;
 
 namespace CallCenter.Api.Filters;
 
-public class TempTokenFilter : IAuthorizationFilter
+public class TempTokenFilter1 : IAuthorizationFilter
 {
     /// <summary>
     /// Called early in the filter pipeline to confirm request is authorized.

+ 53 - 6
src/CallCenter.Api/StartupExtensions.cs

@@ -1,4 +1,5 @@
-using System.Reflection;
+using System.IdentityModel.Tokens.Jwt;
+using System.Reflection;
 using CallCenter.Api.Exceptions;
 using CallCenter.Api.Filters;
 using CallCenter.Api.Realtimes;
@@ -16,6 +17,9 @@ using CallCenter.CacheManager;
 using FluentValidation;
 using FluentValidation.AspNetCore;
 using CallCenter.Settings;
+using Identity.Admin.HttpClient;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.IdentityModel.Tokens;
 using Serilog;
 
 namespace CallCenter.Api;
@@ -44,9 +48,31 @@ internal static class StartupExtensions
             .AddApplication()
             ;
 
+        services.AddIdentityClient(
+            new IdentityClientConfiguration("http://identity.fengwo.com", "http://open.identity.fengwo.com"),
+            d =>
+            {
+                d.ClientId = "hotline_server";
+                d.ClientSecret = "ce2fae0e-f0f6-46d6-bd79-1f1a31dff494";
+                d.ClientScope = "identity.admin_api";
+            });
+
+        JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
+        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, d =>
+            {
+                d.Authority = "http://identity.fengwo.com"; //todo
+                d.RequireHttpsMetadata = false;
+                d.TokenValidationParameters = new TokenValidationParameters
+                {
+                    ValidateAudience = false
+                };
+            })
+            ;
+
         services.AddControllers(options =>
         {
-            options.Filters.Add<TempTokenFilter>();
+            //options.Filters.Add<TempTokenFilter>();
             options.Filters.Add<UnifyResponseFilter>();
             options.Filters.Add<UserFriendlyExceptionFilter>();
         });
@@ -55,16 +81,35 @@ internal static class StartupExtensions
         services.AddSwaggerGen(c =>
         {
             //添加文档
-            c.SwaggerDoc("v1", new OpenApiInfo() { Title = "WebApi", Version = "v1.0" });
+            c.SwaggerDoc("v1", new OpenApiInfo() { Title = "CallCenter Api", Version = "v1.0", Description = "呼叫中心api"});
             //使用反射获取xml文件,并构造出文件的路径
-            var xmlFile = "Document.xml";
+            var xmlFile = "document.xml";
+            //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
             var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
             // 启用xml注释. 该方法第二个参数启用控制器的注释,默认为false.
             c.IncludeXmlComments(xmlPath, true);
+
+            var scheme = new OpenApiSecurityScheme()
+            {
+                Description = "Authorization header. \r\nExample: 'Bearer ***'",
+                Reference = new OpenApiReference
+                {
+                    Type = ReferenceType.SecurityScheme,
+                    Id = "Authorization"
+                },
+                Scheme = "oauth2",
+                Name = "Authorization",
+                In = ParameterLocation.Header,
+                Type = SecuritySchemeType.ApiKey,
+            };
+            c.AddSecurityDefinition("Authorization", scheme);
+            var requirement = new OpenApiSecurityRequirement();
+            requirement[scheme] = new List<string>();
+            c.AddSecurityRequirement(requirement);
         });
 
         //signalR
-        builder.Services.AddSignalR().AddStackExchangeRedis("redis.fengwo.com:6380", options =>
+        builder.Services.AddSignalR().AddStackExchangeRedis(configuration.GetConnectionString("Redis"), options =>
         {
             options.Configuration.ChannelPrefix = "callcenter:signalR:";
         });
@@ -134,11 +179,13 @@ internal static class StartupExtensions
 
         app.UseCors(CorsOrigins);
 
+        app.UseAuthentication();
         app.UseAuthorization();
         //app.MapHub<CallCenterHub>("/hubs/callcenter");
         //app.UseMiddleware<TempTokenMiddleware>();
 
-        app.MapControllers();
+        app.MapControllers()
+            .RequireAuthorization();
 
         return app;
     }

+ 2 - 2
src/CallCenter.Api/Token/DefaultSessionContext.cs

@@ -14,9 +14,9 @@ namespace CallCenter.Api.Token
                 throw new ArgumentNullException(nameof(httpContext));
             //var a = Thread.CurrentPrincipal as ClaimsPrincipal;
             var user = httpContext.User;
-            UserId = user.Claims.FirstOrDefault(d => d.Type == "UserId")?.Value ?? string.Empty;
+            UserId = user.Claims.FirstOrDefault(d => d.Type == "sub")?.Value ?? string.Empty;
             UserName = user.Claims.FirstOrDefault(d => d.Type == "UserName")?.Value ?? string.Empty;
-            
+            var roles = user.Claims.FirstOrDefault(d => d.Type == "role");
         }
 
         /// <summary>

+ 59 - 4
src/CallCenter.Api/appsettings.Development.json

@@ -1,8 +1,63 @@
 {
-  "Logging": {
-    "LogLevel": {
+  "Serilog": {
+    "Using": [
+      "Serilog.Enrichers.Span",
+      "Serilog.Sinks.Console"
+    ],
+    "MinimumLevel": {
       "Default": "Information",
-      "Microsoft.AspNetCore": "Warning"
-    }
+      "Override": {
+        "Microsoft": "Warning",
+        "Microsoft.Hosting.Lifetime": "Information",
+        "Microsoft.AspNetCore.Authentication": "Debug",
+        "Microsoft.AspNetCore": "Warning",
+        "Microsoft.AspNetCore.SignalR": "Debug",
+        "Microsoft.AspNetCore.Http.Connections": "Debug",
+        "System": "Warning"
+      }
+    },
+    "WriteTo": [
+      {
+        "Name": "Console",
+        "Args": {
+          //"outputTemplate": "time=\"{Timestamp:yyyy-MM-dd HH:mm:ss}\" level={Level:w3} category={SourceContext} trace={TraceId}{NewLine}msg=\"{Message:lj}\"{NewLine}error=\"{Exception}\"{NewLine}",
+          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level}] {SourceContext} [{TraceId}]{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}",
+          "theme": "Serilog.Sinks.SystemConsole.Themes.ConsoleTheme::None, Serilog.Sinks.Console"
+        }
+      }
+      //{
+      //  "Name": "File",
+      //  "Args": {
+      //    "path": "logs/log-.txt",
+      //    "rollingInterval": "Day"
+      //  }
+      //}
+    ],
+    "Enrich": [ "FromLogContext", "WithSpan" ]
+  },
+  "AllowedHosts": "*",
+  "DeviceConfigs": {
+    "Address": "http://192.168.100.100/xml",
+    "Authorize": true,
+    "ReceiveKey": "E1BBD1BB-A269-44",
+    "SendKey": "2A-BA92-160A3B1D",
+    "Expired": 86400 //认证过期时间(秒)
+  },
+  "ConnectionStrings": {
+    "CallCenter": "server=db.fengwo.com;Database=callcenter;Uid=dev;Pwd=fengwo11!!;SslMode=none;",
+    "Redis": "192.168.100.223:6379"
+  },
+  "Swagger": true,
+  "Cors": {
+    "Origins": [ "http://localhost:8888", "http://callcenter-admin.fengwo.com", "http://admin.call.fengwo.com" ]
+  },
+  "WorkTimeSettings": {
+    "MorningBegin": "08:00",
+    "MorningEnd": "12:00",
+    "AfterBegin": "15:00",
+    "AfterEnd": "21:00",
+    "WorkDay": [ 1, 2, 3, 4, 5, 0, 6 ],
+    "WorkCategory": "08da9b9f-a35d-4ade-8ea7-55e8abbcdefd",
+    "RestCategory": "08daa5f5-ac7a-4ced-8295-1c78baa15f9e"
   }
 }

+ 4 - 0
src/CallCenter.Application/CallCenter.Application.csproj

@@ -6,6 +6,10 @@
     <Nullable>enable</Nullable>
   </PropertyGroup>
 
+  <ItemGroup>
+    <PackageReference Include="Identity.Admin.HttpClient" Version="1.0.0" />
+  </ItemGroup>
+
   <ItemGroup>
     <ProjectReference Include="..\CallCenter.Application.Contracts\CallCenter.Application.Contracts.csproj" />
     <ProjectReference Include="..\CallCenter.CacheManager\CallCenter.CacheManager.csproj" />