private async void RefreshTokens(object sender, RoutedEventArgs e)
        {
            var options = new OidcClientOptions
            {
                Authority   = _authority,
                ClientId    = _clientIdentifier,
                RedirectUri = _redirectUri
            };
            var oidcClient = new OidcClient(options);
            var result     = await oidcClient.RefreshTokenAsync(_refreshToken);

            if (result.IsError)
            {
                Message.Text += string.Format("{0} - Refresh Tokens error: {1}\n", DateTime.Now, result.Error);
            }
            else
            {
                _accessToken  = result.AccessToken;
                _refreshToken = result.RefreshToken;
                Message.Text  = string.Format("{0} - Refresh completed successfully\n", DateTime.Now);
                Message.Text += string.Format("{0} - Identity token {1}\n Access token {2}\n"
                                              , DateTime.Now
                                              , JWTTokenHelper.ReadToken(_identityToken)
                                              , JWTTokenHelper.ReadToken(_accessToken));
            }
        }
        private void GetDataSource(object sender, RoutedEventArgs e)
        {
            if (JWTTokenHelper.IsTokenExpired(_accessToken))
            {
                Message.Text = string.Format("{0} - Get Data Source error {1} No security tokens acquired or security tokens expired!"
                                             , DateTime.Now
                                             , Environment.NewLine);
                return;
            }

            try
            {
                var dataSource = _sharedFrameworkReader.GetDataSource(_accessToken);
                Message.Text = string.Format("{0} - Get Data Source ok {1}{2}"
                                             , DateTime.Now
                                             , Environment.NewLine
                                             , dataSource.ToString());
            }
            catch (Exception ex)
            {
                Message.Text = string.Format("{0} - Get Data Source error {1}{2}"
                                             , DateTime.Now
                                             , Environment.NewLine
                                             , ex.Message);
            }
        }
Exemple #3
0
        public IActionResult Login(string account, string password)
        {
            var isExist = _user.UserLogin(account, password, out var userInfo);

            //用户不存在
            if (!isExist)
            {
                return(new JsonResult(JsonConvert.SerializeObject(new
                {
                    StatusCode = 200,
                    Status = ReturnStatus.Fail,
                    Msg = "用户名或密码错误,请重新输入"
                })));
            }

            var token = JWTTokenHelper.JwtEncrypt(new TokenModelJwt()
            {
                UserId = userInfo.Id, Level = ""
            }, this._jwtTokenOptions);

            using (RedisStringService service = new RedisStringService())
            {
                service.Set <T_Sys_User>("Bearer " + token, userInfo);
            }



            return(new JsonResult(new ReturnResultModel()
            {
                StatusCode = 200,
                Status = ReturnStatus.Success,
                Data = token,
                Msg = "登录成功"
            }));
        }
Exemple #4
0
        private void Authenticate_Clicked(object sender, RoutedEventArgs e)
        {
            var disco = DiscoveryClient.GetAsync(ConnectivitySettings.Authority).Result;

            if (disco.IsError)
            {
                throw new Exception(disco.Error);
            }

            var client = new TokenClient(disco.TokenEndpoint, ConnectivitySettings.ClientIdentifier, ConnectivitySettings.ClientSecret);
            var tokens = client.RequestClientCredentialsAsync(ConnectivitySettings.Scope).Result;

            _accessToken = tokens.AccessToken;

            Status.Text = string.Format("Access Token: \n{0}", JsonHelper.FormatJson(JWTTokenHelper.ReadToken(_accessToken)));

            if (string.IsNullOrEmpty(_accessToken))
            {
                SetWorkflowIndicator(Workflow.WorkflowState.Authenticate, Visibility.Visible, false);
            }
            else
            {
                EnableGetAppRolePasswordControls();
                SetWorkflowIndicator(Workflow.WorkflowState.Authenticate, Visibility.Visible, true);
            }
        }
Exemple #5
0
        public string GetAuthToken(LogionModel logion)
        {
            SearchCondition search = new SearchCondition();

            search.AddCondition("F_Account", logion.Account, SqlOperator.Equal);
            search.AddCondition("F_PassWord", logion.PassWord, SqlOperator.Equal);
            Sys_UserInfo user = BLLFactory <Sys_User> .Instance.FindSingle(GetConditionStr(search));

            if (user != null)
            {
                return(JWTTokenHelper.GetToken(user.F_Account, user.F_IsAdministrator ?? false));
            }
            return("账号或者密码不正确");
        }
        private async void Authenticate(object sender, RoutedEventArgs e)
        {
            var browser = new SystemBrowser();

            _redirectUri = string.Format($"http://127.0.0.1:{browser.Port}");

            var options = new OidcClientOptions
            {
                Authority    = _authority,
                ClientId     = _clientIdentifier,
                ClientSecret = "secret",
                Scope        = "openid profile offline_access " + _scope,
                RedirectUri  = _redirectUri,
                Browser      = browser,
                //FilterClaims = false,
                Policy = new Policy
                {
                    Discovery = new DiscoveryPolicy
                    {
                        ValidateEndpoints  = false,
                        ValidateIssuerName = false
                    }
                }
            };

            var oidcClient   = new OidcClient(options);
            var loginRequest = new LoginRequest();

            var result = await oidcClient.LoginAsync(loginRequest);

            if (result.IsError)
            {
                _accessToken   = null;
                _identityToken = null;
                _refreshToken  = null;
            }
            else
            {
                _accessToken   = result.AccessToken;
                _identityToken = result.IdentityToken;
                _refreshToken  = result.RefreshToken;
            }

            Message.Text = string.Format("{0} - Identity token {1}\n Access token {2}\n"
                                         , DateTime.Now
                                         , JWTTokenHelper.ReadToken(_identityToken)
                                         , JWTTokenHelper.ReadToken(_accessToken));
        }
        public async Task <string> GetCurrentUser(LoginModel model)
        {
            KgmApiResultEntity result    = new KgmApiResultEntity();//返回对象
            SearchCondition    condition = new SearchCondition();

            condition.AddCondition("F_Account", model.Account, SqlOperator.Equal);
            Sys_UserInfo loginResult = BLLFactory <Sys_User> .Instance.FindSingle(condition.BuildConditionSql().Replace(" Where (1=1)  AND", string.Empty));

            if (loginResult == null)
            {
                result.result  = false;
                result.message = "用户名不存在!";
            }
            else if (!loginResult.F_UserPassword.Equals(DESEncrypt.Encrypt(model.Password)))
            {
                result.result  = false;
                result.message = "用户名与密码不匹配!";
            }
            else
            {
                bool isadmin = false;
                if (loginResult.F_EnabledMark == false)
                {
                    result.result  = false;
                    result.message = "该用户已被禁用,请联系管理员启用后再进行登录!";
                }
                else
                {
                    if (loginResult.F_IsAdministrator == true)
                    {
                        isadmin = true;
                    }
                    //生成token
                    var token = await JWTTokenHelper.GetTokenAsync(loginResult.F_Id, "0", isadmin);

                    var id = currentUserId;
                    result.result  = true;
                    result.message = token;
                }
            }


            return(JsonAppHelper.ToJson(new { status = result.result, token = result.message, User = loginResult }));
        }
        /// <summary>
        /// This is the default route called when you access this url with GET: /SecureLink.  e.g. https://qa01loancenter.newleaflending.com/SecureLink
        ///
        /// SecureLink is meant to be a standalone web application built on angular for handling borrower signing.  It
        /// </summary>
        /// <param name="token">A JWT token that has encoded a SecureLinkAuthenticationViewModel object that has propeties like LoanId and borrower information.</param>
        /// <returns>HTML for the secure link webpage.</returns>
        public ActionResult Index(string token)
        {
            var model = new AuthenticationViewModel();

            bool isSecureLinkTestMode = false;

            bool.TryParse(ConfigurationManager.AppSettings["IsSecureLinkTestMode"], out isSecureLinkTestMode);
            //This block is for testing with a test token
            if (isSecureLinkTestMode == true && string.IsNullOrEmpty(token))
            {
                token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IkxvYW5JZCI6ImIzNzcxYTM2LTExOTMtNGVjNC1iNGM4LTUyMjM2MjA4NDFhOSIsIkxvYW5BcHBsaWNhdGlvbklkIjoiYjM3NzFhMzYtMTE5My00ZWM0LWI0YzgtNTIyMzYyMDg0MWE5IiwiSXNDb250aW51ZVdpdGhvdXRMb2dpbiI6ZmFsc2UsIklzQm9ycm93ZXJDb250aW51ZVdpdGhvdXQiOmZhbHNlLCJCb3Jyb3dlciI6eyJCb3Jyb3dlcklkIjoiZGUzMTYyOTgtODcxYS00MDAwLTg5NzEtNTVjYmFlMTg4OTJhIiwiRnVsbE5hbWUiOiJLZXJyeSBCYXllcyIsIlVzZXJBY2NvdW50SWQiOjkxNTQ2LCJJbnB1dFBJTiI6bnVsbCwiSXNBdXRoZW50aWNhdGVkIjpudWxsfSwiQ29Cb3Jyb3dlciI6eyJCb3Jyb3dlcklkIjoiZDZmNGUyMzYtNmFmNy00ZDRkLThjZjAtM2M4YmY1YTA2OTkzIiwiRnVsbE5hbWUiOiJQQVRSSUNJQSBBREFNUyIsIlVzZXJBY2NvdW50SWQiOjkzMTU3LCJJbnB1dFBJTiI6bnVsbCwiSXNBdXRoZW50aWNhdGVkIjpudWxsfSwiVG9rZW4iOm51bGx9fQ.Xb3hMDv5fkO9_rQV1chvyNWGhSgQsuv4y69Qn0Fiqgw";
            }

            //Check for a valid token and render it to the page
            model.isSecureLinkTestMode    = isSecureLinkTestMode;
            model.isTokenValid            = false;
            model.authenticationViewModel = new JObject();

            if (!string.IsNullOrEmpty(token))
            {
                string secretKey = ConfigSystem.Client.Instance.GetConfigurationValue("SecureLink.JWTPassword", "Environment", new string[] { });
                //double expirationHours = double.Parse(ConfigSystem.Client.Instance.GetConfigurationValue("SecureLink.JWTExpirationHours", "Environment", new string[] { }));
                IDictionary <string, object> payload;
                if (JWTTokenHelper.DecodeToken(token, secretKey, out payload))
                {
                    //Need CamelCasePropertyNamesContractResolver to make JSON with camel case properties.
                    var serializer = new JsonSerializer()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    };
                    JObject data = JObject.FromObject(payload["data"], serializer);
                    if (data != null)
                    {
                        model.authenticationViewModel = data;
                        model.isTokenValid            = true;
                    }

                    //model.authenticationViewModel = JObject.Parse(values["data"].ToString());
                    //model.isTokenValid = true;
                }
            }

            return(View(model));
        }
Exemple #9
0
        private void GetToken()
        {
            try
            {
                if ((tokenExpirationTime - DateTime.Now.ToUniversalTime() < new TimeSpan(0, 2, 0)) ||
                    assertion == null)
                {
                    tokenExpirationTime = DateTime.Now.ToUniversalTime().AddHours(1);

                    var webToken = new JsonWebToken(
                        _appPrincipalId,
                        _tenantContextId.ToString(CultureInfo.InvariantCulture),
                        (new Uri(_stsUrl)).DnsSafeHost,
                        JWTTokenHelper.AcsPrincipalId,
                        DateTime.Now.ToUniversalTime(),
                        60 * 60);

                    // webToken.NameIdentifier = string.Format("{0}@{1}", appPrincipalId, tenantContextId);


                    // You can get ACS token using Asymmetric Key as well. Here would be the implementation.
                    // X509Certificate2 clientCertificate = new X509Certificate2(clientCertificateFilePath, clientCertificatePassword, X509KeyStorageFlags.Exportable);
                    // assertion = JWTTokenHelper.GenerateAccessToken(webToken, clientCertificate);

                    // Get ACS token using symmetricKey
                    assertion = JWTTokenHelper.GenerateAssertion(webToken, _symmetricKey);

                    string resource = String.Format("{0}/{1}@{2}", _protectedResourcePrincipalId, _protectedResourceHostName, _tenantContextId);
                    assertion = JWTTokenHelper.GetOAuthAccessTokenFromACS(_stsUrl, assertion, resource);
                }
            }
            catch (WebException webExc)
            {
                if (webExc.Response != null)
                {
                    using (Stream responseStream = webExc.Response.GetResponseStream())
                    {
                        StreamReader sr = new StreamReader(responseStream);
                        string       responseMessage = sr.ReadToEnd();
                    }
                }
                throw;
            }
        }
        /// <summary>
        /// 认证方式
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            try
            {
                //前端请求api时会将token存放在名为"auth"的请求头中
                var authHeader = from h in actionContext.Request.Headers where h.Key == ConstValue.TOKEN_HEADER select h.Value.FirstOrDefault();

                //没有头部标识
                if (authHeader == null)
                {
                    throw new ApplicationException("没有报文头信息");
                }
                //获取传输过来的token
                string token = authHeader.FirstOrDefault().Substring(6).Trim();
                //token为空 返回false
                if (string.IsNullOrEmpty(token))
                {
                    throw new ApplicationException("没有token信息");
                }

                Dictionary <string, object> dict = JWTTokenHelper.AnalyzeToken(token);


                //判断当前token与数据库内的是否一致,如果不一致,也报错
                //var userToken = BLLFactory<SysUsertoken>.Instance.FindByID(dict[AppConst.JWT_SUB_KEY]);
                //if (userToken == null || !userToken.Token.Equals(token))
                //{
                //    throw new ApplicationException("token已经失效");
                //}

                //将用户信息存放起来,供后续调用
                actionContext.RequestContext.RouteData.Values.Add(ConstValue.TOKEN_HEADER, dict);

                return(true);
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString());
                return(false);
            }
        }
Exemple #11
0
        /// <summary>
        /// 登录系统
        /// </summary>
        /// <param name="loginModel">登录对象</param>
        /// <returns></returns>
        private async Task <KgmApiResultEntity> loginSystemAsync(LoginSystemModel loginModel)
        {
            KgmApiResultEntity result = new KgmApiResultEntity();//返回对象

            result.result  = false;
            result.message = "";

            string errorInfo = string.Empty;

            if (!bRegister(out errorInfo))
            {
                result.result  = false;
                result.message = errorInfo;
                return(result);
            }

            Sys_UserInfo loginResult;//登录对象
            bool         bAdmin = false;

            if (loginModel.Account.Equals(ConstValue.KGMADMIN_USERNAME) && loginModel.Password.Equals(ConstValue.KGMADMIN_PASSWORD))
            {
                //超级管理员
                loginResult                = new Sys_UserInfo();
                loginResult.F_Id           = ConstValue.KGMADMIN_USERID;
                loginResult.F_UserPassword = ConstValue.KGMADMIN_PASSWORD;
                loginResult.F_RealName     = ConstValue.KGMADMIN_USERNAME;
                bAdmin = true;
            }
            else
            {
                SearchCondition condition = new SearchCondition();
                condition.AddCondition("F_Account", loginModel.Account, SqlOperator.Equal);
                loginResult = BLLFactory <Sys_User> .Instance.FindSingle(condition.BuildConditionSql().Replace(" Where (1=1)  AND", string.Empty));
            }


            if (loginResult == null)
            {
                SaveLoginLog(loginModel.Account, string.Empty, loginModel.LoginSystem.ToString(), false, "用户名不存在!");
                result.result  = false;
                result.message = "用户名不存在!";
            }
            else if (!loginResult.F_UserPassword.Equals(DESEncrypt.Encrypt(loginModel.Password)))
            {
                SaveLoginLog(loginModel.Account, string.Empty, loginModel.LoginSystem.ToString(), false, "用户名与密码不匹配!");
                result.result  = false;
                result.message = "用户名与密码不匹配!";
            }
            else
            {
                string token = "";    //token
                //生成token
                token = await JWTTokenHelper.GetTokenAsync(loginResult.F_Id, loginModel.LoginSystem, bAdmin);

                SaveLoginLog(loginResult.F_Account, loginResult.F_NickName, loginModel.LoginSystem.ToString(), true, "登录成功");
                result.result  = true;
                result.message = token;
            }

            return(result);
        }