예제 #1
0
        public static AuthenticationBuilder AddJWTAuth(this IServiceCollection services, IConfiguration config)
        {
            services.Configure <JWTConfig>(config.GetSection("JWT"));
            services.AddSingleton <IToken, TokenHelper>();
            return(services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                   .AddJwtBearer(o =>
            {
                //自定义jwt验证事件
                o.Events = new JwtBearerEvents()
                {
                    //接收token之前,把token解密成jwt
                    OnMessageReceived = context =>
                    {
                        string authorization = context.Request.Headers["Authorization"];
                        if (!string.IsNullOrWhiteSpace(authorization))
                        {
                            if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                            {
                                context.Token = AES.AesDecrypt(authorization.Substring("Bearer ".Length).Trim());
                            }
                        }
                        return Task.CompletedTask;
                    }
                };
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name,
                    RoleClaimType = JwtClaimTypes.Role,
                    //5分钟偏移量,缓冲时间
                    ClockSkew = TimeSpan.FromMinutes(5),
                    ValidIssuer = config["JWT:Issuer"],
                    ValidAudience = config["JWT:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config["JWT:IssuerSigningKey"]))

                                       /***********************************TokenValidationParameters的参数默认值***********************************/
                                       // RequireSignedTokens = true,
                                       // SaveSigninToken = false,
                                       // ValidateActor = false,
                                       // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                                       // ValidateAudience = true,
                                       // ValidateIssuer = true,
                                       // ValidateIssuerSigningKey = false,
                                       // 是否要求Token的Claims中必须包含Expires
                                       // RequireExpirationTime = true,
                                       // 允许的服务器时间偏移量
                                       // ClockSkew = TimeSpan.FromSeconds(300),
                                       // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                                       // ValidateLifetime = true
                };
            }));
        }
예제 #2
0
        public string RefreshToken(string token)
        {
            token = AES.AesDecrypt(token.Trim());
            var claimsPrincipal = GetPrincipalFromRefreshToken(token);

            if (claimsPrincipal == null)
            {
                return("Refresh token validation failed.");
            }
            return(CreateAccessOrRefreshToken(claimsPrincipal.Identities.First().Claims.Where(o => !Except.Contains(o.Type)), TokenType.AccessToken));
        }
예제 #3
0
 public static int ReceiveFrom(Socket socket_, byte[] data_,  ref EndPoint remoteEp_)
 {
     if (_encrypt)
     {
         int n = socket_.ReceiveFrom(data_, ref remoteEp_);
         var decrypted = AES.AesDecrypt(data_, n);
         Array.Copy(decrypted, data_, decrypted.Length);
         return decrypted.Length;
     }
     else
     {
         return socket_.ReceiveFrom(data_, ref remoteEp_);
     }
 }
        public IActionResult Unifiedorder(UnidiedorderData udata)
        {
            using (_dbContext)
            {
                var response = ResponseModelFactory.CreateResultInstance;

                var stu = _dbContext.StudentBill.FirstOrDefault(x => x.StudentBillUuid == udata.BillGuid);


                if (stu == null)
                {
                    response.SetFailed("未查找到对应缴费信息");
                    return(Ok(response));
                }
                if (stu.OrderMoney >= stu.AmountPayable)
                {
                    response.SetFailed("已缴费");
                    return(Ok(response));
                }

                //时间戳
                string timeStamp = TenPayV3Util.GetTimestamp();
                //随机字符串
                string nonceStr = TenPayV3Util.GetNoncestr();
                string appid    = "wx0bf342f51437ca67";

                //获取学校绑定商户信息
                var school = _dbContext.School.FirstOrDefault(x => x.SchoolUuid == udata.Guid);
                if (school == null)
                {
                    response.SetFailed("未查找到对应学校");
                    return(Ok(response));
                }
                if (school.Yard == null || school.Secretkey == null)
                {
                    response.SetFailed("未查找到对应学校商户信息");
                    return(Ok(response));
                }


                //商户号
                string mch_id = school.Yard;                                                 //"1600884893";
                //商户支付秘钥
                string partnerKey = AES.AesDecrypt(school.Secretkey, HaiKan3.Utils.AES.Key); //"ew6QCdWiDfcif902EbC07dh0icTuM5le";
                //签名
                string sign      = "";
                string sign_type = "MD5";

                //商品描述
                string body = udata.Body;
                //商户订单号
                string out_trade_no = "";
                //标价金额(单位:分)
                int total_fee = udata.Totalfee;
                //终端IP
                //string spbill_create_ip = "183.158.56.51"; //Request.HttpContext.Connection.RemoteIpAddress.ToString();
                string spbill_create_ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                _logger.LogInformation("ip:" + spbill_create_ip);
                //通知地址
                string notify_url = "http://msz-b.jiulong.yoruan.com/test/PayCallBack";
                //string notify_url = "http://msz-b.jiulong.yoruan.com/api/v1/student/StudentBill/PayCallBack";
                //交易类型
                string trade_type = "JSAPI";
                //预支付id
                string prepayId = "";
                //微信调用支付的签名
                string paySign = "";
                //用户openid
                string     openid = udata.Openid;
                Store_Info info   = new Store_Info()
                {
                    address   = "xxxxxx",
                    area_code = "330185",
                    id        = "MSZzf" + appid,
                    name      = "码上知支付商城",
                };
                TenPayV3UnifiedorderRequestData_SceneInfo sceneInfo = new TenPayV3UnifiedorderRequestData_SceneInfo(false);
                sceneInfo.store_info = info;

                //生成订单号
                out_trade_no = DateTime.Now.ToString("yyyyMMddHHmmss") + TenPayV3Util.BuildRandomStr(14);
                _logger.LogInformation("订单号:" + out_trade_no);


                TenPayV3UnifiedorderRequestData requestData = new TenPayV3UnifiedorderRequestData(appid, mch_id, body, out_trade_no, total_fee, spbill_create_ip, notify_url, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openid, partnerKey, nonceStr, null, DateTime.Now, DateTime.Now.AddHours(2), null, null, "CNY", null, null, false, sceneInfo, null);

                var urlFormat = ReurnPayApiUrl("https://api.mch.weixin.qq.com/{0}pay/unifiedorder");
                var data      = requestData.PackageRequestHandler.ParseXML();//获取XML
                _logger.LogInformation("xml:" + data);
                var str = PostXmlMethod.PostXmla(urlFormat, data);
                _logger.LogInformation("postxml:" + str);

                DataSet       ds     = new DataSet();
                StringReader  stream = new StringReader(str);     //读取字符串为数据量
                XmlTextReader reader = new XmlTextReader(stream); //对XML的数据流的只进只读访问
                ds.ReadXml(reader);                               //把数据读入DataSet

                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["return_code"].ToString() == "SUCCESS")
                    {
                        _logger.LogInformation("成功");
                        _logger.LogInformation("timeStamp:" + timeStamp + "; nonceStr:" + nonceStr + "; prepayId:" + ds.Tables[0].Rows[0]["prepay_id"].ToString() + "; paySign:" + ds.Tables[0].Rows[0]["sign"].ToString() + "; partnerKey:" + partnerKey);
                        response.SetData(new { appid = ds.Tables[0].Rows[0]["appid"].ToString(), timeStamp, nonceStr, prepayId = ds.Tables[0].Rows[0]["prepay_id"].ToString(), sign_type, paySign = ds.Tables[0].Rows[0]["sign"].ToString(), sjcode = Electroniccode.getString(32), key = partnerKey, outtradeno = out_trade_no });
                        BillState bill = new BillState()
                        {
                            BillUuid  = Guid.NewGuid(),
                            BillNum   = out_trade_no,
                            Appid     = appid,
                            MchId     = mch_id,
                            Money     = total_fee,
                            Key       = partnerKey,
                            SbillUuid = udata.BillGuid,
                        };
                        _logger.LogInformation("订单记录:" + JsonConvert.SerializeObject(bill));
                        _dbContext.BillState.Add(bill);
                        _dbContext.SaveChanges();
                        return(Ok(response));
                    }
                    else
                    {
                        response.SetFailed(ds.Tables[0].Rows[0]["return_msg"].ToString());
                        _logger.LogInformation("异常");
                        _logger.LogInformation(ds.Tables[0].Rows[0]["return_msg"].ToString());
                        return(Ok(response));
                    }
                }
                else
                {
                    response.SetFailed("订单信息为空");
                    return(Ok(response));
                }
            }
        }