/// <summary>
        /// When AccessToken is invalid then refresh new one replace
        /// </summary>
        /// <param name="platformType">Platform Type</param>
        public void RefreshInValidAccessToken(PlatformType platformType)
        {
            AuthorizeConfig   oauthConfig       = GetAuthorizeConfig(platformType);
            DataRequestHelper dataRequestHelper = new DataRequestHelper();
            string            requestUrl        = string.Empty;

            if (platformType == PlatformType.Tencent)
            {
                #region refresh new accesstoke tencent accesstoken
                AccessTokenData     tencentToken        = IsolatedStorageSettings.ApplicationSettings["tencenttoken"] as AccessTokenData;
                TencentSocialHelper tencentSocialHelper = new TencentSocialHelper();
                requestUrl = tencentSocialHelper.GetRefreshAccessTokenUrl(oauthConfig.Url, oauthConfig.AppKey, tencentToken.RefreshToken);

                if (tencentSocialHelper.PostArgumentList != null)
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST, tencentSocialHelper.PostArgumentList);
                }
                else
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST);
                }
                dataRequestHelper.AsyncResponseComplated += (responseData, ex) =>
                {
                    if (!string.IsNullOrEmpty(responseData.ToString()))
                    {
                    }
                };
                #endregion
            }
            else if (platformType == PlatformType.Sina)
            {
            }
        }
        /// <summary>
        /// Get authorize config by platform type
        /// </summary>
        /// <param name="platformType">Soical PlatformType</param>
        /// <returns>Authorize Config Value</returns>
        public AuthorizeConfig GetAuthorizeConfig(PlatformType platformType)
        {
            AuthorizeConfig    authorizeConfig = null;
            StreamResourceInfo configFile      = Application.GetResourceStream(new Uri("/MoCommon;component/Social/SocialConfig.xml", UriKind.RelativeOrAbsolute));
            XDocument          configDoc       = XDocument.Load(configFile.Stream);
            XElement           queryElement    = null;

            #region read config content from xml file
            switch (platformType)
            {
            case PlatformType.Tencent:
                queryElement = configDoc.Elements("social").First().Elements("tencent").First();
                break;

            case PlatformType.Sina:
                queryElement = configDoc.Elements("social").First().Elements("sina").First();
                break;

            case PlatformType.WeChat:
                queryElement = configDoc.Elements("social").First().Elements("wechat").First();
                break;
            }
            authorizeConfig = new AuthorizeConfig()
            {
                PlatformType = platformType,
                AppKey       = queryElement.Attributes().Single(x => x.Name == "appkey").Value,
                AppSecret    = queryElement.Attributes().Single(x => x.Name == "appsecret").Value,
                Url          = queryElement.Attributes().Single(x => x.Name == "url").Value,
                RedirectUrl  = queryElement.Attributes().Single(x => x.Name == "redirecturl").Value,
                ApiUrl       = queryElement.Attributes().Single(x => x.Name == "apiurl").Value,
                OauthApiUrl  = queryElement.Attributes().Single(x => x.Name == "oauthapiurl").Value
            };
            #endregion
            return(authorizeConfig);
        }
Пример #3
0
        /// <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>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api帮助文档 V1");
            });

            #endregion

            #region 实现跨域
            app.UseCors(builder =>
            {
                builder.WithHeaders("*");
                builder.AllowAnyMethod();
                builder.AllowAnyOrigin();
            });
            #endregion

            #region Token验证
            AuthorizeConfig.Instance().ConfigAuth(app);
            #endregion

            #region MVC
            app.UseMvc();
            #endregion
        }
Пример #4
0
        public void Configuration(IAppBuilder app)
        {
            //HttpConfiguration config = new HttpConfiguration();
            //WebApiConfig.Register(config);
            //app.UseWebApi(config);
            //  Auth2Config.OAuth(app);
            //AuthConfig.ClaimsBasedAuth(app);

            AuthorizeConfig.OAuth(app);
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            WebApiConfig.Register(config);
            app.UseWebApi(config);

            //app.UseCookieAuthentication(new CookieAuthenticationOptions

            //{

            //    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

            //    LoginPath = new PathString("/api/Values"),

            //    CookieSecure = CookieSecureOption.Never,
            //    CookieName = "Application"

            //});
        }
        public string GetAuthorizeCode()
        {
            AuthorizeConfig            oauthConfig  = GetAuthorizeConfig(PlatformType.WeChat);
            ShareToWeChatFriendsHelper weChatHelper = new ShareToWeChatFriendsHelper();
            string requestUrl = weChatHelper.GetWeChatOauthUrl(oauthConfig.OauthApiUrl, oauthConfig.AppKey, ResponseType.Code, "http://www.163.com/");

            return(requestUrl);
        }
Пример #6
0
 public async Task <IActionResult> RefreshToken(UserGetAuthToken user)
 {
     return(Ok(new
     {
         status = true,
         message = await AuthorizeConfig.Instance().GenerateTokenAsync(user.Id, user.Account)
     }));
 }
        /// <summary>
        /// Get authorize code by the different platfrom type
        /// </summary>
        /// <param name="platformType">Soical Platform</param>
        /// <param name="responseType">Response Type</param>
        /// <returns>Authorize Code</returns>
        public string GetAuthorizeCode(PlatformType platformType, string responseType)
        {
            AuthorizeConfig oauthConfig = GetAuthorizeConfig(platformType);
            string          requestUrl  = string.Empty;

            if (platformType == PlatformType.Tencent)
            {
                requestUrl = new TencentSocialHelper().GetAuthorizeCodeUrl(oauthConfig.Url, oauthConfig.AppKey, responseType, oauthConfig.RedirectUrl);
            }
            else if (platformType == PlatformType.Sina)
            {
                requestUrl = new SinaSocialHelper().GetAuthorizeCodeUrl(oauthConfig.Url, oauthConfig.AppKey, oauthConfig.RedirectUrl);
            }

            return(requestUrl);
        }
Пример #8
0
        public async Task <IActionResult> GetAuthToken(UserLoginDto LoginDto)
        {
            List <SearchCondition> condition = new List <SearchCondition>();

            condition.Add(new SearchCondition
            {
                Filed     = "Account",
                Value     = LoginDto.Account,
                Operation = CommonEnum.ConditionOperation.Equal
            });
            condition.Add(new SearchCondition
            {
                Filed     = "Password",
                Value     = SecurityHelper.MD5Encrypt32(LoginDto.Password),
                Operation = CommonEnum.ConditionOperation.Equal
            });
            condition.Add(new SearchCondition
            {
                Filed     = "EnabledMark",
                Value     = "1",
                Operation = CommonEnum.ConditionOperation.Equal
            });


            var userlist = await _service.QueryAsync <UserSingleDto>(condition);

            if (userlist == null || userlist.Count == 0)
            {
                return(Ok(new { Status = false, Message = "用户名或密码不正确" }));
            }
            return(Ok(new
            {
                status = true,
                message = await AuthorizeConfig.Instance().GenerateTokenAsync(userlist[0].Id, LoginDto.Account),
                user = userlist[0]
            }));
        }
Пример #9
0
 public ActionPermissionFilter(ILogger <ActionPermissionFilter> logger)
 {
     _logger          = logger ?? throw new ArgumentNullException(nameof(logger));
     _authorizeConfig = EngineContext.Current.GetAppModuleConfig <AuthorizeConfig>();
 }
        /// <summary>
        /// Send TExt Content With Picture to social platform
        /// </summary>
        /// <param name="platformType">platfrom Type</param>
        /// <param name="content">Content TExt</param>
        /// <param name="picFileStream">Upload File Stream</param>
        public void SendTextWithPicContent(PlatformType platformType, string content, Stream picFileStream)
        {
            AuthorizeConfig   authorizeConfig   = GetAuthorizeConfig(platformType);
            DataRequestHelper dataRequestHelper = new DataRequestHelper();
            string            requestUrl        = string.Empty;

            //upload picture as text content
            byte[] picBytes = new byte[picFileStream.Length];
            picFileStream.Seek(0, SeekOrigin.Begin);
            picFileStream.Read(picBytes, 0, picBytes.Length);

            //notice : when you add fileparameter rename filename to api convert
            List <FileParameter> uploadFileList = new List <FileParameter>()
            {
                FileParameter.Create("pic", picBytes, DateTime.Now.ToString("yyyyMMddHHmmss"))
            };

            if (platformType == PlatformType.Tencent)
            {
                #region send text with picture to tencent platform
                AccessTokenData     tokenData           = IsolatedStorageSettings.ApplicationSettings["tencenttoken"] as AccessTokenData;
                TencentSocialHelper tencentSocialHelper = new TencentSocialHelper();
                requestUrl = tencentSocialHelper.GetTextContentWithPicUrl(authorizeConfig.OauthApiUrl, authorizeConfig.AppKey, tokenData.AccessToken, tokenData.OpenId, content, FormatType.Json);

                if (tencentSocialHelper.PostArgumentList != null)
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST, tencentSocialHelper.PostArgumentList, uploadFileList);
                }
                else
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST, null, uploadFileList);
                }
                dataRequestHelper.AsyncResponseComplated += (responseData, ex) =>
                {
                    if (!string.IsNullOrEmpty(responseData.ToString()))
                    {
                        TencentTextResponseData uploadRepData = JsonConvert.DeserializeObject <TencentTextResponseData>(responseData.ToString());
                        if (uploadRepData.ErrCode == "0" && uploadRepData.Msg.Trim().ToLower() == "ok")
                        {
                            //send text with picture success
                            if (AsyncSendPictureComplated != null)
                            {
                                AsyncSendPictureComplated("success", null);
                            }
                        }
                        else
                        {
                            //send text with picture failed
                            if (AsyncSendPictureComplated != null)
                            {
                                AsyncSendPictureComplated("fail", uploadRepData.Msg);
                            }
                        }
                    }
                };
                #endregion
            }
            else if (platformType == PlatformType.Sina)
            {
                #region send text with picture to sina platform
                AccessTokenData  sinaToken        = IsolatedStorageSettings.ApplicationSettings["sinatoken"] as AccessTokenData;
                SinaSocialHelper sinaSocialHelper = new SinaSocialHelper();
                requestUrl = sinaSocialHelper.GetTextContentWithPicUrl(authorizeConfig.OauthApiUrl, sinaToken.AccessToken, content);

                if (sinaSocialHelper.PostArgumentList != null)
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST, sinaSocialHelper.PostArgumentList, uploadFileList);
                }
                else
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST, null, uploadFileList);
                }
                dataRequestHelper.AsyncResponseComplated += (responseData, ex) =>
                {
                    if (!string.IsNullOrEmpty(responseData.ToString()))
                    {
                        SinaTextErrorData    sinaErrorData = JsonConvert.DeserializeObject <SinaTextErrorData>(responseData.ToString());
                        SinaTextResponseData sinaRepData   = JsonConvert.DeserializeObject <SinaTextResponseData>(responseData.ToString());
                        if (sinaErrorData.Error == null && sinaErrorData.Error_Code == null)
                        {
                            //send text with picture success
                            if (AsyncSendPictureComplated != null)
                            {
                                AsyncSendPictureComplated("success", null);
                            }
                        }
                        else
                        {
                            //send text with picture fail
                            if (AsyncSendPictureComplated != null)
                            {
                                AsyncSendPictureComplated("fail", sinaErrorData.Error);
                            }
                        }
                    }
                };
                #endregion
            }
        }
        /// <summary>
        /// Send Pure text content to social platform
        /// </summary>
        /// <param name="platformType">platform type</param>
        /// <param name="content">text content</param>
        public void SendPureTextContent(PlatformType platformType, string content)
        {
            AuthorizeConfig   authorizeConfig   = GetAuthorizeConfig(platformType);
            DataRequestHelper dataRequestHelper = new DataRequestHelper();

            string requestUrl = string.Empty;

            if (platformType == PlatformType.Tencent)
            {
                #region send pure text content to tencent platform
                AccessTokenData     tencentToken        = IsolatedStorageSettings.ApplicationSettings["tencenttoken"] as AccessTokenData;
                TencentSocialHelper tencentSocialHelper = new TencentSocialHelper();
                requestUrl = tencentSocialHelper.GetPureTextContentUrl(authorizeConfig.ApiUrl, authorizeConfig.AppKey, tencentToken.AccessToken, tencentToken.OpenId, content, FormatType.Json);
                if (tencentSocialHelper.PostArgumentList != null)
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST, tencentSocialHelper.PostArgumentList);
                }
                else
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST);
                }

                dataRequestHelper.AsyncResponseComplated += (responseData, ex) => {
                    if (!string.IsNullOrEmpty(responseData.ToString()))
                    {
                        TencentTextResponseData pureRepData = JsonConvert.DeserializeObject <TencentTextResponseData>(responseData.ToString());
                        if (pureRepData.Msg.Trim().ToLower() == "ok" && pureRepData.ErrCode == "0")
                        {
                            //send text content success
                            if (AsyncSendContentComplated != null)
                            {
                                AsyncSendContentComplated("success", null);
                            }
                        }
                        else
                        {
                            //send text content failed
                            if (AsyncSendContentComplated != null)
                            {
                                AsyncSendContentComplated("fail", pureRepData.Msg);
                            }
                        }
                    }
                };
                #endregion
            }
            else if (platformType == PlatformType.Sina)
            {
                #region send pure text content to sina platform
                AccessTokenData  sinaToken        = IsolatedStorageSettings.ApplicationSettings["sinatoken"] as AccessTokenData;
                SinaSocialHelper sinaSocialHelper = new SinaSocialHelper();
                requestUrl = sinaSocialHelper.GetPureTextContentUrl(authorizeConfig.ApiUrl, sinaToken.AccessToken, content);
                if (sinaSocialHelper.PostArgumentList != null)
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST, sinaSocialHelper.PostArgumentList);
                }
                else
                {
                    dataRequestHelper.ExcuteAsyncRequest(requestUrl, Method.POST);
                }

                dataRequestHelper.AsyncResponseComplated += (responseData, ex) => {
                    if (!string.IsNullOrEmpty(responseData.ToString()))
                    {
                        SinaTextErrorData    sinaErrorData    = JsonConvert.DeserializeObject <SinaTextErrorData>(responseData.ToString());
                        SinaTextResponseData sinaResponseData = JsonConvert.DeserializeObject <SinaTextResponseData>(responseData.ToString());
                        if (sinaErrorData.Error == null && sinaErrorData.Error_Code == null)
                        {
                            //send text content success
                            if (AsyncSendContentComplated != null)
                            {
                                AsyncSendContentComplated("success", null);
                            }
                        }
                        else
                        {
                            //send text content failed
                            if (AsyncSendContentComplated != null)
                            {
                                AsyncSendContentComplated("fail", sinaErrorData.Error);
                            }
                        }
                    }
                };
                #endregion
            }
        }
        /// <summary>
        /// Get request access Token by the different platform type
        /// </summary>
        /// <param name="platformType">Social Platform</param>
        /// <param name="grantType">Grant Type</param>
        /// <param name="code">Authorize Code</param>
        public void GetRequestAccessToken(PlatformType platformType, string grantType, string code)
        {
            AuthorizeConfig   oauthConfig       = GetAuthorizeConfig(platformType);
            DataRequestHelper dataReqeustHelper = new DataRequestHelper();

            string requestUrl = string.Empty;

            if (platformType == PlatformType.Tencent)
            {
                #region tencent accesstoken
                TencentSocialHelper tencentSocialHelper = new TencentSocialHelper();
                requestUrl = tencentSocialHelper.GetRequestAccessTokenUrl(oauthConfig.Url, oauthConfig.AppKey, oauthConfig.AppSecret, oauthConfig.RedirectUrl, grantType, code);
                if (tencentSocialHelper.PostArgumentList == null)
                {
                    dataReqeustHelper.ExcuteAsyncRequest(requestUrl, Method.GET);
                }
                else
                {
                    dataReqeustHelper.ExcuteAsyncRequest(requestUrl, Method.GET, tencentSocialHelper.PostArgumentList);
                }

                dataReqeustHelper.AsyncResponseComplated += (content, ex) =>
                {
                    #region get tencent accesstoken and save to local
                    if (!string.IsNullOrEmpty(content.ToString()))
                    {
                        string[]        spileResponseArray = content.ToString().Split(new char[] { '=', '&' });
                        AccessTokenData tencentToken       = new AccessTokenData()
                        {
                            PlatformType = PlatformType.Tencent
                        };
                        for (int count = 0; count < spileResponseArray.Length; count++)
                        {
                            if (spileResponseArray[count] == "access_token")
                            {
                                tencentToken.AccessToken = spileResponseArray[count + 1];
                            }
                            else if (spileResponseArray[count] == "expires_in")
                            {
                                tencentToken.ExpiresIn = Convert.ToInt32(spileResponseArray[count + 1]);
                            }
                            else if (spileResponseArray[count] == "refresh_token")
                            {
                                tencentToken.RefreshToken = spileResponseArray[count + 1];
                            }
                            else if (spileResponseArray[count] == "openid")
                            {
                                tencentToken.OpenId = spileResponseArray[count + 1];
                            }
                        }

                        //save to local
                        tencentToken.CreateDate = DateTime.Now;
                        IsolatedStorageHelper.IsolatedStorageSaveObject("tencenttoken", tencentToken);
                        if (AsyncAuthorizeComplated != null)
                        {
                            AsyncAuthorizeComplated(tencentToken, null);
                        }
                    }
                    #endregion
                };
                #endregion
            }
            else if (platformType == PlatformType.Sina)
            {
                #region sina accesstoken
                SinaSocialHelper sinaSocialHelper = new SinaSocialHelper();
                requestUrl = sinaSocialHelper.GetRequestAccessTokenUrl(oauthConfig.Url, oauthConfig.AppKey, oauthConfig.AppSecret, grantType, code, oauthConfig.RedirectUrl);
                if (sinaSocialHelper.PostArgumentList != null)
                {
                    dataReqeustHelper.ExcuteAsyncRequest(requestUrl, Method.POST, sinaSocialHelper.PostArgumentList);
                }
                else
                {
                    dataReqeustHelper.ExcuteAsyncRequest(requestUrl, Method.POST);
                }

                dataReqeustHelper.AsyncResponseComplated += (content, ex) =>
                {
                    if (!string.IsNullOrEmpty(content.ToString()))
                    {
                        #region spile sina accesstoken data
                        string[]        spiltTokenArray = content.ToString().Split(new char[] { ':', ',', '{', '}' });
                        AccessTokenData sinaTokenData   = new AccessTokenData()
                        {
                            PlatformType = PlatformType.Sina
                        };
                        for (int count = 0; count < spiltTokenArray.Length; count++)
                        {
                            if (spiltTokenArray[count].Contains("access_token"))
                            {
                                sinaTokenData.AccessToken = spiltTokenArray[count + 1].Substring(1, spiltTokenArray[count + 1].Length - 2);
                            }
                            else if (spiltTokenArray[count].Contains("expires_in"))
                            {
                                sinaTokenData.ExpiresIn = Convert.ToInt32(spiltTokenArray[count + 1]);
                            }
                        }

                        //save to local
                        sinaTokenData.CreateDate = DateTime.Now;
                        IsolatedStorageHelper.IsolatedStorageSaveObject("sinatoken", sinaTokenData);
                        if (AsyncAuthorizeComplated != null)
                        {
                            AsyncAuthorizeComplated(sinaTokenData, null);
                        }
                        #endregion
                    }
                };
                #endregion
            }
        }
Пример #13
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); });
            #region 注册验证JWT
            double expTime = 20;
            AuthorizeConfig.Instance(expTime).RegisterAuth(services);
            #endregion

            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version     = "v0.1.0",
                    Title       = "KgmSoft WebAPI",
                    Description = "上海金戈马软件API说明",
                    Contact     = new Swashbuckle.AspNetCore.Swagger.Contact {
                        Name = "上海金戈马软件有限公司", Url = "http://www.kgmsoft.com.cn"
                    }
                });

                #region 加载xml注释
                var xmlPath    = PathUtil.GetAbsolutePath("KGM.Framework.WebApi.xml");      //这个就是刚刚配置的xml文件名
                var dtoXmlPath = PathUtil.GetAbsolutePath("KGM.Framework.Application.xml"); //这个就是刚刚配置的xml文件名
                c.IncludeXmlComments(xmlPath, true);                                        //默认的第二个参数是false,这个是controller的注释,记得修改
                c.IncludeXmlComments(dtoXmlPath);
                #endregion

                #region Token绑定到ConfigureServices
                var security = new Dictionary <string, IEnumerable <string> > {
                    { "上海金戈马软件WebAPI", new string[] { } },
                };
                c.AddSecurityRequirement(security);
                c.AddSecurityDefinition("上海金戈马软件WebAPI", new ApiKeyScheme
                {
                    Description = "请输入token",
                    Name        = "Authorization", //jwt默认的参数名称
                    In          = "header",        //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
                #endregion
            });
            #endregion

            #region 跨域注册
            services.AddCors();
            #endregion

            #region MVC注册
            services.AddMvc(options =>
            {
                options.Filters.Add <HttpGlobalExceptionFilter>();
                options.Filters.Add <HttpGlobalExcuteFilter>();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            #endregion

            #region 注册自动映射
            AutoMapperConfig.RegisterAutoMapper(services);
            #endregion

            #region 注册IoC
            return(IoCContainer.RegisterIoC(services));

            #endregion
        }
Пример #14
0
 public AuthorizeFunction(AuthorizeConfig authorizeConfig)
 {
     _authorizeConfig = authorizeConfig;
 }