Commit 09ef9726 authored by 黄奎's avatar 黄奎

页面修改

parent c873ac83
...@@ -12,18 +12,22 @@ namespace Mall.Common ...@@ -12,18 +12,22 @@ namespace Mall.Common
public class GlobalKey public class GlobalKey
{ {
#region 系统配置 #region 系统配置
/// <summary> /// <summary>
/// 请求异常 /// 请求异常
/// </summary> /// </summary>
public const string Request_Exception = "Request_Exception"; public const string Request_Exception = "Request_Exception";
/// <summary> /// <summary>
/// 当前请求model /// 当前请求model
/// </summary> /// </summary>
public const string Current_Assembly_Model = "Current_Assembly_Model"; public const string Current_Assembly_Model = "Current_Assembly_Model";
/// <summary> /// <summary>
/// 配置文件缓存前缀 /// 配置文件缓存前缀
/// </summary> /// </summary>
public const string ConfigPrefix = "CONFIG_KEY_"; public const string ConfigPrefix = "CONFIG_KEY_";
/// <summary> /// <summary>
/// 当前请求Token携带的UserInfo /// 当前请求Token携带的UserInfo
/// </summary> /// </summary>
......
using JWT; using JWT;
using JWT.Serializers;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Mall.Common; using Mall.Common;
using Mall.Common.API; using Mall.Common.API;
using Mall.Common.Plugin; using Mall.Common.Plugin;
using System; using System;
using System.Collections.Generic;
using System.IO;
using System.Net; using System.Net;
using System.Text;
using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Filters;
using System.Configuration;
using Mall.Common.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.Configuration.Json;
using Mall.CacheManager.User; using Mall.CacheManager.User;
using System.Linq; using System.Linq;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features;
...@@ -29,8 +21,6 @@ namespace Mall.WebApi.Filter ...@@ -29,8 +21,6 @@ namespace Mall.WebApi.Filter
/// </summary> /// </summary>
public class ApiFilterAttribute : ActionFilterAttribute public class ApiFilterAttribute : ActionFilterAttribute
{ {
//private readonly string Key = "_ApiOnActionMonitorLog_";
/// <summary> /// <summary>
/// OnActionExecuting /// OnActionExecuting
/// </summary> /// </summary>
...@@ -63,6 +53,7 @@ namespace Mall.WebApi.Filter ...@@ -63,6 +53,7 @@ namespace Mall.WebApi.Filter
{ {
isCheckToken = false; isCheckToken = false;
} }
#region Token校验 #region Token校验
if (isCheckToken) if (isCheckToken)
{ {
...@@ -165,7 +156,6 @@ namespace Mall.WebApi.Filter ...@@ -165,7 +156,6 @@ namespace Mall.WebApi.Filter
} }
} }
#endregion #endregion
} }
/// <summary> /// <summary>
...@@ -185,33 +175,8 @@ namespace Mall.WebApi.Filter ...@@ -185,33 +175,8 @@ namespace Mall.WebApi.Filter
/// <returns></returns> /// <returns></returns>
private JObject DoApiMonitorLog(ActionExecutingContext actionContext, ref string token) private JObject DoApiMonitorLog(ActionExecutingContext actionContext, ref string token)
{ {
JObject parm = new JObject();
var request = actionContext.HttpContext.Request; var request = actionContext.HttpContext.Request;
#region 如果参数是json实体对象,获取序列化后的数据 JObject parm = Helper.ApiTokenHelper.GetRequestParameters(request, ref token);
request.EnableBuffering();
string responseData = "";
using (var reader = new StreamReader(request.Body, encoding: Encoding.UTF8))
{
var body = reader.ReadToEndAsync();
// Do some processing with body…
// Reset the request body stream position so the next middleware can read it
responseData = body.Result;
request.Body.Position = 0;
}
if (!string.IsNullOrWhiteSpace(responseData.Trim()))
{
try
{
parm = JObject.Parse(responseData);
actionContext.HttpContext.Items[GlobalKey.UserPostInfo] = responseData;
}
catch (Exception ex)
{
LogHelper.Write(ex, string.Format("DoApiMonitorLog:{0}", responseData));
}
token = JsonHelper.GetStringValue(parm, "token");
}
#endregion
return parm; return parm;
} }
...@@ -222,36 +187,13 @@ namespace Mall.WebApi.Filter ...@@ -222,36 +187,13 @@ namespace Mall.WebApi.Filter
/// <param name="token"></param> /// <param name="token"></param>
private static void JWTValidat(ActionExecutingContext actionContext, string token) private static void JWTValidat(ActionExecutingContext actionContext, string token)
{ {
//解析token,校验是否失效
if (!string.IsNullOrEmpty(token)) if (!string.IsNullOrEmpty(token))
{ {
//解析token,校验是否失效
try try
{ {
IJsonSerializer serializer = new JsonNetSerializer(); var userInfo= Helper.ApiTokenHelper.ParsingToken(token);
IDateTimeProvider provider = new UtcDateTimeProvider(); actionContext.HttpContext.Items[GlobalKey.TokenUserInfo] = JObject.Parse(Common.Plugin.JsonHelper.Serialize(userInfo));
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
string secret = Config.JwtSecretKey;
var json = decoder.Decode(token, secret, verify: true);//token为之前生成的字符串
JObject jwtJson = JObject.Parse(json);
actionContext.HttpContext.Items[GlobalKey.TokenUserInfo] = jwtJson["mall_userInfo"];
//TokenUserInfo userInfo = JsonConvert.DeserializeObject<TokenUserInfo>(muserInfo.ToString());
//if (userInfo != null && userInfo.requestFrom == Common.Enum.ApiRequestFromEnum.MiniProgram)
//{
// //查询是否是黑名单
// AppletUserInfo uInfo = UserReidsCache.GetAppletUserBlacklistInfo(userInfo.uid);
// if ((uInfo?.Blacklist ?? 0) == 1)
// {
// actionContext.Result = new Microsoft.AspNetCore.Mvc.JsonResult(
// new ApiResult
// {
// resultCode = (int)ResultCode.TokenIllegal,
// message = "已进入黑名单,无法访问",
// data = null
// });
// }
//}
} }
catch (SignatureVerificationException sve) catch (SignatureVerificationException sve)
{ {
......
...@@ -3,11 +3,12 @@ using JWT.Algorithms; ...@@ -3,11 +3,12 @@ using JWT.Algorithms;
using JWT.Serializers; using JWT.Serializers;
using Mall.Common.API; using Mall.Common.API;
using Mall.Common.Plugin; using Mall.Common.Plugin;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.IO;
using System.Threading.Tasks; using System.Text;
namespace Mall.WebApi.Helper namespace Mall.WebApi.Helper
{ {
...@@ -37,8 +38,7 @@ namespace Mall.WebApi.Helper ...@@ -37,8 +38,7 @@ namespace Mall.WebApi.Helper
IJsonSerializer serializer = new JsonNetSerializer(); IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
string secret = Common.Config.JwtSecretKey; string token = encoder.Encode(payload, Common.Config.JwtSecretKey);
string token = encoder.Encode(payload, secret);
return token; return token;
} }
...@@ -50,15 +50,15 @@ namespace Mall.WebApi.Helper ...@@ -50,15 +50,15 @@ namespace Mall.WebApi.Helper
public static TokenUserInfo ParsingToken(string token) public static TokenUserInfo ParsingToken(string token)
{ {
TokenUserInfo tokenUser = new TokenUserInfo(); TokenUserInfo tokenUser = new TokenUserInfo();
if (string.IsNullOrEmpty(token)) if (!string.IsNullOrEmpty(token))
{ {
IJsonSerializer serializer = new JsonNetSerializer(); IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider(); IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider); IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
string secret = Common.Config.JwtSecretKey; //token为之前生成的字符串
var json = decoder.Decode(token, secret, verify: true);//token为之前生成的字符串 var json = decoder.Decode(token, Common.Config.JwtSecretKey, verify: true);
if (!string.IsNullOrEmpty(json)) if (!string.IsNullOrEmpty(json))
{ {
JObject jwtJson = JObject.Parse(json); JObject jwtJson = JObject.Parse(json);
...@@ -69,5 +69,46 @@ namespace Mall.WebApi.Helper ...@@ -69,5 +69,46 @@ namespace Mall.WebApi.Helper
} }
return tokenUser; return tokenUser;
} }
/// <summary>
/// 解析Request参数
/// </summary>
/// <param name="request"></param>
/// <param name="token"></param>
/// <returns></returns>
public static JObject GetRequestParameters(HttpRequest request, ref string token)
{
JObject parm = new JObject();
//如果参数是json实体对象,获取序列化后的数据
request.EnableBuffering();
string responseData = "";
try
{
using (var reader = new StreamReader(request.Body, encoding: Encoding.UTF8))
{
var body = reader.ReadToEndAsync();
responseData = body.Result;
request.Body.Position = 0;
}
}
catch (Exception ex)
{
Common.Plugin.LogHelper.Write(ex, "GetRequestParameters");
}
if (!string.IsNullOrWhiteSpace(responseData.Trim()))
{
try
{
parm = JObject.Parse(responseData);
request.HttpContext.Items[Common.GlobalKey.UserPostInfo] = responseData;
}
catch (Exception ex)
{
LogHelper.Write(ex, string.Format("DoApiMonitorLog:{0}", responseData));
}
token = JsonHelper.GetStringValue(parm, "token");
}
return parm;
}
} }
} }
...@@ -3,33 +3,22 @@ using System.Collections.Generic; ...@@ -3,33 +3,22 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Text;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Text.Unicode; using System.Text.Unicode;
using System.Threading.Tasks; using System.Threading.Tasks;
using Dnc.Api.Throttle; using Dnc.Api.Throttle;
using JWT;
using JWT.Serializers;
using Mall.CacheManager.User; using Mall.CacheManager.User;
using Mall.Common.Plugin;
using Mall.Module.Education; using Mall.Module.Education;
using Mall.Module.User;
using Mall.ThirdCore.Message; using Mall.ThirdCore.Message;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using Senparc.CO2NET; using Senparc.CO2NET;
using Senparc.CO2NET.HttpUtility;
using Senparc.CO2NET.RegisterServices; using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin; using Senparc.Weixin;
using Senparc.Weixin.Entities; using Senparc.Weixin.Entities;
...@@ -46,17 +35,12 @@ namespace Mall.WebApi ...@@ -46,17 +35,12 @@ namespace Mall.WebApi
public IConfiguration Configuration { get; } public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. /// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
//services.AddHttpClient("elite-wechat").ConfigurePrimaryHttpMessageHandler(() =>
//{
// var httpClientHandler = HttpClientHelper.GetHttpClientHandler(null, RequestUtility.SenparcHttpClientWebProxy, System.Net.DecompressionMethods.GZip);
// httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errir) => true;
// return httpClientHandler;
//});
services.Configure<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>(x => x.AllowSynchronousIO = true) services.Configure<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>(x => x.AllowSynchronousIO = true)
.Configure<IISServerOptions>(x => x.AllowSynchronousIO = true); .Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);
services.AddControllers(); services.AddControllers();
...@@ -72,10 +56,10 @@ namespace Mall.WebApi ...@@ -72,10 +56,10 @@ namespace Mall.WebApi
List<string> corsArray = new List<string>() List<string> corsArray = new List<string>()
{ {
"http://localhost:8081", "http://localhost:8081",
"http://localhost:8181", "http://localhost:8181",
"http://localhost:8080", "http://localhost:8080",
"http://localhost:8082", "http://localhost:8082",
"http://localhost:8083", "http://localhost:8083",
"http://127.0.0.1:50512", "http://127.0.0.1:50512",
"http://127.0.0.1:20224", "http://127.0.0.1:20224",
"http://127.0.0.1:28221", "http://127.0.0.1:28221",
...@@ -96,28 +80,10 @@ namespace Mall.WebApi ...@@ -96,28 +80,10 @@ namespace Mall.WebApi
| Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto; | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto;
options.KnownProxies.Add(IPAddress.Parse("47.96.12.235")); options.KnownProxies.Add(IPAddress.Parse("47.96.12.235"));
}); });
//services.AddCap(x =>
//{
// x.UseMongoDB(Common.Config.Mongo);
// x.UseRabbitMQ(cfg =>
// {
// cfg.HostName = Common.Config.ReadConfigKey("RabbitMqConfig", "HostName");
// cfg.VirtualHost = Common.Config.ReadConfigKey("RabbitMqConfig", "VirtualHost");
// cfg.Port = Convert.ToInt32(Common.Config.ReadConfigKey("RabbitMqConfig", "Port"));
// cfg.UserName = Common.Config.ReadConfigKey("RabbitMqConfig", "UserName");
// cfg.Password = Common.Config.ReadConfigKey("RabbitMqConfig", "Password");
// });
// //失败后的重试次数,默认50次;在FailedRetryInterval默认60秒的情况下,即默认重试50*60秒(50分钟)之后放弃失败重试
// x.FailedRetryCount = 10;
// //失败后的重拾间隔,默认60秒
// x.FailedRetryInterval = 10;
// //设置成功信息的删除时间默认24*3600秒
// x.SucceedMessageExpiredAfter = 3600;
//});
//Api限流 //Api限流
services.AddApiThrottle(options => { services.AddApiThrottle(options => {
//配置redis //配置redis
//如果Cache和Storage使用同一个redis,则可以按如下配置
options.UseRedisCacheAndStorage(opts => { options.UseRedisCacheAndStorage(opts => {
opts.ConnectionString = "47.96.23.199,password=Viitto2018,connectTimeout=5000,allowAdmin=false,defaultDatabase=0"; opts.ConnectionString = "47.96.23.199,password=Viitto2018,connectTimeout=5000,allowAdmin=false,defaultDatabase=0";
opts.KeyPrefix = "apithrottle"; //指定给所有key加上前缀,默认为apithrottle opts.KeyPrefix = "apithrottle"; //指定给所有key加上前缀,默认为apithrottle
...@@ -131,101 +97,70 @@ namespace Mall.WebApi ...@@ -131,101 +97,70 @@ namespace Mall.WebApi
}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddApiThrottle(options => services.AddApiThrottle(options =>
{
options.Global.AddValves(
new BlackListValve
{
Policy = Policy.Ip,
Priority = 99
},
new WhiteListValve
{
Policy = Policy.UserIdentity,
Priority = 88
},
new BlackListValve
{
Policy = Policy.Header,
PolicyKey = "throttle",
}
);
options.OnIpAddress = (context) =>
{ {
options.Global.AddValves( string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
new BlackListValve if (string.IsNullOrEmpty(ip))
{
Policy = Policy.Ip,
Priority = 99
},
new WhiteListValve
{
Policy = Policy.UserIdentity,
Priority = 88
},
new BlackListValve
{
Policy = Policy.Header,
PolicyKey = "throttle",
}
);
options.OnIpAddress = (context) =>
{ {
string ip = ""; ip = context.Connection.RemoteIpAddress.ToString();
ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); }
if (string.IsNullOrEmpty(ip)) return ip;
{ };
ip = context.Connection.RemoteIpAddress.ToString(); //options.onIntercepted = (context, value, where) =>
} //{
Common.Plugin.LogHelper.Write("ConfigureServices_ip_【" + ip + "】"); // var request = context.Request;
return ip; // string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
}; // if (string.IsNullOrEmpty(ip))
//options.onIntercepted = (context, value, where) => // {
// { // ip = context.Connection.RemoteIpAddress.ToString();
// Object parm = new JObject(); // }
// var request = context.Request; // Common.BackListHelper.Add(ip);
// request.EnableBuffering(); // string uToken = "";
// string responseData = ""; // var parm = Helper.ApiTokenHelper.GetRequestParameters(request, ref uToken);
// using (var reader = new StreamReader(request.Body, encoding: Encoding.UTF8)) // if (!string.IsNullOrEmpty(uToken))
// { // {
// var body = reader.ReadToEndAsync(); // var userInfo = Helper.ApiTokenHelper.ParsingToken(uToken);
// // Do some processing with body… // if (userInfo != null && !string.IsNullOrEmpty(userInfo.uid))
// // Reset the request body stream position so the next middleware can read it // {
// responseData = body.Result; // Int32.TryParse(userInfo.uid, out int NewUserId);
// request.Body.Position = 0; // if (userInfo.requestFrom == Common.Enum.ApiRequestFromEnum.MiniProgram && NewUserId>0)
// } // {
// string ip = ""; // UserReidsCache.Delete(userInfo.uid);
// ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); // new EducationModule().UpdateUserBlacklist(NewUserId);
// if (string.IsNullOrEmpty(ip)) // }
// { // }
// ip = context.Connection.RemoteIpAddress.ToString(); // }
// } // return new ApiThrottleResult() { Content = "访问过于频繁!" };
// Common.BackListHelper.Add(ip); //};
// Common.Plugin.LogHelper.Write("ConfigureServices_ip2222_【" + ip + "】"); });
// if (!string.IsNullOrWhiteSpace(responseData.Trim()))
// {
// try
// {
// var jsonParm = JObject.Parse(responseData);
// var token = jsonParm.GetStringValue("token");
// if (!string.IsNullOrWhiteSpace(token))
// {
// IJsonSerializer serializer = new JsonNetSerializer();
// IDateTimeProvider provider = new UtcDateTimeProvider();
// IJwtValidator validator = new JwtValidator(serializer, provider);
// IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
// IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
// string secret = Common.Config.JwtSecretKey;
// var json = decoder.Decode(token, secret, verify: true);//token为之前生成的字符串
// JObject jwtJson = JObject.Parse(json);
// var mall_userInfo = JObject.Parse(jwtJson.GetStringValue("mall_userInfo"));
// var requestFrom = mall_userInfo.GetInt("requestFrom");
// var uid = mall_userInfo.GetInt("uid");
// if (requestFrom == 2 && uid > 0)
// {
// UserReidsCache.Delete(uid.ToString());
// new EducationModule().UpdateUserBlacklist(uid);
// }
// }
// }
// catch (Exception ex)
// {
// }
// }
// return new ApiThrottleResult() { Content = "访问过于频繁!" };
// };
});
} }
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// <param name="appLifetime"></param>
/// <param name="senparcSetting"></param>
/// <param name="senparcWeixinSetting"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, IOptions<SenparcSetting> senparcSetting, IOptions<SenparcWeixinSetting> senparcWeixinSetting) public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, IOptions<SenparcSetting> senparcSetting, IOptions<SenparcWeixinSetting> senparcWeixinSetting)
{ {
app.UseForwardedHeaders(); app.UseForwardedHeaders();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment