Пример #1
0
        public void SendPrivate(long userId, string message)
        {
            log.LogInformation("Send message to {0}", userId);
            var authentication = auth.Authenticate();

            Auth.ExecuteOperationWithCredentials(
                authentication,
                () => { Message.PublishMessage("Messages Rocks around here!", userId); });
        }
Пример #2
0
        public async Task <string> GetCalls(string token)
        {
            Console.WriteLine(".. GetCallsFromPremise .. " + DateTime.Now);


            string result      = string.Empty;
            var    beginPeriod = await GetSyncStartTime();

            var endPeriod = DateTime.UtcNow;

            DynamicQueryRequest requestBody = new DynamicQueryRequest
            {
                Period = new Period
                {
                    BeginPeriod = beginPeriod,
                    EndPeriod   = endPeriod,
                }
            };

            if (string.IsNullOrEmpty(_authentication.Token))
            {
                await _authentication.Authenticate();
            }

            var _apiClient = _httpClientFactory.CreateClient("recorder");

            _apiClient.DefaultRequestHeaders.Add("Impact360AuthToken", _authentication.Token);

            var response = await _apiClient.PostAsJsonAsync <DynamicQueryRequest>("/DASWebAPI/Query/ExecuteDynamicQuery", requestBody);

            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                AuthToken authToken = await _authentication.Authenticate();

                token = authToken.token;
                return(await GetCalls(token));
            }

            response.EnsureSuccessStatusCode();

            result = await response.Content.ReadAsStringAsync();

            Console.WriteLine(".. RetrivedCallsFromPremise .. " + DateTime.Now);

            await UpdateState(requestBody);

            return(result);
        }
Пример #3
0
        public async Task <IActionResult> Signin(LoginViewModel model)
        {
            //validate that the provided username is registered on the app
            var user = await userManager.FindByNameAsync(model.username);

            if (user != null)
            {
                var result = await signInManager.PasswordSignInAsync(user, model.Password, isPersistent : true, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    var response = _authentication.Authenticate(Guid.Parse(user.Id), user.Email, user.UserName);
                    if (response == null)
                    {
                        return(BadRequest(new { message = "Username or password is incorrect" }));
                    }


                    //get the user role
                    string userRole = await GetUserRole(user);

                    return(Ok(new { User = response, role = userRole }));
                }
                return(BadRequest("Sorry Username and password do not match"));
            }
            return(BadRequest(new { message = "Sorry the username provide is not registered on this platform" }));
        }
Пример #4
0
 public async Task Setup()
 {
     _message         = new MessageProviderFake();
     _physicalFactory = new PhysicalFactoryFake();
     _auth            = new UnattendedAuthentication(_message, TestContext.Parameters["ClientId"], TestContext.Parameters["ClientSecret"], TestContext.Parameters["Username"], TestContext.Parameters["Password"]);
     await _auth.Authenticate();
 }
Пример #5
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            //ako je stanje modela validno
            //ModelState je Dictionary objekat cija definicija se nalazi u klasi osnove a koju nasledjuje ovaj kontroler
            if (ModelState.IsValid)
            {
                //ako su uneti username i sifra tacni odnosno postoje u bazi
                if (authentication.Authenticate(model.UserName, model.Password))
                {
                    //setujemo kuki koji cuva username od administratora na koriscenom browseru
                    FormsAuthentication.SetAuthCookie(model.UserName, false);

                    //vracamo ka browseru View koji se nalazi pod adresom 'Admin/Index'
                    return(Redirect(returnUrl ?? Url.Action("Index", "Admin")));
                }

                //ako uneti username i sifra nisu tacni odnosno ne postoje u bazi
                else
                {
                    //dodajemo poruku o gresci  u stanje modela
                    ModelState.AddModelError("", "Incorrect username or password");

                    //vracamo ka browseru view za logovanje
                    return(View());
                }
            }

            //ako stanje modela nije validno
            else
            {
                //vracamo ka browseru view za logovanje
                return(View());
            }
        }
Пример #6
0
        public async Task <string> AcquireToken()
        {
            var token = await cache.GetToken(client_id, client_secret, audience, async() =>
            {
                var info = await GetApiInfo();

                AccessToken t;
                try
                {
                    t = await auth.Authenticate(client_id, client_secret, audience, info.Auth.Authority);
                }
                catch (HttpRequestException ex)
                {
                    throw new AuthenticationException(ex);
                }

                return(t);
            });

            if (String.IsNullOrWhiteSpace(token?.Value))
            {
                return(null);
            }

            return(token.Value);
        }
 static void Main(string[] args)
 {
     for (; true;)
     {
         Console.SetCursorPosition((Console.WindowWidth - StringLiterals.WelcomeMsg.Length) / 2, Console.CursorTop);
         Console.WriteLine(StringLiterals.WelcomeMsg);
         Console.Write(StringLiterals.UserNameLabel);
         string username = Console.ReadLine();
         Console.Write(StringLiterals.PasswordLabel);
         string          password = Console.ReadLine();
         IAuthentication obj      = BALFactory.GetAuthenticationObject();
         if (obj.Authenticate(new AuthModel()
         {
             Email = username, Password = password
         }))
         {
             Console.WriteLine(StringLiterals.LoginSuccessMsg);
             IBookModule  bookOp  = BALFactory.GetBookModuleObject();
             OperationsUI driveUI = new OperationsUI();
             driveUI.StartPoint(bookOp, username);
         }
         else
         {
             Console.WriteLine(StringLiterals.InvalidCredentialsMsg);
         }
         Thread.Sleep(1000);
         Console.Clear();
     }
 }
Пример #8
0
        protected override Task Execute(CancellationToken token)
        {
            log.LogInformation("Starting twitter monitoring...");
            var keywords = string.IsNullOrEmpty(config.Topics) ? new string[] { } : config.Topics.Split(',');

            if (config.Topics.Length == 0)
            {
                throw new NotSupportedException("Invalid selection");
            }

            var discovery = discoveryFactory(new DiscoveryRequest(keywords));
            var cred      = auth.Authenticate();

            using (var streamWriter = new StreamWriter(config.Out, true, new UTF8Encoding(false)))
                using (var csvDataTarget = new CsvWriter(streamWriter))
                {
                    Auth.ExecuteOperationWithCredentials(
                        cred,
                        () =>
                    {
                        foreach (var item in discovery.Process())
                        {
                            csvDataTarget.WriteField(item.Message.Id);
                            csvDataTarget.WriteField(item.Message.Text);
                            csvDataTarget.NextRecord();
                            streamWriter.Flush();
                        }
                    });
                }

            return(Task.CompletedTask);
        }
        public static Credential Login(IAuthentication authentication, ICredentialProvider credentialProvider, string identity, string password, string @namespace, bool isRemember, out string redirectUrl)
        {
            if (authentication == null)
            {
                throw new ArgumentNullException("authentication");
            }

            if (credentialProvider == null)
            {
                throw new ArgumentNullException("credentialProvider");
            }

            //进行身份验证(即验证身份标识和密码是否匹配)
            var result = authentication.Authenticate(identity, password, @namespace);

            //注册用户凭证
            var credential = credentialProvider.Register(result.User, AuthenticationUtility.GetScene(), (result.HasParameters ? result.Parameters : null));

            //将注册成功的用户凭证保存到Cookie中
            AuthenticationUtility.SetCredentialCookie(credential, isRemember ? TimeSpan.FromDays(7) : TimeSpan.Zero);

            object redirectObject = null;

            //如果验证事件中显式指定了返回的URL,则使用它所指定的值
            if (result.HasParameters && result.Parameters.TryGetValue("RedirectUrl", out redirectObject) && redirectObject != null)
            {
                redirectUrl = redirectObject.ToString();
            }
            else             //返回重定向的路径中
            {
                redirectUrl = AuthenticationUtility.GetRedirectUrl(credential.Scene);
            }

            return(credential);
        }
        public void ValidWildCardLoginReturnsSessionToken()
        {
            IAuthentication wildcardMock = mocks.DynamicMock <IAuthentication>();

            SetupResult.For(wildcardMock.Identifier).Return("*doe");
            manager.Users = new IAuthentication[] {
                wildcardMock
            };

            LoginRequest credentials = new LoginRequest("johndoe");

            Expect.Call(wildcardMock.Authenticate(credentials)).Return(true);
            Expect.Call(wildcardMock.GetUserName(credentials)).Return("johndoe");
            Expect.Call(wildcardMock.GetDisplayName(credentials)).Return("johndoe");
            Expect.Call(sessionMock.AddToCache("johndoe")).Return(testSessionToken);
            Expect.Call(delegate { sessionMock.StoreSessionValue(string.Empty, string.Empty, string.Empty); })
            .IgnoreArguments();

            mocks.ReplayAll();
            manager.Initialise();

            string sessionToken = manager.Login(credentials);

            Assert.AreEqual(testSessionToken, sessionToken);
        }
Пример #11
0
        /// <summary>
        /// Logs on with specified authentication method.
        /// </summary>
        /// <param name="authentication">The authentication method.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">
        /// Already logged on
        /// or
        /// Another unfinished log on/off request exists.
        /// </exception>
        /// <exception cref="System.Exception">Null user info is not allowed</exception>
        public async Task LogOn(IAuthentication authentication)
        {
            if (UserInfo != null)
            {
                throw new InvalidOperationException("Already logged on");
            }
            if (Interlocked.CompareExchange(ref IsWorking, 1, 0) == 0)
            {
                try
                {
                    var result = await authentication.Authenticate();

                    if (result == null)
                    {
                        throw new Exception("Null user info is not allowed");
                    }
                    UserInfo = result;
                    ServerConnection.AccessToken = UserInfo.AccessToken;
                    return;
                }
                finally
                {
                    Interlocked.CompareExchange(ref IsWorking, 0, 1);
                }
            }
            throw new InvalidOperationException("Another unfinished log on/off request exists.");
        }
Пример #12
0
        protected override Task Execute(CancellationToken token)
        {
            log.LogInformation("Downloading message...");
            var downloadMessages = File.ReadLines(config.Ids).Select(long.Parse).ToArray();

            log.LogInformation("Total messages to download: {0}", downloadMessages.Length);
            var cred      = auth.Authenticate();
            var extractor = new MessageCleanup();
            var monitor   = new PerformanceMonitor(downloadMessages.Length);

            using (var streamWriter = new StreamWriter(config.Out, false, new UTF8Encoding(false)))
                using (var csvDataTarget = new CsvWriter(streamWriter))
                {
                    csvDataTarget.WriteField("Id");
                    csvDataTarget.WriteField("Date");
                    csvDataTarget.WriteField("Author");
                    csvDataTarget.WriteField("Message");
                    csvDataTarget.NextRecord();

                    Auth.ExecuteOperationWithCredentials(
                        cred,
                        () =>
                    {
                        using (Observable.Interval(TimeSpan.FromSeconds(30)).Subscribe(item => log.LogInformation(monitor.ToString())))
                        {
                            downloader.Download(downloadMessages)
                            .ToObservable()
                            .Select(
                                item =>
                            {
                                try
                                {
                                    csvDataTarget.WriteField(item.Id);
                                    csvDataTarget.WriteField(item.CreatedAt);
                                    csvDataTarget.WriteField(item.CreatedBy.Id);
                                    var text = item.Text;
                                    if (config.Clean)
                                    {
                                        text = extractor.Cleanup(text);
                                    }

                                    csvDataTarget.WriteField(text);
                                    csvDataTarget.NextRecord();
                                    monitor.Increment();
                                }
                                catch (Exception e)
                                {
                                    log.LogError(e, "Error");
                                }

                                return(item);
                            })
                            .LastOrDefaultAsync()
                            .Wait();
                        }
                    });
                }

            return(Task.CompletedTask);
        }
Пример #13
0
 public ActionResult Login(LoginViewModel model, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         if (_authentication.Authenticate(model.UserName, model.Password))
         {
             FormsAuthentication.SetAuthCookie(model.UserName, false);
             if (string.IsNullOrEmpty(returnUrl))
             {
                 return(RedirectToAction("Index", "Admin", null));
             }
             else
             {
                 return(RedirectToAction("List", "Products", null));
             }
         }
         else
         {
             ModelState.AddModelError("", "Incorrect User Name or Password");
         }
     }
     else
     {
         return(View());
     }
     return(View());
 }
Пример #14
0
 public ActionResult Login(LoginViewModel model, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         if (authProvider.Authenticate(model.UserName, model.Password))
         {
             if (authProvider.IsAdmin(model.UserName, model.Password))
             {
                 FormsAuthentication.SetAuthCookie(model.UserName, false);
                 return(Redirect(returnUrl ?? Url.Action("Index", "Admin")));
             }
             FormsAuthentication.SetAuthCookie(model.UserName, false);
             return(Redirect(returnUrl ?? Url.Action("Index", "Home")));
         }
         else
         {
             TempData["errorMessage"] = string.Format("Incorrect username or password");
             ModelState.AddModelError("", "Incorrect username or password");
             return(View());
         }
     }
     else
     {
         TempData["errorMessage"] = string.Format("Ivalid username");
         return(View());
     }
 }
        public ConfigurationValidator(IAuthentication cred, Credentials credentials)
        {
            if (cred == null)
            {
                throw new ArgumentNullException(nameof(cred));
            }

            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            var twitterCredentials = cred.Authenticate();

            if (string.IsNullOrWhiteSpace(twitterCredentials.AccessToken) ||
                string.IsNullOrWhiteSpace(twitterCredentials.AccessTokenSecret))
            {
                throw new ArgumentNullException("Access token not found");
            }

            if (string.IsNullOrWhiteSpace(credentials.QuandlKey))
            {
                throw new ArgumentNullException("QuandlKey not found");
            }
        }
Пример #16
0
        /// <summary>
        /// Logs on with specified authentication method.
        /// </summary>
        /// <param name="authentication">The authentication method.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">
        /// Already logged on
        /// or
        /// Another unfinished log on/off request exists.
        /// </exception>
        /// <exception cref="System.Exception">Null user info is not allowed</exception>
        public async Task LogOn(IAuthentication authentication)
        {

            if (UserInfo != null)
            {
                throw new InvalidOperationException("Already logged on");
            }
            if (Interlocked.CompareExchange(ref IsWorking, 1, 0) == 0)
            {
                try
                {
                    var result = await authentication.Authenticate();
                    if (result == null)
                    {
                        throw new Exception("Null user info is not allowed");
                    }
                    UserInfo = result;
                    ServerConnection.AccessToken = UserInfo.AccessToken;
                    return;
                }
                finally
                {
                    Interlocked.CompareExchange(ref IsWorking, 0, 1);
                }
            }
            throw new InvalidOperationException("Another unfinished log on/off request exists.");
        }
Пример #17
0
        /// <summary>
        /// Changes the password of the user.
        /// </summary>
        /// <param name="sessionToken">The session token for the current user.</param>
        /// <param name="oldPassword">The person's old password.</param>
        /// <param name="newPassword">The person's new password.</param>
        public override void ChangePassword(string sessionToken, string oldPassword, string newPassword)
        {
            // Retrieve the user
            string userName = GetUserName(sessionToken);

            if (string.IsNullOrEmpty(userName))
            {
                throw new SessionInvalidException();
            }
            IAuthentication user = RetrieveUser(userName);

            if (user == null)
            {
                throw new SessionInvalidException();
            }

            // Validate the old password
            LoginRequest credientals = new LoginRequest(userName);

            credientals.AddCredential(LoginRequest.PasswordCredential, oldPassword);
            if (!user.Authenticate(credientals))
            {
                LogEvent(null, userName, SecurityEvent.ChangePassword, SecurityRight.Deny, "Old password is incorrect");
                throw new SecurityException("Old password is incorrect");
            }

            // Change the password
            LogEvent(null, userName, SecurityEvent.ChangePassword, SecurityRight.Allow, null);
            user.ChangePassword(newPassword);

            // Update the file
            UpdateSetting(user);
        }
Пример #18
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                int result = authentication.Authenticate(model.UserName, model.Password);
                if (result == 1)

                {
                    Session["LogedInUser"] = model.UserName;

                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    return(Redirect(returnUrl ?? Url.Action("Index", "Admin")));
                }
                else if (result == 2)
                {
                    Session["LogedInUser"] = model.UserName;

                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    return(Redirect(returnUrl ?? Url.Action("List", "Product")));
                }

                else
                {
                    ModelState.AddModelError("", "Incorrect username or password");
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }
        public void ValidLoginReturnsSessionToken()
        {
            LoginRequest credentials = new LoginRequest("johndoe");

            Expect.Call(authenticationMock.Authenticate(credentials)).Return(true);
            Expect.Call(authenticationMock.GetUserName(credentials)).Return("johndoe");
            Expect.Call(authenticationMock.GetDisplayName(credentials)).Return("johndoe");
            Expect.Call(sessionMock.AddToCache("johndoe")).Return(testSessionToken);
            Expect.Call(delegate { sessionMock.StoreSessionValue(string.Empty, string.Empty, string.Empty); })
            .IgnoreArguments();

            mocks.ReplayAll();
            manager.Initialise();

            string sessionToken = manager.Login(credentials);

            Assert.AreEqual(testSessionToken, sessionToken);
        }
Пример #20
0
        public ActionResult Login([FromForm] AuthenticateRequest model)
        {
            var response = _authService.Authenticate(model);

            if (!response.Item1)
            {
                return(BadRequest(new { message = response.Item2.ToString() }));
            }
            return(Ok(response.Item2));
        }
Пример #21
0
        /// <summary>
        /// Authenticate user. if successful then save user inforation
        /// </summary>
        /// <param name="context">http context</param>
        /// <param name="signin">singin information</param>
        public UserInfo Signin(HttpContextBase context, SigninModel signin)
        {
            Expect.IsNotNull(context, nameof(context));
            Expect.IsNotNull(signin, nameof(signin));

            var user = _authentication.Authenticate(signin);

            FormsSignin(signin);
            context.Session[USER_KEY] = user;
            return(user);
        }
Пример #22
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                int UserStatusId = authentication.Authenticate(model.Email, model.Password);
                if (UserStatusId < 3)
                {
                    Session["MyKey"] = UserStatusId;
                    User user = repository.Users.FirstOrDefault(u => u.Email == model.Email);
                    Session["MyId"] = user.UserId;
                    Session["Name"] = user.UserName;
                    email           = model.Email;
                }
                if (UserStatusId == 1) //1 means admin
                {
                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    if (!Roles.RoleExists("1"))
                    {
                        Roles.CreateRole("1");
                    }

                    if (!Roles.IsUserInRole(model.Email, "1"))
                    {
                        Roles.AddUserToRole(model.Email, "1");
                    }
                    return(Redirect(returnUrl ?? Url.Action("Index", "Admin")));
                }
                else if (UserStatusId == 0) // 0 means customer
                {
                    if (Roles.IsUserInRole(email, "1"))
                    {
                        Roles.RemoveUserFromRole(email, "1");
                    }
                    FormsAuthentication.SetAuthCookie(model.Email, false);

                    return(Redirect(returnUrl ?? Url.Action("Index", "Home")));
                }
                else if (UserStatusId == 2)
                {
                    ModelState.AddModelError("", "Your account has been deactivated. Please contact our Customer Services for help ");
                    return(View());
                }
                else
                {
                    ModelState.AddModelError("", "Incorect userhname or password ");
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }
Пример #23
0
        public IActionResult Post([FromBody] Login Model)
        {
            var user = _authenticateService.Authenticate(Model);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or Password is incorrect" }));
            }
            else
            {
                return(Ok(user));
            }
        }
Пример #24
0
        public async Task Start()
        {
            log.LogInformation("Starting user stream");
            var authenticate = auth.Authenticate();

            stream = Stream.CreateUserStream(authenticate);
            await stream.StartStreamAsync().ConfigureAwait(false);

            stream.MessageReceived += (sender, args) =>
            {
                received.OnNext(args.Message);
            };
        }
Пример #25
0
        protected override Task Execute(CancellationToken token)
        {
            log.LogInformation("Starting twitter monitoring...");
            SetupWords();
            RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
            var cleanup = new MessageCleanup();
            var monitor = new PerformanceMonitor(100000);
            var cred    = auth.Authenticate();

            using (Observable.Interval(TimeSpan.FromSeconds(30)).Subscribe(item => log.LogInformation(monitor.ToString())))
                using (var streamWriter = new StreamWriter(config.Out, true, new UTF8Encoding(false)))
                    using (var csvDataTarget = new CsvWriter(streamWriter))
                    {
                        Auth.ExecuteOperationWithCredentials(
                            cred,
                            () =>
                        {
                            var enrichments = Enrichment().ToArray();
                            foreach (var enrichment in enrichments)
                            {
                                enrichment.Discovery.BatchSize = 5;
                                enrichment.Discovery.AddProcessed(enrichments.SelectMany(p => p.Discovery.Processed).ToArray());
                                enrichment.Discovery.Process()
                                .ToObservable()
                                .ObserveOn(TaskPoolScheduler.Default)
                                .Select(
                                    x =>
                                {
                                    var text = cleanup.Cleanup(x.Message.Text).Replace("\r\n", " ");
                                    if (!CanInclude(text, enrichment.Type))
                                    {
                                        return(x);
                                    }

                                    text = Regex.Replace(text, @"[^\u0000-\u007F]+", string.Empty);
                                    csvDataTarget.WriteField(x.Message.Id);
                                    csvDataTarget.WriteField(x.Topic);
                                    csvDataTarget.WriteField(enrichment.Type);
                                    csvDataTarget.WriteField(text);
                                    csvDataTarget.NextRecord();
                                    streamWriter.Flush();
                                    monitor.Increment();
                                    return(x);
                                })
                                .Wait();
                            }
                        });
                    }

            return(Task.CompletedTask);
        }
Пример #26
0
        public async Task <T> Authenticate()
        {
            if (File.Exists(AuthFile))
            {
                log.LogInformation("Found saved credentials. Loading...");
                var json = File.ReadAllText(AuthFile);
                return(await Refresh(JsonConvert.DeserializeObject <T>(json)).ConfigureAwait(false));
            }

            T credentials = await underlying.Authenticate().ConfigureAwait(false);

            Save(credentials);
            return(credentials);
        }
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            var result = await _authentication.Authenticate(model.Email, model.Senha);

            if (result)
            {
                return(Redirect("/"));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Login Inválido");
                return(View(model));
            }
        }
Пример #28
0
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            var result = await _iauthentication.Authenticate(model.EMAIL, model.PASSWORD);

            if (result)
            {
                return(RedirectToAction("Index", "Dashboard"));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Login Invalido.");
                return(View(model));
            }
        }
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            var result = await _authentication.Authenticate(model.Email, model.Password);

            if (result)
            {
                return(Redirect("/"));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(View(model));
            }
        }
Пример #30
0
        public IActionResult Login(LoginViewModel account)
        {
            var result = _authentication.Authenticate(account.Login, account.Password).Result;

            if (result)
            {
                return(Redirect("/"));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(View(account));
            }
        }
Пример #31
0
        public async Task <ActionResult <LoginResultDto> > Login(LoginDto dto)
        {
            try
            {
                var resultDto = await _authentication.Authenticate(dto.Username, dto.Password);

                await ZZApiMain.AddUserConnection(resultDto);

                return(resultDto);
            }
            catch (Exception e)
            {
                ConsoleEx.WriteError(e);
                return(NotFound());
            }
        }
Пример #32
0
		public static Credential Login(IAuthentication authentication, ICredentialProvider credentialProvider, string identity, string password, string @namespace, bool isRemember, out string redirectUrl)
		{
			if(authentication == null)
				throw new ArgumentNullException("authentication");

			if(credentialProvider == null)
				throw new ArgumentNullException("credentialProvider");

			//进行身份验证(即验证身份标识和密码是否匹配)
			var result = authentication.Authenticate(identity, password, @namespace);

			//注册用户凭证
			var credential = credentialProvider.Register(result.User, AuthenticationUtility.GetScene(), (result.HasExtendedProperties ? result.ExtendedProperties : null));

			//将注册成功的用户凭证保存到Cookie中
			AuthenticationUtility.SetCredentialCookie(credential, isRemember ? TimeSpan.FromDays(7) : TimeSpan.Zero);

			object redirectObject = null;

			//如果验证事件中显式指定了返回的URL,则使用它所指定的值
			if(result.HasExtendedProperties && result.ExtendedProperties.TryGetValue("RedirectUrl", out redirectObject) && redirectObject != null)
				redirectUrl = redirectObject.ToString();
			else //返回重定向的路径中
				redirectUrl = AuthenticationUtility.GetRedirectUrl(credential.Scene);

			return credential;
		}