Ejemplo n.º 1
0
        /// <summary>
        /// Asynchronously executes the specified request.
        /// </summary>
        public async Task <T> ExecuteAsync <T>(Func <Task <T> > attempt)
            where T : class
        {
            if (_mainSettings.Session == null)
            {
                var tokenResponse = await _authenticationService.GetTokenAsync();

                if (tokenResponse.Status == AuthenticationStatus.Success &&
                    await _authenticator.AuthenticateAsync(_credentials.UserName, _credentials.Password, tokenResponse.Token))
                {
                    var sessionRequest = new SessionRequest
                    {
                        TequilaToken = tokenResponse.Token,
                        RememberMe   = _mainSettings.SessionStatus == SessionStatus.LoggedIn
                    };
                    var sessionResponse = await _authenticationService.GetSessionAsync(sessionRequest);

                    if (sessionResponse.Status == AuthenticationStatus.Success)
                    {
                        _mainSettings.Session = sessionResponse.Session;
                    }
                }
                else
                {
                    _mainSettings.SessionStatus = SessionStatus.NotLoggedIn;
                    return(null);
                }
            }

            return(await attempt());
        }
Ejemplo n.º 2
0
        private async Task ExecuteClientRequestAsync(string jsonRequest, Func <ClientRequest, IClientProxy, Task> func)
        {
            var clientRequest = JsonConvert.DeserializeObject <ClientRequest>(jsonRequest, _jsonSerializerSettings);

            if (clientRequest == null || clientRequest.SessionId == Guid.Empty)
            {
                await RespondMalformedRequestAsync().ConfigureAwait(false);

                return;
            }

            Console.WriteLine($"Incoming request: Name: '{clientRequest.RequestName}'. SessionId: '{clientRequest.SessionId}' Payload: '{clientRequest.Payload}'");

            var connectionId = Context.ConnectionId;
            var proxyClient  = Clients.Client(connectionId);
            var success      = await _authenticator.AuthenticateAsync(clientRequest.UserId, clientRequest.SessionId).ConfigureAwait(false);

            if (success)
            {
                _connectionUserRegistry.RegisterOrUpdate(connectionId, clientRequest.UserId);

                await func.Invoke(clientRequest, proxyClient).ConfigureAwait(false);
                await RespondRequestAcceptedAsync().ConfigureAwait(false);
            }
            else
            {
                await RespondNotAuthenticatedAsync().ConfigureAwait(false);
            }
        }
Ejemplo n.º 3
0
        internal async Task <T> Create()
        {
            string authenticationToken = await _authn.AuthenticateAsync();

            return(Create(new AuthenticationOptions {
                AuthenticationToken = authenticationToken, Uri = _uri
            }));
        }
Ejemplo n.º 4
0
        internal async Task OpenAsync(CancellationToken cancellationToken)
        {
            logger.Debug("Open Session");

            if (authenticator == null)
            {
                authenticator = new BasicAuthenticator(this);
            }

            await authenticator.AuthenticateAsync(cancellationToken);
        }
 public async Task SkillPingAsync()
 {
     if (_credentialProvider != null && !await _credentialProvider.IsAuthenticationDisabledAsync().ConfigureAwait(false))
     {
         await _authenticator.AuthenticateAsync(Request, Response).ConfigureAwait(false);
     }
     else
     {
         Response.StatusCode = (int)HttpStatusCode.OK;
     }
 }
        internal async Task OpenAsync(CancellationToken cancellationToken)
        {
            logger.Debug("Open Session");

            if (authenticator == null)
            {
                authenticator = AuthenticatorFactory.GetAuthenticator(this);
            }

            await authenticator.AuthenticateAsync(cancellationToken).ConfigureAwait(false);
        }
Ejemplo n.º 7
0
            static async Task <FailoverDecision> AuthorizationErrorsFailover(RequestTimeouts timeouts, IAuthenticator authProvider, IHttpResponse response, uint attempt)
            {
                switch (attempt)
                {
                case 0 when response.Status.IsUnauthorized:
                    await authProvider.AuthenticateAsync(true, timeouts.DefaultReadTimeout).ConfigureAwait(false);

                    return(FailoverDecision.RepeatRequest);

                default:
                    return(FailoverDecision.LetItFail);
                }
            }
Ejemplo n.º 8
0
        public async Task <IActionResult> Token([FromBody] Client.Auth.TokenCreationInfo tokenCreationInfo,
                                                CancellationToken cancellationToken)
        {
            string encodedJwt;

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

            return(Ok(encodedJwt));
        }
Ejemplo n.º 9
0
    private async Task GenerateToken(JwtParams jwtParams)
    {
        var authResult = await _authenticator.AuthenticateAsync(jwtParams);

        if (authResult == null || !authResult.Success)
        {
            await ResponseErrorAsync(authResult?.Message);

            return;
        }

        var jwtResult = await _provider.GenerateToken(authResult.Claims);

        jwtResult.UserInfo = authResult.UserInfo;

        await ResponseSuccessAsync(jwtResult);
    }
Ejemplo n.º 10
0
        public async Task InvokeAsync(HttpContext context)
        {
            var    authInfo = context.Request.Headers.GetCommaSeparatedValues("Authorization");
            string userName = null;
            string password = null;

            if (authInfo.Length == 0)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync(ServiceErrorCodes.Unauthorized);
            }

            var loginInfo = authInfo[0].Split(" ");

            if (loginInfo.Length != 2)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync(ServiceErrorCodes.Unauthorized);
            }

            var base64String    = loginInfo[1];
            var decodedByteData = Convert.FromBase64String(base64String);
            var decodedInfo     = System.Text.Encoding.UTF8.GetString(decodedByteData).Split(":");

            userName = decodedInfo[0];
            password = decodedInfo[1];

            //TODO мне не нравится эта штука
            authenticator = (IAuthenticator)context.RequestServices.GetService(typeof(IAuthenticator));

            try
            {
                var user = await authenticator.AuthenticateAsync(userName, password, CancellationToken.None);

                context.Items.Add("userId", user.Id);
            }
            catch (AuthenticationException)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync(ServiceErrorCodes.InvalidCredentials);
            }

            await next.Invoke(context);
        }
Ejemplo n.º 11
0
        public LoginPageViewModel(IAuthenticator authenticator, IAzureInitializer azureInitializer,
                                  IUserService userService)
        {
            _authenticator = authenticator;
            _userService   = userService;

            IsEnabled    = true;
            LoginCommand = new Command(async() =>
            {
                try
                {
                    IsEnabled          = false;
                    IsIndicatorRunning = true;
                    var isAuth         = false;
                    if (!string.IsNullOrEmpty(Password) && !string.IsNullOrEmpty(UserName))
                    {
                        isAuth = await authenticator.AuthenticateAsync(new LoginObject()
                        {
                            Password = this.Password, UserName = this.UserName
                        });
                    }

                    if (!isAuth)
                    {
                        IsEnabled          = true;
                        IsIndicatorRunning = false;
                        return;
                    }

                    await azureInitializer.SyncClientAndStore();

                    App.UserName = UserName;

                    NavigationHelper.NavigateToHomePage();
                }
                catch (Exception ex)
                {
                    ex.ToString();
                    throw;
                }
            });
        }
        public async Task <IHttpActionResult> Authenticate(string username, string password)
        {
            try
            {
                _logger.WriteLog(LogLevel.Information, "User attempting to login");
                var authentication = await _authenticator.AuthenticateAsync(username, password);

                return(Ok(authentication));
            }
            catch (UnauthorizedAccessException)
            {
                _logger.WriteLog(LogLevel.Error, $"Failed attempt to login for {username}");
                return(StatusCode(HttpStatusCode.Unauthorized));
            }
            catch (Exception e)
            {
                _logger.WriteLog(LogLevel.Error, "Exception occured in AuthenticationController.Authenticate", e.Message, e.StackTrace);
                return(StatusCode(HttpStatusCode.Conflict));
            }
        }
Ejemplo n.º 13
0
        public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

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

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

            if (!httpRequest.HttpContext.WebSockets.IsWebSocketRequest)
            {
                httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                await httpResponse.WriteAsync("Upgrade to WebSocket required.").ConfigureAwait(false);

                return;
            }

            ClaimsIdentity claims;

            // only perform auth when it's enabled
            if (_credentialProvider != null && !await _credentialProvider.IsAuthenticationDisabledAsync().ConfigureAwait(false))
            {
                claims = await _authenticator.AuthenticateAsync(httpRequest, httpResponse).ConfigureAwait(false);
            }
            else
            {
                claims = new ClaimsIdentity(new List <Claim>(), "anonymous");
            }

            await CreateWebSocketConnectionAsync(claims, httpRequest.HttpContext, bot).ConfigureAwait(false);
        }
Ejemplo n.º 14
0
        private async Task <HttpRequestMessage> CreateRequest(string endPoint, HttpMethod method, DateTime?modifiedSince = null, string accept = "application/json", HttpContent content = null, string query = null)
        {
            if (!string.IsNullOrWhiteSpace(query))
            {
                endPoint = string.Format("{0}?{1}", endPoint, query);
            }

            var uri = new Uri(_baseUri, endPoint);

            var request = new HttpRequestMessage(method, uri)
            {
                Content = content
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));

            if (modifiedSince.HasValue)
            {
                request.Headers.IfModifiedSince = modifiedSince;
            }

            if (_auth != null)
            {
                await _auth.AuthenticateAsync(request, _consumer, _user).ConfigureAwait(false);
            }

            var escapedUserAgent = Uri.EscapeDataString("Xero-NetStandard - " + _consumer.ConsumerKey);

            request.Headers.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue(escapedUserAgent)));

            if (!string.IsNullOrWhiteSpace(UserAgent))
            {
                var escapedCustomUserAgent = Uri.EscapeDataString(UserAgent);
                request.Headers.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue(escapedCustomUserAgent)));
            }

            return(request);
        }
Ejemplo n.º 15
0
        public async Task <ActionResult <string> > AuthenticateAsync(
            [FromBody] AuthenticationRequest request,
            [FromServices] IUnitOfWork unitOfWork)
        {
            using var scope =
                      _log.BeginScope("Begin authentication for user with email: {Email}", request.Email);
            try
            {
                var token = await _authenticator.AuthenticateAsync(unitOfWork, request.Email, request.Password);

                return(Ok(token));
            }
            catch (UserNotFoundException)
            {
                _log.LogWarning("Failed to find user with email: {Email}", request.Email);
                return(Forbid());
            }
            catch (IncorrectPasswordException)
            {
                _log.LogWarning("Password is incorrect");
                return(Forbid());
            }
        }
        public static async Task <Request> AuthenticateRequestAsync(this IAuthenticator authenticator, Request request, bool force, TimeSpan timeout)
        {
            var authenticationResult = await authenticator.AuthenticateAsync(force, timeout).ConfigureAwait(false);

            return(authenticationResult.Apply(request));
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            if (button != "login")
            {
                // the user clicked the "cancel" button
                var context = await idsService.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await idsService.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var loginInfo = new LoginInfo {
                    Username = model.Username,
                    Password = model.Password
                };
                var user = await authenticator.AuthenticateAsync(loginInfo);

                if (user != null)
                {
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    await HttpContext.SignInAsync(user.UserId.ToString(), user.Username, props);

                    var returnUrl = model.ReturnUrl;
                    logger.LogInformation($"Return URL: {returnUrl}");
                    if (idsService.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }

                    return(Redirect("~/"));
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await _account.BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Ejemplo n.º 18
0
        internal async Task <T> Create()
        {
            string authenticationToken = await _authenticator.AuthenticateAsync();

            return(Create(new AuthenticationOptions(_uri, authenticationToken)));
        }