public async Task <ActionResult> Login([FromBody] AuthenticationRequest request)
        {
            if (request.Username is null || request.Password is null)
            {
                return(BadRequest());
            }

            request.Username = request.Username.Replace(" ", string.Empty);
            request.Password = request.Password.Replace(" ", string.Empty);

            if (request.Username == string.Empty ||
                request.Password == string.Empty)
            {
                return(BadRequest());
            }

            User user = await context.Users.SingleOrDefaultAsync(x => x.Username == request.Username);

            if (user is null)
            {
                return(StatusCode(StatusCodes.Status404NotFound));
            }

            if (!Util.CompareHash(request.Password, user.PasswordHash))
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }

            return(Ok(auth.Authenticate(request)));
        }
Exemple #2
0
        private async void Login()
        {
//#if DEBUG
//			//TODO: remove this (added to simplify testing
//			Email = "*****@*****.**"; //Derek
//			Password = "******";
//#endif
            if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
            {
                MessagingCenter.Send(this, "InvalidLogin");
                return;
            }
            _userInfoService.SaveUserInfo(new Models.UserInfoModel
            {
                Email        = Email,
                Password     = Password,
                Token        = "",
                LastDownload = ""
            });

            _hudProvider.DisplayProgress(AppResources.WorkingText);

            bool authenticated = await _authManager.Authenticate();

            if (authenticated)
            {
                App.ShowHomeScreen();
            }
            else
            {
                MessagingCenter.Send(this, "InvalidLogin");
            }

            _hudProvider.Dismiss();
        }
        public async Task <ActionResult> Login([FromBody] EmailLoginInfo emailLoginInfo)
        {
            try
            {
                var user = await authenticationManager.Authenticate(emailLoginInfo);

                var sid = await userCookieManager.SetLoginCookie(Response, user);

                logger.LogInformation($"Успешный вход по логин-паролю {emailLoginInfo.Email}. sessionId {sid}");
                return(Json(user));
            }
            catch (AuthenticationFailedException)
            {
                return(Unauthorized());
            }
        }
        public async Task ClickTokenButton()
        {
            bool createResult;

            IsLoading = true;
            try
            {
                // TODO: Create Public/Private Key
                var result = await _authManager.CreateUserDeviceViaEmail(EmailAddress, Token, "test", "Test");

                if (result != null)
                {
                    var accessToken = await _authManager.Authenticate(result.UserDeviceId, result.AccessToken);

                    createResult = accessToken != null;
                }
                else
                {
                    createResult = false;
                }
            }
            catch (Exception ex)
            {
                ChatDebugger.SendMessageDialogAsync(ex.Message, ex);
                createResult = false;
            }
            IsLoading = false;
            RaiseEvent(createResult ? UserCreatedSuccessful : UserCreatedFailed, EventArgs.Empty);
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
            {
                return(AuthenticateResult.Fail("Missing Authorization Header"));
            }

            try
            {
                var authHeader      = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
                var password        = credentials[1];
                var userName        = credentials[0];

                var userPrincipal = await _authenticationManager.Authenticate(userName, password);

                if (userPrincipal == null)
                {
                    return(AuthenticateResult.Fail("Invalid Username or Password"));
                }

                var ticket = new AuthenticationTicket(userPrincipal, Scheme.Name);

                return(AuthenticateResult.Success(ticket));
            }
            catch
            {
                return(AuthenticateResult.Fail("Invalid Authorization Header"));
            }
        }
Exemple #6
0
        public async Task Invoke(HttpContext context)
        {
            if (FilterNonXhrRequest(context))
            {
                return;
            }

            if (context.Session.Get <EmployeDto>(LoggedEmployeKey) == null)
            {
                var basicAuthenticationHeader = GetBasicAuthenticationHeaderValue(context);
                if (basicAuthenticationHeader.IsValidBasicAuthenticationHeaderValue)
                {
                    try
                    {
                        EmployeBaseDto loggedEmploye = _authenticationManager.Authenticate(context, basicAuthenticationHeader.UserIdentifier, basicAuthenticationHeader.UserPassword);
                        context.Session.Set(LoggedEmployeKey, loggedEmploye);
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e.StackTrace);
                        SetUnauthorizedHeader(context);
                        return;
                    }
                }
                else
                {
                    SetUnauthorizedHeader(context);
                    return;
                }
            }
            await _next.Invoke(context);
        }
Exemple #7
0
        public IActionResult Login([FromBody] LoginDto user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid client request"));
            }

            if (_authenticationManager.Authenticate(user.Username, user.Password))
            {
                var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["jwt:secretKey"]));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokenOptions = new JwtSecurityToken(
                    issuer: _config["jwt:issuer"],
                    audience: _config["jwt:audience"],
                    claims: new List <Claim>(),
                    expires: DateTime.Now.AddMinutes(5),
                    signingCredentials: signinCredentials
                    );

                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
                return(Ok(tokenString));
            }
            else
            {
                return(Unauthorized());
            }
        }
        public async Task <IActionResult> Login(LoginRequest loginRequest)
        {
            // Returns error if username or password are null
            if (loginRequest.Username == null || loginRequest.Password == null)
            {
                return(BadRequest("Username and password must not be null"));
            }

            // Attempts to create token, returns error if login details are incorrect
            Result <string> tokenResult = await _manager.Authenticate(loginRequest.Username, loginRequest.Password);

            if (tokenResult.Failure)
            {
                return(BadRequest(tokenResult.Error));
            }

            // Creates and returns response
            LoginResponse response = new LoginResponse()
            {
                Token      = tokenResult.Value,
                ValidUntil = DateTime.Now.AddMonths(1)
            };

            return(Json(response));
        }
Exemple #9
0
        public async Task <IActionResult> Login([FromBody] UserVM userParam)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ErrorMessageVM()
                {
                    Message = "Entered data is incorrect!"
                }));
            }
            else
            {
                var user = await _authenticationManager.Authenticate(userParam.Email, userParam.Password);

                if (user != null)
                {
                    return(Ok(new { token = _authenticationManager.BuildToken(user) }));
                }
                else
                {
                    return(BadRequest(new ErrorMessageVM()
                    {
                        Message = "Either Username or password is inccorect!"
                    }));
                }
            }
        }
Exemple #10
0
        public async Task <ActionResult> IsValidUser(string userName, string password)
        {
            if ((await _authenticationManager.Authenticate(userName, password)) == null)
            {
                return(Forbid());
            }

            return(Ok());
        }
        public IActionResult Authenticate([FromBody] AuthenticateModel model)
        {
            var user = _manager.Authenticate(model.Username, model.Password);

            if (user == null)
            {
                return(Unauthorized());
            }
            return(Ok(user));
        }
Exemple #12
0
        public IActionResult AuthenticateUser([FromBody] User user)
        {
            var token = manager.Authenticate(user);

            if (token == null)
            {
                return(Unauthorized());
            }
            return(Ok(token));
        }
        public IActionResult Authenticate([FromBody] UserCredentials userCredentials)
        {
            var token = _authenticationManager.Authenticate(userCredentials.Username, userCredentials.Password);

            if (token == null)
            {
                return(Unauthorized()); // if incorrect username or password.
            }
            return(Ok(token));
        }
Exemple #14
0
        public async Task <IActionResult> Login([FromBody] string password)
        {
            User admin = await context.Users.FindAsync(1);

            bool setPassword = admin.PasswordHash == "null";

            if (string.IsNullOrEmpty(password))
            {
                return(BadRequest());
            }

            if (setPassword)
            {
                if (password.Length < 5)
                {
                    return(BadRequest());
                }

                admin.PasswordHash = Util.Hash(password);

                context.Entry(admin).State = EntityState.Modified;
                await context.SaveChangesAsync();
            }

            if (!Util.CompareHash(password, admin.PasswordHash))
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }

            CookieBuilder authCookieBuilder = new()
            {
                IsEssential = true,
                SameSite    = SameSiteMode.Strict,
                Expiration  = new TimeSpan(8, 0, 0)
            };

            var    authCookieOptions = authCookieBuilder.Build(HttpContext);
            string token             = auth.Authenticate(admin).Token;

            Response.Cookies.Append("AdminAuthorization", token, authCookieOptions);

            return(Ok());
        }
        public IActionResult Login([FromBody] AuthenticateRequest request)
        {
            var response = _authenticationManager.Authenticate(request);

            if (!response.IsSuccess)
            {
                return(Problem(title: response.Message, statusCode: response.StatusCode));
            }
            return(Ok(response));
        }
Exemple #16
0
        public async Task <IActionResult> Authenticate([FromBody] LoginDto loginDto)
        {
            var jwtToken = await _authenticationManager.Authenticate(loginDto);

            if (jwtToken == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(Ok(jwtToken));
        }
        public IActionResult AuthenticateUser([FromBody] LoginDetails loginDetails)
        {
            _log4net.Info(" Http Authentication request Initiated");
            var token = manager.Authenticate(loginDetails.Username, loginDetails.Password, loginDetails.LoginType);

            if (token == null)
            {
                return(Unauthorized());
            }
            return(Ok(token));
        }
Exemple #18
0
        public IActionResult AuthenticateUser([FromBody] Userdetails details)
        {
            _log4net.Info("Http Authentication Login request Initiated");
            var token = manager.Authenticate(details.Email, details.Password);

            if (token == null)
            {
                return(Unauthorized());
            }
            return(Ok(token));
        }
        public IActionResult AuthenticateUser([FromBody] Register user)
        {
            _log4net.Info(" Http Authentication request Initiated");
            var token = manager.Authenticate(user.EmailId, user.Password);

            if (token == null)
            {
                return(Unauthorized());
            }
            return(Ok(token));
        }
Exemple #20
0
        public IActionResult AuthenticateUser([FromBody] UserServiceInfo user)
        {
            // _log4net.Info(" Http Authentication request Initiated");
            var token = manager.Authenticate(user.Phoneno, user.Password);

            if (token == null)
            {
                return(Unauthorized());
            }
            return(Ok(token));
        }
        public ActionResult Authenciate([FromBody] UCredential uCred)
        {
            var token = _authManager.Authenticate(uCred.Username, uCred.Password);

            if (token == null)
            {
                Unauthorized();
            }

            return(Ok(token));
        }
        public TicketModel Post([FromBody] ApiFormInput formData)
        {
            if (formData == null)
            {
                return(new TicketModel
                {
                    Errors = ApiHelper.JsonError(400, new[] { "User credentials are incomplete" })
                });
            }

            if (string.IsNullOrWhiteSpace(formData.username) && string.IsNullOrWhiteSpace(formData.password))
            {
                return(new TicketModel
                {
                    Errors = ApiHelper.JsonError(400, new[] { "Invalid login or password" })
                });
            }

            if (!_authenticationManager.Authenticate(formData.username, formData.password, out var authToken, out var refreshToken))
            {
                return(new TicketModel
                {
                    Errors = ApiHelper.JsonError(400, new[] { "Invalid login or password" })
                });
            }

            var resulTicketModel = new TicketModel {
                Token = authToken, RefreshToken = refreshToken
            };

            var server = string.IsNullOrEmpty(formData.server) ? "localhost" : formData.server;

            SVNManager.Authorizate(server, formData.username, formData.password, _ => { });

            return(resulTicketModel);
        }
        private Dictionary <string, object> GetUserClaims(string user, string password)
        {
            string userName   = GetUserName(user);
            string domainName = GetDomainName(user);

            Dictionary <string, object> userMetaData = new Dictionary <string, object>();

            userMetaData.Add("user", userName);
            userMetaData.Add("domainName", domainName);
            userMetaData.Add("userName", userName);
            userMetaData.Add("environment", EnvironmentName);
            userMetaData.Add("isAuthenticated", false);
            userMetaData.Add("isAuthorized", false);

            if (!AuthenticationManager.Authenticate(userName, password, domainName))
            {
                return(userMetaData);
            }
            userMetaData["isAuthenticated"] = true;

            UserIdentity userIdentity = AuthorizationManager.GetUserIdentity(userName, domainName, EnvironmentName, MarkelConfiguration.ApplicationName);

            if (!EnvironmentName.Equals(userIdentity?.EnvironmentName))
            {
                throw new Exception("User Identity does not match requested environment!");
            }
            if (userIdentity == null)
            {
                return(userMetaData);
            }

            // Successful Authentication
            userMetaData["isAuthorized"] = true;
            userMetaData.Add("application", userIdentity.ApplicationName);
            userMetaData.Add("applicationVersion", IOHelper.GetServerVersion());
            userMetaData.Add("authTokenDate", userIdentity.AuthenticatedOn.ToString());
            userMetaData.Add("authToken", userIdentity.AuthenticationToken.ToString());
            userMetaData.Add("authTokenExpireDate", userIdentity.AuthenticationTokenExpiration.ToString());
            userMetaData.Add("ermsHome", userIdentity.GetPath("ErmsHome"));
            userMetaData.Add("serviceAccount", userIdentity.IsServiceAccount.ToString());
            // this better match: userMetaData.Add("userName", userIdentity.UserName);
            foreach (var permission in userIdentity.Permissions.Where(p => p.Value == true))
            {
                userMetaData.Add(permission.Key, permission.Value.ToString());
            }

            return(userMetaData);
        }
        private UserIdentity userIdentity;  // mp... 02/27/2019 - move up

        #endregion Constants

        #region Auth Managers

        private Dictionary <string, object> GetUserClaims(string user, string password, bool isTrustedServer)
        {
            string userName   = GetUserName(user);
            string domainName = GetDomainName(user);

            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new UnauthorizedAccessException("User Name is required for Authentication!");
            }

            Dictionary <string, object> userMetaData = new Dictionary <string, object>();

            userMetaData.Add("user", userName);
            userMetaData.Add("domainName", domainName);
            userMetaData.Add("userName", userName);
            userMetaData.Add("environment", EnvironmentName);
            userMetaData.Add("isAuthenticated", false);
            userMetaData.Add("isAuthorized", false);

            if (!isTrustedServer && !AuthenticationManager.Authenticate(userName, password, domainName))
            {
                return(userMetaData);
            }
            userMetaData["isAuthenticated"] = true;

            userIdentity = AuthorizationManager.GetUserIdentity(userName, domainName, EnvironmentName, MarkelConfiguration.ApplicationName);

            if (!EnvironmentName.Equals(userIdentity?.EnvironmentName))
            {
                throw new Exception("User Identity does not match requested environment!");
            }
            if (userIdentity == null)
            {
                return(userMetaData);
            }

            // Successful Authentication
            userMetaData["isAuthorized"] = true;
            userMetaData.Add("application", userIdentity.ApplicationName);
            userMetaData.Add("applicationVersion", IOHelper.GetServerVersion());

            foreach (var permission in userIdentity.Permissions.Where(p => p.Value == true))
            {
                userMetaData.Add(permission.Key, permission.Value.ToString());
            }

            return(userMetaData);
        }
        public async Task ClickLoginButton()
        {
            bool loginResult;

            IsLoading = true;
            try
            {
                loginResult = await _authManager.Authenticate(UserName, Password);
            }
            catch (LoginFailedException)
            {
                // TODO: The failure message should be bubbled up to the user; this is a different scenario than login failing due to bad credentials, and they should know that
                loginResult = false;
            }
            IsLoading = false;
            base.RaiseEvent(loginResult ? LoginSuccessful : LoginFailed, EventArgs.Empty);
        }
Exemple #26
0
        public async Task ClickLoginButton()
        {
            bool loginResult;

            IsLoading = true;
            try
            {
                loginResult = await _authManager.Authenticate(UserName, Password);
            }
            catch (LoginFailedException ex)
            {
                AwfulDebugger.SendMessageDialogAsync(ex.Message, ex);
                loginResult = false;
            }
            IsLoading = false;
            base.RaiseEvent(loginResult ? LoginSuccessful : LoginFailed, EventArgs.Empty);
        }
Exemple #27
0
        public IActionResult AuthenticateUser([FromBody] Userdetails details)
        {
            _log4net.Info("Http Authentication Login request Initiated");
            var token = manager.Authenticate(details.Username, details.Password);

            if (token == null)
            {
                return(Unauthorized());
            }
            TokenAndUserId tokenanduserid = new TokenAndUserId
            {
                UserId = manager.GetUserid(details.Username),
                Token  = token
            };

            return(Ok(tokenanduserid));
        }
        public ActionResult <User> Authenticate(UserCred userCred)
        {
            User user = userService.GetUserByEmail(userCred.Email);

            if (user.IdentityVerificationCode != null)
            {
                return(Forbid());
            }
            else if (user.SignInRetries == 3)
            {
                string verificationCode = NewVerificationCode;
                user.IdentityVerificationCode = verificationCode;
                userService.Update(user.Id, user);

                var link = GetVerificationLink(
                    VerificationType.Identity,
                    user.Email,
                    verificationCode);

                authenticationManager.SendVerificationEmail(
                    VerificationType.Identity,
                    link,
                    user.Email);

                return(Forbid());
            }
            var token = authenticationManager.Authenticate(userCred, user);

            if (token == null)
            {
                user.SignInRetries += 1;
                userService.Update(user.Id, user);
                return(Unauthorized());
            }
            if (!user.EmailConfirmed)
            {
                return(NoContent());
            }
            else if (user.SignInRetries > 0)
            {
                user.SignInRetries = 0;
                userService.Update(user.Id, user);
            }
            return(Ok(token));
        }
        public async Task <IActionResult> Authenticate([FromBody] Authentication request)
        {
            try
            {
                AuthenticateResponse response = await authenticationManager.Authenticate(request);

                if (response == null)
                {
                    return(NotFound(new { message = "Username or password is incorrect" }));
                }

                return(Ok(response));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Exemple #30
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var authenticated = await authenticationManager.Authenticate(context.UserName, context.Password);

            if (!authenticated)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);
        }