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

页面修改

parent c873ac83
......@@ -12,18 +12,22 @@ namespace Mall.Common
public class GlobalKey
{
#region 系统配置
/// <summary>
/// 请求异常
/// </summary>
public const string Request_Exception = "Request_Exception";
/// <summary>
/// 当前请求model
/// </summary>
public const string Current_Assembly_Model = "Current_Assembly_Model";
/// <summary>
/// 配置文件缓存前缀
/// </summary>
public const string ConfigPrefix = "CONFIG_KEY_";
/// <summary>
/// 当前请求Token携带的UserInfo
/// </summary>
......
using JWT;
using JWT.Serializers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Configuration;
using Mall.Common.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Mall.CacheManager.User;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Features;
......@@ -29,8 +21,6 @@ namespace Mall.WebApi.Filter
/// </summary>
public class ApiFilterAttribute : ActionFilterAttribute
{
//private readonly string Key = "_ApiOnActionMonitorLog_";
/// <summary>
/// OnActionExecuting
/// </summary>
......@@ -63,6 +53,7 @@ namespace Mall.WebApi.Filter
{
isCheckToken = false;
}
#region Token校验
if (isCheckToken)
{
......@@ -165,7 +156,6 @@ namespace Mall.WebApi.Filter
}
}
#endregion
}
/// <summary>
......@@ -185,33 +175,8 @@ namespace Mall.WebApi.Filter
/// <returns></returns>
private JObject DoApiMonitorLog(ActionExecutingContext actionContext, ref string token)
{
JObject parm = new JObject();
var request = actionContext.HttpContext.Request;
#region 如果参数是json实体对象,获取序列化后的数据
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
JObject parm = Helper.ApiTokenHelper.GetRequestParameters(request, ref token);
return parm;
}
......@@ -222,36 +187,13 @@ namespace Mall.WebApi.Filter
/// <param name="token"></param>
private static void JWTValidat(ActionExecutingContext actionContext, string token)
{
//解析token,校验是否失效
if (!string.IsNullOrEmpty(token))
{
//解析token,校验是否失效
try
{
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 = 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
// });
// }
//}
var userInfo= Helper.ApiTokenHelper.ParsingToken(token);
actionContext.HttpContext.Items[GlobalKey.TokenUserInfo] = JObject.Parse(Common.Plugin.JsonHelper.Serialize(userInfo));
}
catch (SignatureVerificationException sve)
{
......
......@@ -3,11 +3,12 @@ using JWT.Algorithms;
using JWT.Serializers;
using Mall.Common.API;
using Mall.Common.Plugin;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Text;
namespace Mall.WebApi.Helper
{
......@@ -37,8 +38,7 @@ namespace Mall.WebApi.Helper
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
string secret = Common.Config.JwtSecretKey;
string token = encoder.Encode(payload, secret);
string token = encoder.Encode(payload, Common.Config.JwtSecretKey);
return token;
}
......@@ -50,15 +50,15 @@ namespace Mall.WebApi.Helper
public static TokenUserInfo ParsingToken(string token)
{
TokenUserInfo tokenUser = new TokenUserInfo();
if (string.IsNullOrEmpty(token))
if (!string.IsNullOrEmpty(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为之前生成的字符串
//token为之前生成的字符串
var json = decoder.Decode(token, Common.Config.JwtSecretKey, verify: true);
if (!string.IsNullOrEmpty(json))
{
JObject jwtJson = JObject.Parse(json);
......@@ -69,5 +69,46 @@ namespace Mall.WebApi.Helper
}
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;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Dnc.Api.Throttle;
using JWT;
using JWT.Serializers;
using Mall.CacheManager.User;
using Mall.Common.Plugin;
using Mall.Module.Education;
using Mall.Module.User;
using Mall.ThirdCore.Message;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using Senparc.CO2NET;
using Senparc.CO2NET.HttpUtility;
using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
......@@ -46,17 +35,12 @@ namespace Mall.WebApi
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)
{
//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)
.Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);
services.AddControllers();
......@@ -72,10 +56,10 @@ namespace Mall.WebApi
List<string> corsArray = new List<string>()
{
"http://localhost:8081",
"http://localhost:8181",
"http://localhost:8181",
"http://localhost:8080",
"http://localhost:8082",
"http://localhost:8083",
"http://localhost:8083",
"http://127.0.0.1:50512",
"http://127.0.0.1:20224",
"http://127.0.0.1:28221",
......@@ -96,28 +80,10 @@ namespace Mall.WebApi
| Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto;
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限流
services.AddApiThrottle(options => {
//配置redis
//如果Cache和Storage使用同一个redis,则可以按如下配置
options.UseRedisCacheAndStorage(opts => {
opts.ConnectionString = "47.96.23.199,password=Viitto2018,connectTimeout=5000,allowAdmin=false,defaultDatabase=0";
opts.KeyPrefix = "apithrottle"; //指定给所有key加上前缀,默认为apithrottle
......@@ -131,101 +97,70 @@ namespace Mall.WebApi
}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
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(
new BlackListValve
{
Policy = Policy.Ip,
Priority = 99
},
new WhiteListValve
{
Policy = Policy.UserIdentity,
Priority = 88
},
new BlackListValve
{
Policy = Policy.Header,
PolicyKey = "throttle",
}
);
options.OnIpAddress = (context) =>
string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(ip))
{
string ip = "";
ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(ip))
{
ip = context.Connection.RemoteIpAddress.ToString();
}
Common.Plugin.LogHelper.Write("ConfigureServices_ip_【" + ip + "】");
return ip;
};
//options.onIntercepted = (context, value, where) =>
// {
// Object parm = new JObject();
// var request = context.Request;
// 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;
// }
// string ip = "";
// ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
// if (string.IsNullOrEmpty(ip))
// {
// ip = context.Connection.RemoteIpAddress.ToString();
// }
// 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 = "访问过于频繁!" };
// };
});
ip = context.Connection.RemoteIpAddress.ToString();
}
return ip;
};
//options.onIntercepted = (context, value, where) =>
//{
// var request = context.Request;
// string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
// if (string.IsNullOrEmpty(ip))
// {
// ip = context.Connection.RemoteIpAddress.ToString();
// }
// Common.BackListHelper.Add(ip);
// string uToken = "";
// var parm = Helper.ApiTokenHelper.GetRequestParameters(request, ref uToken);
// if (!string.IsNullOrEmpty(uToken))
// {
// var userInfo = Helper.ApiTokenHelper.ParsingToken(uToken);
// if (userInfo != null && !string.IsNullOrEmpty(userInfo.uid))
// {
// Int32.TryParse(userInfo.uid, out int NewUserId);
// if (userInfo.requestFrom == Common.Enum.ApiRequestFromEnum.MiniProgram && NewUserId>0)
// {
// UserReidsCache.Delete(userInfo.uid);
// new EducationModule().UpdateUserBlacklist(NewUserId);
// }
// }
// }
// return new ApiThrottleResult() { Content = "访问过于频繁!" };
//};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// <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>
/// <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)
{
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