示例#1
0
        public static void SendAuthComplete(bool failed, AuthResult result, AuthSession session)
        {
            var complete = new AuthPacket(AuthServerMessage.Complete);

            complete.Write(failed, 1);

            if (failed)
            {
                complete.Write(false, 1);       // false - disable optional modules
                complete.Write(1, 2);           // 1 - enable AuthResults
                complete.Write(result, 16);     // AuthResults (Error codes)
                complete.Write(0x80000000, 32); // Unknown
            }
            else
            {
                complete.Write(0, 3);
                complete.Write(0x80005000, 32); // Ping request, ~10 secs

                var hasOptionalData = true;

                complete.Write(hasOptionalData, 1);

                if (hasOptionalData)
                {
                    var hasConnectionInfo = true;

                    complete.Write(hasConnectionInfo, 1);

                    if (hasConnectionInfo)
                    {
                        complete.Write(25000000, 32);
                        complete.Write(1000, 32);
                    }
                }

                complete.Write(false, 1);

                complete.WriteString("", 8, false); // FirstName not implemented
                complete.WriteString("", 8, false); // LastName not implemented

                complete.Write(session.Account.Id, 32);

                complete.Write(0, 8);
                complete.Write(0, 64);
                complete.Write(0, 8);

                complete.WriteString(session.Account.Email, 5, false, -1);

                complete.Write(0, 64);
                complete.Write(0, 32);

                complete.Write(0, 8);
            }

            session.Send(complete);
        }
示例#2
0
 public SamlDirector(IPrincipalBuilder principalBuilder, IAuthenticationSession session, IPrincipalContext context)
 {
     _principalBuilder = principalBuilder;
     _session = session;
     _context = context;
     _result = new AuthResult
     {
         Success = false,
         Continuation =
             FubuContinuation.RedirectTo(new LoginRequest
             {
                 Message = SamlValidationKeys.UnableToValidationSamlResponse
             }, "GET")
     };
 }
示例#3
0
        public ServerAuthProof(BinaryReader reader)
            : this()
        {
            command = AuthCommand.LOGON_PROOF;
            error = (AuthResult)reader.ReadByte();
            if (error != AuthResult.SUCCESS)
            {
                reader.ReadUInt16();
                return;
            }

            M2 = reader.ReadBytes(20);
            unk1 = reader.ReadUInt32();
            unk2 = reader.ReadUInt32();
            unk3 = reader.ReadUInt16();
        }
        public ServerAuthChallenge(BinaryReader reader)
            : this()
        {
            command = AuthCommand.LOGON_CHALLENGE;
            unk2 = reader.ReadByte();
            error = (AuthResult)reader.ReadByte();
            if (error != AuthResult.SUCCESS)
                return;

            B = reader.ReadBytes(32);
            gLen = reader.ReadByte();
            g = reader.ReadBytes(1);
            nLen = reader.ReadByte();
            N = reader.ReadBytes(32);
            salt = reader.ReadBytes(32);
            unk3 = reader.ReadBytes(16);
            securityFlags = reader.ReadByte();
        }
        public async Task<AuthResult> AuthAsync(string startUrl, string endUrlPrefix)
        {
            AuthResult result = new AuthResult(WebAuthenticationStatus.UserCancel);
            Uri start = null;

            OnlineIdServiceTicketRequest[] tickets = new OnlineIdServiceTicketRequest[]
            {
                new OnlineIdServiceTicketRequest(
                    new Uri(startUrl).Host,
                    String.IsNullOrEmpty(LiveIdAuthPolicy)
                        ? ServiceDefinition.DefaultLiveIdAuthPolicy
                        : LiveIdAuthPolicy)
            };

            try
            {
                var onlineIdAuthenticator = new OnlineIdAuthenticator();
                UserIdentity useridentity =
                    await onlineIdAuthenticator.AuthenticateUserAsync(tickets, CredentialPromptType.PromptIfNeeded);

                if (useridentity != null && useridentity.Tickets != null && useridentity.Tickets.Count > 0)
                {
                    OnlineIdServiceTicket ticket = useridentity.Tickets.First();
                    start = new Uri(startUrl + WebUtility.UrlEncode("&" + ticket.Value) + "&mobile=true");
                }
            }
            catch (TaskCanceledException)
            {
                result.Status = WebAuthenticationStatus.UserCancel;
            }
            catch
            {
                start = new Uri(startUrl + "&mobile=true");
            }
            
            if (start != null)
            {
                WebAuthenticationResult webAuthResult = (await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, start, new Uri(endUrlPrefix)));
                result = new AuthResult(webAuthResult);
            }

            return result;
        }
示例#6
0
 public AuthResult merge(AuthResult auth)
 {
     if (auth.result != null)
     {
         result = auth.result;
         game   = null;
         player = null;
     }
     else
     {
         if (auth.game != null)
         {
             game = auth.game;
         }
         if (auth.player != null)
         {
             player = auth.player;
         }
     }
     return(this);
 }
示例#7
0
        public async Task <IActionResult> Auth(AuthRequest request)
        {
            AuthResult res = userService.Login(
                new LoginInfoDTO {
                Login    = request.Login,
                Password = request.Password,
                Key      = request.SecretKey,
                Browser  = Request.Headers["User-Agent"],
                IP       = Request.HttpContext.Connection.RemoteIpAddress.ToString()
            }
                );

            if (res.Status == AuthStatus.Succsess)
            {
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(res.Identity));
            }
            return(new JsonResult(
                       new AuthResponse {
                AuthType = res.authType, KeyTime = res.KeyTime, Status = res.Status
            }));
        }
        public AuthResult TryToApply()
        {
            AuthResult result = AuthResult.Failed();

            _requestData.Value(SamlResponseKey, v => {
                try
                {
                    var xml = v.RawValue as string;
                    ProcessSamlResponseXml(xml);
                }
                catch (Exception e)
                {
                    _logger.Error("Saml Response handling failed", e);
                    _director.FailedUser();
                }

                result = _director.Result();
            });

            return(result);
        }
示例#9
0
        public static AuthResult GetAuth <TKey>(System.Security.Claims.ClaimsIdentity claim, IUserDevice <TKey> model)
        {
            var now = DateTime.Now;
            var jwt = new JwtSecurityToken(
                issuer: AuthOption.ISSUER,
                audience: AuthOption.AUDINECE,
                notBefore: now,
                claims: claim.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthOption.LifeTime)),
                signingCredentials: new SigningCredentials(State.GetSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            AuthResult result = new AuthResult()
            {
                AccessToken  = encodedJwt,
                RefreshToken = ComputeSha256Hash(now.ToLongDateString() + now.ToLongTimeString() + RepositoryRule.State.State.RandomString(6)),
                AccessTime   = now,
            };

            return(result);
        }
示例#10
0
        public IAuthResult Login(ILoginModel model)
        {
            var result = new AuthResult
            {
                Message = Constants.MessageLoginFailUnknow,
                Success = false
            };

            UserService = Container.Resolve <IUserService>();
            var user = UserService.GetByLoginPassword(model.Login.ToLower(), model.Password);

            if (user != null)
            {
                result.Success = true;
                result.Message = Constants.MessageLoginSuccess;
                result.Login   = user.Login;
                result.UserID  = user.Id.ToString();
            }

            return(result);
        }
        public IActionResult CheckUser([FromForm] UserAuthRequest request)
        {
            var tags = new [] { "administrator", "management" };

            try
            {
                var userlog = string.Format("user : {0}, password : {1}", request.UserName, request.Password);
                _logger.LogInformation(userlog);

                if (request.UserName == "authuser") //Sample check you can put your custom logic over here
                {
                    return(AuthResult.Deny());
                }
            }
            catch (Exception ex)
            {
                //check or log error
            }

            return(AuthResult.Allow(tags));
        }
示例#12
0
        public AuthResult TryPassword(string userName, string password)
        {
            byte[] phash  = Digest(password);
            var    reply  = Call(CmdTryPassword, userName, phash);
            var    result = reply.ReadCString();

            switch (result)
            {
            case ReplyOk:
                var sessionId     = reply.ReadCString();
                var sessionCookie = GetCookie();
                return(AuthResult.Success(sessionId, sessionCookie));

            case ReplyNo:
                var error = reply.ReadCString();
                throw new AuthException(error);

            default:
                throw new AuthException($"Unexpected reply {result} from auth server");
            }
        }
示例#13
0
        public async Task <AuthResult> AssignRoleToUserAsync(int userId, string[] roles)
        {
            var user = await _userManager.FindByIdAsync(userId.ToString());

            var message    = new AuthResult();
            var existRoles = await _userManager.GetRolesAsync(user);

            //adding new roles
            var newRoles = roles.Where(p => !existRoles.Any(p2 => p2 == p)).ToList();
            await _userManager.AddToRolesAsync(user, newRoles);

            //remove new roles
            var deletedRoles = existRoles.Where(ex => !roles.Any(p2 => p2 == ex)).ToList();
            await _userManager.RemoveFromRolesAsync(user, deletedRoles);

            message = new AuthResult()
            {
                Suceess = true, Message = "Successfully add roles"
            };
            return(message);
        }
示例#14
0
        public string ParseGameArguments(AuthResult authResult)
        {
            var mcArgumentsDic = new Dictionary <string, string>
            {
                { "${version_name}", LaunchSettings.Version },
                { "${version_type}", GameProfile?.Type ?? $"\"{LaunchSettings.LauncherName}\"" },
                { "${assets_root}", $"\"{AssetRoot}\"" },
                { "${assets_index_name}", $"\"{VersionInfo.AssetInfo.Id}\"" },
                {
                    "${game_directory}",
                    $"\"{(string.IsNullOrWhiteSpace(LaunchSettings.GamePath) ? "/" : LaunchSettings.GamePath)}\""
                },
                { "${auth_player_name}", authResult?.SelectedProfile?.Name },
                { "${auth_uuid}", authResult?.SelectedProfile?.Id },
                { "${auth_access_token}", authResult?.AccessToken },
                { "${user_properties}", authResult?.User?.Properties.ResolveUserProperties() },
                { "${user_type}", "Mojang" } // use default value as placeholder
            };

            return(StringHelper.ReplaceByDic(VersionInfo.GameArguments, mcArgumentsDic));
        }
示例#15
0
        public void RetriveToken(ref AuthResult authResult)
        {
            Debug.Assert(authResult.Status);
            if (!authResult.Status)
            {
                return;
            }
            var client = authResult.Client;
            var output = Exec.Run("-p " + server.Host + " -u " + client.Username + " tickets");
            var match  = Regex.Match(output, @"\b(.*)\s((.*))\b");

            if (match.Success && match.Groups.Count == 4)
            {
                var token = match.Groups[3];
                client.Token = token.Value;
            }
            else
            {
                authResult = new AuthResult(client, false);
            }
        }
示例#16
0
        public async Task <Launcher.Launcher> LaunchGame(string id, bool offline = true)
        {
            AuthResult authResult;

            if (offline)
            {
                authResult = new AuthResult(BmclCore.Config);
            }
            else
            {
                authResult = await BmclCore.AuthManager.Login(BmclCore.Config.Username, BmclCore.Config.GetPassword());

                if (!authResult.IsSuccess)
                {
                    var authname = "BMCL";
                    if (BmclCore.AuthManager.GetCurrectAuth() is IBmclAuthPlugin)
                    {
                        var plugin = BmclCore.AuthManager.GetCurrectAuth() as IBmclAuthPlugin;
                        authname = plugin?.GetName();
                    }
                    MessageBox.Show(BmclCore.MainWindow, authResult.Message, authname, MessageBoxButton.OK);
                    return(null);
                }
            }
            if (_launcher != null)
            {
                throw new AnotherGameRunningException(_launcher);
            }
            var game = GetVersion(id);

            if (game == null)
            {
                throw new NoSuchVersionException(id);
            }
            _launcher = new Launcher.Launcher(game, authResult, BmclCore.Config);
            _launcher.OnLaunchError += (launcher, exception) => _launcher = null;
            _launcher.OnGameExit    += (sender, info, exitcode) => _launcher = null;
            _launcher.OnGameStart   += LauncherOnGameStart;
            return(_launcher);
        }
示例#17
0
        static async Task Main(string[] args)
        {
            OfflineAuthenticator mojangAuthenticator = new OfflineAuthenticator
            {
                Account = "*****@*****.**",
            };
            AuthResult authResult = mojangAuthenticator.Auth();

            Console.WriteLine(authResult.PlayerName);
            Global.AuthConfiguation   = authResult;
            Global.LaunchConfiguation = new LaunchConfiguation
            {
                JavaSetting = new JavaSetting
                {
                    MaxMemorySize = 10,
                    MinMemorySize = 6,
                    JavaPath      = @"C:\Program Files\Java\jre1.8.0_241\bin\javaw.exe",
                },
                MinecraftSetting = new MinecraftSetting
                {
                    LauncherName    = "Tets",
                    MinecraftSource = @"D:\Minecraft\Solution1\.minecraft",
                    VersionJson     = JsonStorage.ParseVersionJson(@"D:\Minecraft\Solution1\.minecraft\versions\1.8.9")
                }
            };
            foreach (var item in Libraries.GetExistLibraries())
            {
                Console.WriteLine(item.DownloadUri);
                Console.WriteLine(item.FileName);
            }
            LaunchCore launchCore = new LaunchCore();
            String     argss      = launchCore.GenerateLaunchArgs();

            Console.WriteLine(argss);
            launchCore.ExtraNatives();



            Console.ReadLine();
        }
示例#18
0
        /// <summary>
        /// Valida um token.
        /// </summary>
        /// <returns></returns>
        internal static AuthResult ValidateToken()
        {
            if (_securityKey == null)
            {
                _securityKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(ParameterCache.Get("TOKEN_SYMETRIC_KEY")));
            }

            AuthResult result      = new AuthResult();
            string     accessToken = ReadTokenFromRequest();

            if (!string.IsNullOrWhiteSpace(accessToken))
            {
                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    ValidAudience    = TOKEN_AUDIENCE,
                    ValidIssuer      = TOKEN_ISSUER,
                    IssuerSigningKey = _securityKey
                };

                SecurityToken jwtToken = null;
                try
                {
                    result.TokenClaims = _tokenHandler.ValidateToken(accessToken, validationParameters, out jwtToken);
                }
                catch (SecurityTokenExpiredException)
                {
                    result.AuthStatus = AuthStatus.TOKEN_EXPIRED;
                }
                catch
                {
                    result.AuthStatus = AuthStatus.UNAUTHORIZED;
                }
            }
            else
            {
                result.AuthStatus = AuthStatus.ANONYMOUS;
            }

            return(result);
        }
示例#19
0
        static string ObtainAccessToken(string clientID, string clientSecret, string refreshToken)
        {
            const string AuthRequestBase = "https://auth.ischool.com.tw/oauth/token.php";
            const string AuthGrantType   = "grant_type=refresh_token";

            string urlString = $"{AuthRequestBase}?{AuthGrantType}&client_id={clientID}&client_secret={clientSecret}&refresh_token={refreshToken}";

            // 準備 Http request
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(urlString);

            req.Method        = "GET";
            req.Accept        = "*/*";
            req.ContentType   = "application/json";
            req.ContentLength = 0;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            // 呼叫並取得結果
            HttpWebResponse rsp;

            rsp = (HttpWebResponse)req.GetResponse();
            Stream       dataStream = rsp.GetResponseStream();
            StreamReader reader     = new StreamReader(dataStream);
            string       result     = reader.ReadToEnd();

            reader.Close();
            dataStream.Close();
            rsp.Close();

            //Console.WriteLine(result);

            // 解析 JSON
            byte[]       byteArray         = Encoding.UTF8.GetBytes(result);
            MemoryStream authStream        = new MemoryStream(byteArray);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(AuthResult));

            authStream.Position = 0;
            AuthResult authResult = (AuthResult)ser.ReadObject(authStream);

            return(authResult.accessToken);
        }
示例#20
0
        private static void MenuAuthHelper(AuthResult result, string menuName)
        {
            string str;

            if (result == null || !result.IsLicensed)
            {
                str = "licenseUnlicensed";
            }
            else if (result.IsLifetime())
            {
                str = "licenseLifetime";
            }
            else
            {
                str = "licenseSubscription";
            }

            var expiry = result.Expiry.ToString(CultureInfo.InvariantCulture);
            var item   = Menu.GetMenu("license").Get <MenuText>(menuName);

            void Update(EventArgs _)
            {
                Menu.ResetTranslations("license", menuName);

                var inner = GetString(str).Replace("{expiry}", expiry);

                item.Text = item.Text.Replace("{status}", "\n" + inner);
            }

            if (MenuLicenseHandlers.TryGetValue(menuName, out var value))
            {
                Menu.OnLanguageChanged -= value;
            }

            MenuLicenseHandlers[menuName] = Update;
            Menu.OnLanguageChanged       += Update;

            Update(null);
        }
示例#21
0
        private void ShowAuthError(string email, AuthResult res, Mode mode, bool googleAuth = false)
        {
            DialogFragment dia = null;

            switch (res)
            {
            case AuthResult.InvalidCredentials:
                if (mode == Mode.Login && !googleAuth)
                {
                    dia = new ErrorDialogFragment(LoginError.InvalidCredentials);
                }
                else if (mode == Mode.Signup)
                {
                    dia = new ErrorDialogFragment(LoginError.SignupFailed);
                }
                else if (mode == Mode.Login && googleAuth)
                {
                    dia = new ErrorDialogFragment(LoginError.NoAccount);
                }
                break;

            case AuthResult.NoDefaultWorkspace:
                dia = new NoWorkspaceDialogFragment(email);
                break;

            case AuthResult.NetworkError:
                dia = new ErrorDialogFragment(LoginError.NetworkError);
                break;

            default:
                dia = new ErrorDialogFragment(LoginError.SystemError);
                break;
            }

            if (dia != null)
            {
                dia.Show(FragmentManager, "auth_result_dialog");
            }
        }
示例#22
0
        public async Task <IActionResult> Token([FromBody] Client.Auth.TokenCreationInfo tokenCreationInfo,
                                                CancellationToken cancellationToken)
        {
            string encodedJwt;

            try
            {
                encodedJwt = await authenticator.AuthenticateAsync(tokenCreationInfo.Email, tokenCreationInfo.Password,
                                                                   cancellationToken);
            }
            catch
            {
                return(BadRequest("Invalid login or password"));
            }

            var authResult = new AuthResult
            {
                Token = encodedJwt
            };

            return(Ok(authResult));
        }
示例#23
0
        public IActionResult Index(IndexViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            UserData user = _authentication.GetUserByAssociatedUser(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_authentication.GetUserId(User)}'.");
            }

            var email = user.Email;

            if (model.Email != email)
            {
                AuthResult setEmailResult = _authentication.SetUserEmail(User, model.Email);
                if (!setEmailResult.Succeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                }
            }

            var phoneNumber = user.PhoneNumber;

            if (model.PhoneNumber != phoneNumber)
            {
                AuthResult setPhoneResult = _authentication.SetUserPhoneNumber(User, model.PhoneNumber);
                if (!setPhoneResult.Succeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
                }
            }

            StatusMessage = "Your profile has been updated";
            return(RedirectToAction(nameof(Index)));
        }
示例#24
0
        public async Task <ApplicationActionResult <AuthResult> > Refresh(JwtTokenModel authToken)
        {
            AuthResult      refreshResult = new AuthResult();
            string          userLogin     = _tokenHelper.GetUserNameFromExpiredToken(authToken.AccessToken);
            ApplicationUser user          = await _userManager.FindByNameAsync(userLogin);

            //Validate refresh token
            if (user.RefreshToken != authToken.RefreshToken)
            {
                refreshResult.InvalidRefreshToken();
                return(new ApplicationActionResult <AuthResult>(refreshResult, (int)Core.Constants.ActionStatuses.Fail, ""));
            }
            //create access and refresh token
            var token = await _tokenHelper.CreateJwtTokens(user);

            //save user refresh token in database
            user.SetRefreshToken(token.RefreshToken);
            await _userManager.UpdateAsync(user);

            refreshResult.SuccessAuth(token);
            return(new ApplicationActionResult <AuthResult>(refreshResult, (int)Core.Constants.ActionStatuses.Success, ""));
        }
示例#25
0
        public async Task AddUser_Throws_Exception_When_Trying_To_Write_Different_User_Than_Specified_Credentials()
        {
            /* Test this rule
             * {
             * "rules": {
             *  "users": {
             *    "$userId": {
             *      ".write": "auth.uid == $userId"
             *    }
             *  }
             * }
             * }
             */
            AuthResult result = await _authService.LoginWithEmailAndPasswordAsync(_validatedUser, "testPassword");

            Assert.IsNotNull(result.User);
            Assert.IsNotNull(result.User.UserId);
            Assert.IsTrue(result.User.IsEmailVerified);
            Assert.AreEqual("Success", result.Result); //check that preparation is successful

            Assert.ThrowsAsync <FirebaseException>(() => _sut.SaveUserAsync(_user));
        }
示例#26
0
        /// <summary>
        /// Update the user's password
        /// </summary>
        /// <param name="oldpass">Old password to validate</param>
        /// <param name="newpass">Intended password to be changed</param>
        /// <returns>AuthResult Success if password is changed successfully</returns>
        internal AuthResult UpdatePassword(string oldpass, string newpass)
        {
            using (DataContext db = new DataContext())
            {
                Users u = Users.FindByEmail(this.Email, db);
                if (u == null)
                {
                    return(AuthResult.UserNotFound);
                }

                AuthResult oldpwres = ValidateLogin(oldpass);
                if (oldpwres != AuthResult.Success)
                {
                    return(oldpwres);
                }

                db.Entry(u).Reference(usr => usr.UserKeyStore).Load();

                // Get the user key store and decrypt their private key
                UserKeyStore uks          = u.UserKeyStore;
                byte[]       aesKey       = Crypt.Instance.DeriveKey(oldpass, u.Salt, uks.DesIv);
                byte[]       rsaPrivBytes = Crypt.Instance.DecryptAes(uks.RsaPriv, aesKey, uks.AesIv);

                // Do the password update
                u.UpdatePassword(newpass);

                // Encrypt the private key again
                byte[] newAesIv = Crypt.Instance.GenerateIv("AES");
                uks.AesIv = newAesIv;
                byte[] newAesKey     = Crypt.Instance.DeriveKey(newpass, u.Salt, uks.DesIv);
                byte[] newRsaPrivEnc = Crypt.Instance.EncryptAes(rsaPrivBytes, newAesKey, newAesIv);
                uks.RsaPriv = newRsaPrivEnc;

                db.SaveChanges();

                AuthLogger.Instance.PasswordChanged();
                return(AuthResult.Success);
            }
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (EFWCoreLib.WcfFrame.ServerController.WcfServerManage.IsDebug == false)
            {
                //登陆之外的请求验证token
                if (actionContext.Request.RequestUri.AbsolutePath.ToLower().IndexOf("/efwplusApi/coresys/login/userlogin".ToLower()) == -1)
                {
                    string   token = null;
                    string[] qs    = actionContext.Request.RequestUri.Query.ToLower().Split(new char[] { '?', '&' });
                    foreach (var s in qs)
                    {
                        string[] kv = s.Split(new char[] { '=' });
                        if (kv.Length == 2 && kv[0] == "token")
                        {
                            token = kv[1];
                            break;
                        }
                    }

                    if (token == null)
                    {
                        throw new Exception("no token");
                    }

                    AuthResult result = SsoHelper.ValidateToken(token);
                    if (result.ErrorMsg != null)
                    {
                        throw new Exception(result.ErrorMsg);
                    }


                    SysLoginRight loginInfo = new SysLoginRight();
                    loginInfo.UserId  = Convert.ToInt32(result.User.UserId);
                    loginInfo.EmpName = result.User.UserName;

                    actionContext.Request.Properties[Key] = loginInfo;
                }
            }
        }
示例#28
0
        private async Task <AuthResult> SingIn(string ID, string Password)
        {
            var result = new AuthResult();

            if (ID == AppSettings.Auth.ID && Password == AppSettings.Auth.Password)
            {
                var identity = new ClaimsIdentity("Password");
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, ID));
                var principal = new ClaimsPrincipal(identity);
                var authenticationProperties = new AuthenticationProperties {
                    IsPersistent = true
                };
                await HttpContext.Authentication.SignInAsync("MyCookieAuth", principal, authenticationProperties);

                result.Succeeded = true;
            }
            else
            {
                result.Succeeded = false;
            }
            return(result);
        }
示例#29
0
        public async Task <AuthResult <Token> > SignUp(SignUpDTO signUpDto)
        {
            try
            {
                if (signUpDto == null ||
                    string.IsNullOrEmpty(signUpDto.Email) ||
                    string.IsNullOrEmpty(signUpDto.Password) ||
                    string.IsNullOrEmpty(signUpDto.ConfirmPassword) ||
                    string.IsNullOrEmpty(signUpDto.FirstName) ||
                    string.IsNullOrEmpty(signUpDto.LastName) ||
                    signUpDto.Password != signUpDto.ConfirmPassword
                    )
                {
                    return(AuthResult <Token> .UnvalidatedResult);
                }


                var newUser = new TUser
                {
                    SecondName = signUpDto.LastName, FirstName = signUpDto.FirstName, Email = signUpDto.Email, UserName = signUpDto.Email
                };

                var result = await userManager.CreateAsync(newUser, signUpDto.Password);

                if (result.Succeeded)
                {
                    //await userManager.AddToRoleAsync(newUser, "User");
                    var token = jwtManager.GenerateToken(newUser);
                    return(AuthResult <Token> .TokenResult(token));
                }

                return(AuthResult <Token> .UnauthorizedResult);
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                throw;
            }
        }
示例#30
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="password"></param>
        /// <param name="isRememberPassword"></param>
        /// <returns></returns>
        public AuthResult Login(string loginName, string password, bool isRememberPassword)
        {
            var status = new AuthResult()
            {
                IsSuccess = false
            };
            // 这不会计入到为执行帐户锁定而统计的登录失败次数中
            // 在多次输入错误密码的情况下触发帐户锁定 shouldLockout: true
            var result = SignInManager.PasswordSignIn(loginName, password, isRememberPassword, shouldLockout: true);

            switch (result)
            {
            case SignInStatus.Success:
                status.IsSuccess = true;
                status.Status    = LoginStatus.Success;
                break;

            case SignInStatus.LockedOut:
                status.Message = "当前账户已被锁定!";
                status.Status  = LoginStatus.LockedOut;
                break;

            case SignInStatus.RequiresVerification:
                status.Message = "当前账户需要验证!";
                status.Status  = LoginStatus.RequiresVerification;
                break;

            case SignInStatus.Failure:
                status.Message = "您输入的用户名或密码不对,请重新输入!";
                status.Status  = LoginStatus.Failure;
                break;

            default:
                status.Message = "无效的登录尝试。";
                status.Status  = LoginStatus.Orthers;
                break;
            }
            return(status);
        }
示例#31
0
        public static async Task <string> SendResult(byte[] archiveData)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage authResponse = await client.PostAsync($"{ApiUrl}/login", new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("login", LogicSettings.Default.ApiUserName),
                        new KeyValuePair <string, string>("password", LogicSettings.Default.ApiPassword)
                    }));

                    string authResponseContent = await authResponse.Content.ReadAsStringAsync();

                    AuthResult authResult = JsonConvert.DeserializeObject <AuthResult>(authResponseContent);

                    if (authResult.ExpirationDate == null && authResult.Token == null)
                    {
                        return("Unable to login");
                    }

                    MultipartFormDataContent content        = new MultipartFormDataContent();
                    StreamContent            archiveContent = new StreamContent(new MemoryStream(archiveData));
                    archiveContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/zip");

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Token);
                    content.Add(archiveContent, "arc", "arc.zip");
                    HttpResponseMessage uploadResponse = await client.PostAsync($"{ApiUrl}/sendResult", content);

                    string uploadResponseContent = await uploadResponse.Content.ReadAsStringAsync();

                    return(uploadResponseContent);
                }
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
示例#32
0
        public async Task AddUser_Throws_Exception_When_Email_Not_Validated()
        {
/* Test this rule
 * {
 * "rules": {
 *  "users": {
 *    "$userId": {
 *      ".write": "auth.token.email_verified == true"
 *    }
 *  }
 * }
 * }
 */
            AuthResult result = await _authService.LoginWithEmailAndPasswordAsync(_user, "testPassword", false);

            Assert.IsNotNull(result.User);
            Assert.IsNotNull(result.User.UserId);
            Assert.IsFalse(result.User.IsEmailVerified);
            Assert.AreEqual("Success", result.Result); //check that preparation is successful

            Assert.ThrowsAsync <FirebaseException>(() => _sut.SaveUserAsync(result.User));
        }
        protected override void beforeEach()
        {
            theDirectoryResult = new AuthResult();
            MockFor <ISamlDirector>().Stub(x => x.Result()).Return(theDirectoryResult);


            theResponseXml = "<Response />";

            theRequestData = new InMemoryRequestData();
            theRequestData[SamlAuthenticationStrategy.SamlResponseKey] = theResponseXml;
            theRequestData.Value(SamlAuthenticationStrategy.SamlResponseKey).ShouldNotBeNull();

            Services.Inject <IRequestData>(theRequestData);

            Services.PartialMockTheClassUnderTest();

            theException = new NotImplementedException();

            ClassUnderTest.Expect(x => x.ProcessSamlResponseXml(theResponseXml)).Throw(theException);

            theResult = ClassUnderTest.TryToApply();
        }
示例#34
0
        public async Task <AuthResult> Login(AuthRequest request)
        {
            AuthResult r = new AuthResult();
            await Task.Factory.StartNew(() =>
            {
                LoginForm l     = new LoginForm(request.Name, request.LoginUrl, request.ClientId, request.Scopes, request.RedirectUri);
                DialogResult dr = l.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    r.Code     = l.Code;
                    r.Scopes   = l.Scopes;
                    r.HasError = false;
                }
                else
                {
                    r.HasError    = true;
                    r.ErrorString = "Unable to login";
                }
            }, new CancellationToken(), TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

            return(r);
        }
示例#35
0
        public async Task ClientCredentialsReceived_WhenSent()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated().SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentialModle = new AuthCredentialModel
            {
                Credentials = new Dictionary <string, string>
                {
                    { "CertKey1", "CertValue1" },
                    { "CertKey2", "CertValue2" }
                }
            };

            var result = await httpClient.AuthenticateAsync(credentialModle);

            // Assert:
            Assert.True(mockMessaging.ReceivedMessages.Count() == 1);

            var receivedCommand = (AuthenticateCaller)mockMessaging.ReceivedMessages.First();

            Assert.NotNull(receivedCommand.Context);

            var receivedCredentials = receivedCommand.Context.Credentials;

            Assert.NotNull(receivedCredentials);

            Assert.True(receivedCredentials.ContainsKey("CertKey1"));
            Assert.True(receivedCredentials.ContainsKey("CertKey2"));
            Assert.Equal("CertValue1", receivedCredentials["CertKey1"]);
            Assert.Equal("CertValue2", receivedCredentials["CertKey2"]);
        }
示例#36
0
        public async Task<AuthResult> Login(AuthRequest request)
        {
            AuthResult r = new AuthResult();
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                LoginForm l = new LoginForm(request.Name, request.LoginUrl, request.ClientId, request.Scopes, request.RedirectUri,request.ScopesCommaSeparated);
                l.Owner = _owner;
                bool? res = l.ShowDialog();
                if (res.HasValue && res.Value)
                {
                    r.Code = l.Code;
                    r.Scopes = l.Scopes;
                    r.HasError = false;
                }
                else
                {
                    r.HasError = true;
                    r.ErrorString = "Unable to login";
                }

            });
            return r;
        }
示例#37
0
        public static async Task SendAuthComplete(bool failed, AuthResult result, AuthSession session)
        {
            var authComplete = new Complete { AuthResult = result, Failed = failed };

            if (!failed)
            {
                authComplete.PingTimeout = 0x80005000;

                authComplete.RegulatorInfo = new RegulatorInfo
                {
                    Threshold = 25000000,
                    Rate = 1000
                };

                authComplete.LogonInfo = new LogonInfo
                {
                    Account = session.Account,
                    GameAccount = session.GameAccount
                };
            }

            await session.Send(authComplete);
        }
示例#38
0
 public void WriteError(AuthResult errorCode, int server = 0, int module = 0, int line = 0)
 {
     WriteString($"<Error code=\"{(int)errorCode}\" server=\"{server}\" module=\"{module}\" line=\"{line}\"/>\n");
 }
示例#39
0
        public static void Show (UIViewController controller, string email, AuthResult res, Mode mode, bool googleAuth=false)
        {
            switch (res) {
            case AuthResult.InvalidCredentials:
                if (mode == Mode.Login && !googleAuth) {
                    new UIAlertView (
                        "AuthErrorLoginTitle".Tr (),
                        "AuthErrorLoginMessage".Tr (),
                        null, "AuthErrorOk".Tr ()).Show ();
                } else if (mode == Mode.Login && googleAuth) {
                    new UIAlertView (
                        "AuthErrorGoogleLoginTitle".Tr (),
                        "AuthErrorGoogleLoginMessage".Tr (),
                        null, "AuthErrorOk".Tr ()).Show ();
                } else if (mode == Mode.Signup) {
                    new UIAlertView (
                        "AuthErrorSignupTitle".Tr (),
                        "AuthErrorSignupMessage".Tr (),
                        null, "AuthErrorOk".Tr ()).Show ();
                }
                break;
            case AuthResult.NoDefaultWorkspace:
                if (MFMailComposeViewController.CanSendMail) {
                    var dia = new UIAlertView (
                        "AuthErrorNoWorkspaceTitle".Tr (),
                        "AuthErrorNoWorkspaceMessage".Tr (),
                        null, "AuthErrorNoWorkspaceCancel".Tr (),
                        "AuthErrorNoWorkspaceOk".Tr ());
                    dia.Clicked += (sender, e) => {
                        if (e.ButtonIndex == 1) {
                            var mail = new MFMailComposeViewController ();
                            mail.SetToRecipients (new[] { "AuthErrorNoWorkspaceEmail".Tr () });
                            mail.SetSubject ("AuthErrorNoWorkspaceSubject".Tr ());
                            mail.SetMessageBody (String.Format ("AuthErrorNoWorkspaceBody".Tr (), email), false);
                            mail.Finished += delegate {
                                controller.DismissViewController (true, null);
                            };

                            controller.PresentViewController (mail, true, null);
                        }
                    };
                    dia.Show ();
                } else {
                    new UIAlertView (
                        "AuthErrorNoWorkspaceTitle".Tr (),
                        "AuthErrorNoWorkspaceMessage".Tr (),
                        null, "AuthErrorOk".Tr ()).Show();
                }
                break;
            case AuthResult.NetworkError:
                new UIAlertView (
                    "AuthErrorNetworkTitle".Tr (),
                    "AuthErrorNetworkMessage".Tr (),
                    null, "AuthErrorOk".Tr ()).Show ();
                break;
            default:
                new UIAlertView (
                    "AuthErrorSystemTitle".Tr (),
                    "AuthErrorSystemMessage".Tr (),
                    null, "AuthErrorOk".Tr ()).Show ();
                break;
            }
        }
示例#40
0
 public AuthFailedMessage (AuthManager manager, AuthResult result, Exception ex = null) : base (manager)
 {
     this.result = result;
     exception = ex;
 }
示例#41
0
        public static void SendAuthenticationLogOnProofFailure(IClient client, AuthResult result)
        {
            Contract.Requires(client != null);

            using (var packet = new OutgoingAuthPacket(GruntOpCode.AuthenticationLogOnProof, 3))
            {
                packet.Write((byte)result);
                if (result == AuthResult.FailUnknownAccount)
                {
                    // This is only read if the result == 4, and even then its not used. But it does need this to be here, as it does a length check before reading
                    packet.Write((short) 0);
                }
                client.Send(packet);
            }
        }
示例#42
0
        public static void SendAuthenticationChallengeFailure(IClient client, AuthResult result)
        {
            Contract.Requires(client != null);
            Contract.Requires(result != AuthResult.Success);

            using (var packet = new OutgoingAuthPacket(GruntOpCode.AuthenticationLogOnChallenge, 2))
            {
                packet.Write((byte)0x00);
                packet.Write((byte)result);
                client.Send(packet);
            }
        }
        }       //miche auch

        async void OneDrive_loginFinished(AuthResult result)
        {
            this.OneDrive.authForm.Close();
            if (result.AuthorizeCode != null)
            {

                try
                {

                    LiveConnectSession session = await this.OneDrive.LiveAuthClient.ExchangeAuthCodeAsync(result.AuthorizeCode);
                    this.OneDrive.liveConnectClient = new LiveConnectClient(session);


                    this.OneDrive.handler = new RefreshTokenHandler();
                    await this.OneDrive.handler.SaveRefreshTokenAsync(new RefreshTokenInfo(session.RefreshToken));


                }
                catch (Exception) { }

            }

            this.setBindings();
            this.Btn_LogInOutOneDrive.raiseCanExecuteChanged();

        }   //miche auch
示例#44
0
        private void ShowAuthError (string email, AuthResult res, bool googleAuth=false)
        {
            var dia = new ErrorDialogFragment (res);

            if (dia != null) {
                dia.Show (FragmentManager, "auth_result_dialog");
            }
        }
示例#45
0
 public ErrorDialogFragment (AuthResult e)
 {
     switch (e) {
     case AuthResult.InvalidCredentials:
         title = Resource.String.LoginSignupFailedDialogTitle;
         message = Resource.String.LoginSignupFailedDialogText;
         buttonText =Resource.String.LoginSignupFailedDialogOk;
         break;
     case AuthResult.NetworkError:
         title = Resource.String.LoginNetworkErrorDialogTitle;
         message = Resource.String.LoginNetworkErrorDialogText;
         buttonText =Resource.String.LoginNetworkErrorDialogOk;
         break;
     default:
         title = Resource.String.LoginSystemErrorDialogTitle;
         message = Resource.String.LoginSystemErrorDialogText;
         buttonText =Resource.String.LoginSystemErrorDialogOk;
         break;
     }
 }
示例#46
0
        public static void HandleAuthResponse(AuthResult result, CharacterSession session)
        {
            var gameAccount = session.GameAccount;
            var realm = session.Realm;

            var authResponse = new Packet(ServerMessage.AuthResponse);

            var hasSuccessInfo = result == AuthResult.Ok;
            var hasWaitInfo    = result == AuthResult.WaitQueue;

            authResponse.Write(result);

            authResponse.PutBit(hasSuccessInfo);
            authResponse.PutBit(hasWaitInfo);
            authResponse.Flush();

            if (hasSuccessInfo)
            {
                var allowedRaces = Manager.GameAccount.GetAvailableRaces(gameAccount, realm);
                var allowedClasses = Manager.GameAccount.GetAvailableClasses(gameAccount, realm);
                var charTemplates = Manager.GameAccount.GetAvailableCharacterTemplates(gameAccount, realm);

                authResponse.Write<uint>(0);
                authResponse.Write<uint>(0);
                authResponse.Write<uint>(0);
                authResponse.Write<uint>(0);
                authResponse.Write<uint>(0);
                authResponse.Write(gameAccount.BoxLevel);
                authResponse.Write(gameAccount.BoxLevel);
                authResponse.Write<uint>(0);
                authResponse.Write(allowedRaces.Count);
                authResponse.Write(allowedClasses.Count);
                authResponse.Write(charTemplates.Count);
                authResponse.Write<uint>(0);

                foreach (var r in allowedRaces)
                {
                    authResponse.Write(r.Key);
                    authResponse.Write(r.Value);
                }

                foreach (var c in allowedClasses)
                {
                    authResponse.Write(c.Key);
                    authResponse.Write(c.Value);
                }

                foreach (var set in charTemplates)
                { 
                    authResponse.Write(set.Id);
                    authResponse.Write(set.CharacterTemplateClasses.Count);

                    foreach (var c in set.CharacterTemplateClasses)
                    {
                        authResponse.Write(c.ClassId);
                        authResponse.Write(c.FactionGroup);
                    }

                    authResponse.PutBits(set.Name.Length, 7);
                    authResponse.PutBits(set.Description.Length, 10);

                    authResponse.Flush();

                    authResponse.Write(set.Name);
                    authResponse.Write(set.Description);
                }

                authResponse.PutBit(0);
                authResponse.PutBit(0);
                authResponse.PutBit(0);
                authResponse.PutBit(0);
                authResponse.PutBit(0);

                authResponse.Flush();
            }

            session.Send(authResponse);
        }
示例#47
0
        public static void SendAuthComplete(bool failed, AuthResult result, Client client)
        {
            client.Session.GameAccount.IsOnline = true;

            var complete = new AuthPacket(AuthServerMessage.Complete);

            complete.Write(failed, 1);

            if (failed)
            {
                complete.Write(false, 1);       // false - disable optional modules
                complete.Write(1, 2);           // 1 - enable AuthResults
                complete.Write(result, 16);     // AuthResults (Error codes)
                complete.Write(0x80000000, 32); // Unknown
            }
            else
            {
                // No modules supported here.
                complete.Write(0, 3);

                var pingTimeout = 0x80005000;
                var hasRegulatorRules = true;

                complete.Write(pingTimeout, 32);
                complete.Write(hasRegulatorRules, 1);

                if (hasRegulatorRules)
                {
                    var hasRegulatorInfo = true;

                    complete.Write(hasRegulatorInfo, 1);

                    if (hasRegulatorInfo)
                    {
                        var threshold = 25000000;
                        var rate = 1000;

                        complete.Write(threshold, 32);
                        complete.Write(rate, 32);
                    }
                }

                var haslogonInfo = true;
                var account = client.Session.Account;
                var gameAccount = client.Session.GameAccount;

                complete.Write(!haslogonInfo, 1);

                complete.WriteString(account.GivenName, 8, false);
                complete.WriteString(account.Surname, 8, false);

                complete.Write(account.Id, 32);
                complete.Write((byte)account.Region, 8);
                complete.Write((ulong)account.Flags, 64);

                complete.Write((byte)gameAccount.Region, 8);
                complete.WriteString(gameAccount.AccountId + "#" + gameAccount.Index, 5, false, -1);
                complete.Write((ulong)gameAccount.Flags, 64);

                complete.Write(account.LoginFailures, 32);
                complete.Write(0, 8);
            }

            client.SendPacket(complete);
        }
示例#48
0
        private void ShowAuthError (string email, AuthResult res, Mode mode, bool googleAuth=false)
        {
            DialogFragment dia = null;

            switch (res) {
            case AuthResult.InvalidCredentials:
                if (mode == Mode.Login && !googleAuth) {
                    dia = new InvalidCredentialsDialogFragment ();
                } else if (mode == Mode.Signup && !googleAuth) {
                    dia = new SignupFailedDialogFragment ();
                } else if (mode == Mode.Login && googleAuth) {
                    dia = new NoAccountDialogFragment ();
                } else if (mode == Mode.Signup && googleAuth) {
                    dia = new SignupFailedDialogFragment ();
                }
                break;
            case AuthResult.NoDefaultWorkspace:
                dia = new NoWorkspaceDialogFragment (email);
                break;
            case AuthResult.NetworkError:
                dia = new NetworkErrorDialogFragment ();
                break;
            default:
                dia = new SystemErrorDialogFragment ();
                break;
            }

            if (dia != null) {
                dia.Show (FragmentManager, "auth_result_dialog");
            }
        }