예제 #1
0
        /// <summary>
        /// This contructor does application authentication and setups up the necessary timers to keep the app auth ticket valid.
        /// </summary>
        /// <param name="appId">The application version's app id</param>
        /// <param name="sharedSecret">The application version's shared secret</param>
        /// <param name="baseAppAuthUrl">The base URL of the Mozu application authentication service</param>
        private AppAuthenticator(AppAuthInfo appAuthInfo, string baseAppAuthUrl, RefreshInterval refreshInterval = null)
        {
            BaseUrl          = baseAppAuthUrl;
            _appAuthInfo     = appAuthInfo;
            _refreshInterval = refreshInterval;

            MozuConfig.SharedSecret  = appAuthInfo.SharedSecret;
            MozuConfig.ApplicationId = appAuthInfo.ApplicationId;
        }
예제 #2
0
        public static async Task <AppAuthenticator> InitializeAsync(AppAuthInfo appAuthInfo, RefreshInterval refreshInterval = null)
        {
            var baseAppAuthUrl = MozuConfig.BaseAppAuthUrl;

            if (appAuthInfo == null || string.IsNullOrEmpty(baseAppAuthUrl))
            {
                throw new Exception("AppAuthInfo or Base App auth Url cannot be null or empty");
            }

            if (String.IsNullOrEmpty(appAuthInfo.ApplicationId) || String.IsNullOrEmpty(appAuthInfo.SharedSecret))
            {
                throw new Exception("ApplicationId or Shared Secret is missing");
            }

            if (_auth != null && _auth.AppAuthInfo.ApplicationId == appAuthInfo.ApplicationId)
            {
                return(_auth);
            }
            try
            {
                await _semaphoreWaiter.WaitAsync();

                // Double check to make sure that someone else didn't already initialize it while we were waiting
                if (_auth == null || (_auth != null && _auth.AppAuthInfo.ApplicationId != appAuthInfo.ApplicationId))
                {
                    try
                    {
                        _log.Info("Initializing App");
                        var uri = new Uri(baseAppAuthUrl);
                        HttpHelper.UrlScheme = uri.Scheme;
                        var tmp = new AppAuthenticator(appAuthInfo, baseAppAuthUrl, refreshInterval);
                        await tmp.AuthenticateAppAsync();

                        lock (_lockObj)
                        {
                            _auth = tmp;
                        }
                    }
                    finally
                    {
                        _semaphoreWaiter.Release();
                    }
                    _log.Info("Initializing App..Done");
                }
            }
            catch (ApiException exc)
            {
                _log.Error(exc.Message, exc);
                lock (_lockObj)
                {
                    _auth = null;
                }
                throw exc;
            }

            return(_auth);
        }
예제 #3
0
        private async void btnAuthenticate_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtApplicationID.Text.Length > 20 &&
                    txtSharedSecret.Text.Length > 20)
                {
                    btnAuthenticate.Text = "Authenticating...";
                    var appAuthInfo = new AppAuthInfo
                    {
                        ApplicationId = txtApplicationID.Text,
                        SharedSecret  = txtSharedSecret.Text
                    };
                    if (txtEmail.Text.Contains("@") &&
                        txtEmail.Text.Contains(".") &&
                        txtPassword.Text.Length > 5)
                    {
                        await AppAuthenticator.InitializeAsync(appAuthInfo);

                        btnAuthenticate.Text = "Loading Scopes...";
                        panelAPI.Visible     = true;
                        panelTenant.Visible  = true;
                        var userAuthInfo = new UserAuthInfo {
                            EmailAddress = txtEmail.Text, Password = txtPassword.Text
                        };
                        _userInfo = await UserAuthenticator.AuthenticateAsync(userAuthInfo, AuthenticationScope.Tenant);

                        panelTenant.Visible = true;
                        _userInfo.AuthorizedScopes.Insert(0, new Scope {
                            Id = -1, Name = "[Select Tenant]"
                        });
                        cbTenant.DataSource = _userInfo.AuthorizedScopes;

                        btnAuthenticate.Text = "Renew Authentication";
                    }
                    else
                    {
                        btnAuthenticate.Text = "Authenticate";
                        LogError(new Exception("Not enough User data entered for User Scope Authentication"));
                    }
                }
                else
                {
                    LogError(new Exception("Not enough Application data entered for Authentication"));
                }
            }
            catch (ApiException exc)
            {
                LogError(exc);
                btnAuthenticate.Text = "Authenticate";
            }
        }
예제 #4
0
        public static void AuthApp(string mozuApplicationId, string mozuApplicationSecret)
        {
            MozuApplicationId              = mozuApplicationId;
            MozuApplicationSecret          = mozuApplicationSecret;
            MozuConfig.ThrowExceptionOn404 = true;

            // auth with mozu
            _mozuAppAuthInfo = new AppAuthInfo()
            {
                ApplicationId = MozuApplicationId,
                SharedSecret  = MozuApplicationSecret
            };
            AppAuthenticator.Initialize(_mozuAppAuthInfo);
            isAuthed = true;
        }
예제 #5
0
        public static async Task <AppAuthenticator> InitializeAsync(AppAuthInfo appAuthInfo, RefreshInterval refreshInterval = null)
        {
            var baseAppAuthUrl = MozuConfig.BaseAppAuthUrl;

            if (appAuthInfo == null || string.IsNullOrEmpty(baseAppAuthUrl))
            {
                throw new Exception("AppAuthInfo or Base App auth Url cannot be null or empty");
            }

            if (String.IsNullOrEmpty(appAuthInfo.ApplicationId) || String.IsNullOrEmpty(appAuthInfo.SharedSecret))
            {
                throw new Exception("ApplicationId or Shared Secret is missing");
            }

            if (_auth != null && _auth.AppAuthInfo.ApplicationId == appAuthInfo.ApplicationId)
            {
                return(_auth);
            }
            try
            {
                _log.Info("Initializing App");
                var uri = new Uri(baseAppAuthUrl);
                HttpHelper.UrlScheme = uri.Scheme;
                var tmp = new AppAuthenticator(appAuthInfo, baseAppAuthUrl, refreshInterval);
                await tmp.AuthenticateAppAsync();

                lock (_lockObj)
                {
                    _auth = tmp;
                }
                _log.Info("Initializing App..Done");
            }
            catch (ApiException exc)
            {
                _log.Error(exc.Message, exc);
                lock (_lockObj)
                {
                    _auth = null;
                }
                throw exc;
            }

            return(_auth);
        }
예제 #6
0
        public static AppAuthenticator Initialize(AppAuthInfo appAuthInfo, RefreshInterval refreshInterval = null)
        {
            var baseAppAuthUrl = MozuConfig.BaseAppAuthUrl;

            if (appAuthInfo == null || string.IsNullOrEmpty(baseAppAuthUrl))
            {
                throw new Exception("AppAuthInfo or Base App auth Url cannot be null or empty");
            }

            if (String.IsNullOrEmpty(appAuthInfo.ApplicationId) || String.IsNullOrEmpty(appAuthInfo.SharedSecret))
            {
                throw new Exception("ApplicationId or Shared Secret is missing");
            }

            if (_auth == null || (_auth != null && _auth.AppAuthInfo.ApplicationId != appAuthInfo.ApplicationId))
            {
                _semaphoreWaiter.Wait();
                lock (_lockObj)
                {
                    try
                    {
                        _log.Info("Initializing App");
                        var uri = new Uri(baseAppAuthUrl);
                        HttpHelper.UrlScheme = uri.Scheme;
                        _auth = new AppAuthenticator(appAuthInfo, baseAppAuthUrl, refreshInterval);
                        _auth.AuthenticateApp();
                        _log.Info("Initializing App..Done");
                    }
                    catch (ApiException exc)
                    {
                        _log.Error(exc.Message, exc);
                        _auth = null;
                        throw exc;
                    }
                    finally
                    {
                        _semaphoreWaiter.Release();
                    }
                }
            }

            return(_auth);
        }
예제 #7
0
        public void SimpleAppAuthLoginTest()
        {
            var baseAppAuthUrl = "http://aus02ndserv001.dev.volusion.com/Mozu.AppDev.WebApi/platform/applications/authtickets/";
            var appId          = "158496f0ca114e0b88bda2ed011dc745";
            var sharedSecret   = "3c9a6a0bd09b44d1a7c7a2ed011dc745";

            var appAuthInfo = new AppAuthInfo
            {
                ApplicationId = appId,
                SharedSecret  = sharedSecret
            };

            MozuConfig.BaseAppAuthUrl = baseAppAuthUrl;
            var authenticator = AppAuthenticator.Initialize(appAuthInfo);

            authenticator.EnsureAuthTicket();

            Assert.IsNotNull(appAuthInfo);
            Assert.IsNotNull(appAuthInfo.ApplicationId);
            Assert.IsNotNull(appAuthInfo.SharedSecret);
        }
예제 #8
0
        public override string OnAuthorizedRequest(RequestMessageAuthorized requestMessage)
        {
            // create new entity
            AppAuthInfo appInfo = new AppAuthInfo();

            appInfo.AuthorizerAppId = requestMessage.AuthorizerAppid; // db table key
            appInfo.AppId           = requestMessage.AppId;           // 第三方平台的 appid
            appInfo.Authorized      = true;
            appInfo.Code            = requestMessage.AuthorizationCode;
            appInfo.ExpiredTime     = requestMessage.AuthorizationCodeExpiredTime;
            appInfo.CreateOn        = DateTime.Now;
            appInfo.LastUpdateOn    = DateTime.Now;

            //,
            var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(ComponentKeys.GetInstance().AccessData.AccessCode, _wxConfig.AppId, requestMessage.AuthorizerAppid);
            var authorizerInfo       = authorizerInfoResult.authorizer_info;
            var authorizerInfoEntity = new JinZhou.Models.DbEntities.AuthorizerInfo()
            {
                UserName      = authorizerInfo.user_name,
                NickName      = authorizerInfo.nick_name,
                HeadImg       = authorizerInfo.head_img,
                ServiceType   = (int)authorizerInfo.service_type_info.id,
                VerifyType    = (int)authorizerInfo.verify_type_info.id,
                PrincipalName = authorizerInfo.principal_name,
                BizStore      = authorizerInfo.business_info.open_store,
                BizPay        = authorizerInfo.business_info.open_pay,
                BizCard       = authorizerInfo.business_info.open_card,
                BizScan       = authorizerInfo.business_info.open_scan,
                BizShake      = authorizerInfo.business_info.open_shake,
                Alias         = authorizerInfo.alias,
                QrcodeUrl     = authorizerInfo.qrcode_url
            };

            appInfo.Authorizer = authorizerInfoEntity;

            db.AppAuths.Add(appInfo);
            db.SaveChanges();
            return(base.OnAuthorizedRequest(requestMessage));
        }
예제 #9
0
        public async Task AsyncTest()
        {
            var baseAppAuthUrl = "http://home.mozu-ci.volusion.com/";
            var appId          = "5d76bb2a852d4741939fa27d00d98a40";
            var sharedSecret   = "348f780339b749b58d3fa27d00d98a40";

            var appAuthInfo = new AppAuthInfo
            {
                ApplicationId = appId,
                SharedSecret  = sharedSecret
            };

            MozuConfig.BaseAppAuthUrl = baseAppAuthUrl;
            await AppAuthenticator.InitializeAsync(appAuthInfo);

            Assert.IsNotNull(AppAuthenticator.Instance);
            Assert.IsNotNull(AppAuthenticator.Instance.AppAuthTicket);
            Assert.IsNotNull(AppAuthenticator.Instance.AppAuthTicket.AccessToken);

            //var tenantResource = new TenantResource();
            //var tenant = await tenantResource.GetTenantAsync(9539);
            //Assert.IsNotNull(tenant);
            //Assert.AreEqual(tenant.Id, 9539);
        }
예제 #10
0
        public IActionResult Installed(string auth_code, int expires_in)
        {
            LogService.GetInstance().AddLog("Home:Installed", null, "Auth succeed", "", "Info");

            var queryAuth = Senparc.Weixin.Open.ComponentAPIs.ComponentApi.QueryAuth(ComponentKeys.GetInstance().AccessData.AccessCode,
                                                                                     _wxConfig.AppId, auth_code);

            string authorizerAppid = queryAuth.authorization_info.authorizer_appid;
            var    authorizer      = db.AppAuths.FirstOrDefault(c => c.AuthorizerAppId == authorizerAppid);

            if (authorizer == null || authorizer.Code != auth_code)
            {
                if (authorizer == null)
                {
                    authorizer                 = new AppAuthInfo();
                    authorizer.AppId           = _wxConfig.AppId;
                    authorizer.AuthorizerAppId = queryAuth.authorization_info.authorizer_appid;
                    authorizer.Authorized      = true;
                    authorizer.CreateOn        = DateTime.Now;

                    var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(ComponentKeys.GetInstance().AccessData.AccessCode, _wxConfig.AppId, queryAuth.authorization_info.authorizer_appid);
                    var authorizerInfo       = authorizerInfoResult.authorizer_info;
                    var authorizerInfoEntity =
                        db.AuthorizerInfos.FirstOrDefault(c => c.UserName == authorizerInfo.user_name);
                    if (authorizerInfoEntity == null)
                    {
                        authorizerInfoEntity = new JinZhou.Models.DbEntities.AuthorizerInfo()
                        {
                            UserName      = authorizerInfo.user_name,
                            NickName      = authorizerInfo.nick_name,
                            HeadImg       = authorizerInfo.head_img,
                            ServiceType   = (int)authorizerInfo.service_type_info.id,
                            VerifyType    = (int)authorizerInfo.verify_type_info.id,
                            PrincipalName = authorizerInfo.principal_name,
                            BizStore      = authorizerInfo.business_info.open_store,
                            BizPay        = authorizerInfo.business_info.open_pay,
                            BizCard       = authorizerInfo.business_info.open_card,
                            BizScan       = authorizerInfo.business_info.open_scan,
                            BizShake      = authorizerInfo.business_info.open_shake,
                            Alias         = authorizerInfo.alias,
                            QrcodeUrl     = authorizerInfo.qrcode_url
                        };
                    }

                    authorizer.Authorizer = authorizerInfoEntity;
                    //TODO: 这里应该存储以下信息,并自动刷新
                    //todo: queryAuth.authorization_info.authorizer_access_token
                    //TODO: queryAuth.authorization_info.authorizer_refresh_token
                    AuthorizerToken token =
                        db.AuthorizerTokens.FirstOrDefault(c => c.AuthorizerAppId == authorizerAppid);
                    if (token == null)
                    {
                        token = new AuthorizerToken();
                        db.AuthorizerTokens.Add(token);
                    }

                    token.RefreshOn              = DateTime.Now;
                    token.AuthorizerAccessToken  = queryAuth.authorization_info.authorizer_access_token;
                    token.AuthorizerRefreshToken = queryAuth.authorization_info.authorizer_refresh_token;
                    token.ExpiredIn              = queryAuth.authorization_info.expires_in;
                    db.SaveChanges();

                    //todo: 网站加入性能监控的组件,方便了解网站的运行状态

                    db.AppAuths.Add(authorizer);
                }
                //need update
                authorizer.Code         = auth_code;
                authorizer.ExpiredTime  = DateTime.Now.AddSeconds(queryAuth.authorization_info.expires_in);
                authorizer.LastUpdateOn = DateTime.Now;
                db.SaveChanges();
            }

            HomeInstalledViewModels vm = new HomeInstalledViewModels();

            vm.AuthorizerAppId = authorizerAppid;
            vm.AuthUrl         = string.Format(_wxConfig.UserAuthEntryPointUriFmt, authorizerAppid);
            return(View(vm));
        }