示例#1
0
        public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            var username = context.UserName;
            var password = context.Password;
            var message = context.SignInMessage;

            if (message != null)
            {
                var tenant = message.Tenant;

                if (username == password)
                {
                    var claims = new List<Claim>
                    {
                        new Claim("account_store", tenant)
                    };

                    var result = new AuthenticateResult("123", username,
                        claims: claims,
                        authenticationMethod: "custom");

                    context.AuthenticateResult = new AuthenticateResult("123", username, claims);
                }
            }

            return Task.FromResult(0);
        }
        public async Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            var signInData = Mapper.Map<SignInMessage, SignInData>(context.SignInMessage);
            var result = await domainService.AuthenticateLocalAsync(context.UserName, context.Password, signInData);

            context.AuthenticateResult = Mapper.Map<AuthenticationResult, AuthenticateResult>(result);
        }
        public async Task<CustomGrantValidationResult> ValidateAsync(ValidatedTokenRequest request)
        {
            var legacyAccountStoreType = request.Raw.Get("account_store");
            var id = request.Raw.Get("legacy_id");
            var secret = request.Raw.Get("legacy_secret");

            if (string.IsNullOrWhiteSpace(legacyAccountStoreType) ||
                string.IsNullOrWhiteSpace(id) ||
                string.IsNullOrWhiteSpace(secret))
            {
                Logger.Error("malformed request");
                return null;
            }

            var message = new SignInMessage { Tenant = legacyAccountStoreType };
            var context = new LocalAuthenticationContext
            {
                UserName = id, Password = secret,
                SignInMessage = message
            };
            await _users.AuthenticateLocalAsync(context);

            var result = context.AuthenticateResult;
            if (result.IsError)
            {
                Logger.Error("authentication failed");
                return new CustomGrantValidationResult("Authentication failed.");
            }

            return new CustomGrantValidationResult(
                result.User.GetSubjectId(),
                "custom",
                result.User.Claims);
        }
示例#4
0
        public override async Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            var form = await ctx.Request.ReadFormAsync();
            var extra = form["extra"];

            await base.AuthenticateLocalAsync(context);
        }
示例#5
0
        public override Task AuthenticateLocalAsync(IdentityServer3.Core.Models.LocalAuthenticationContext context)
        {
            //var user = userRepository.GetUser(context.UserName, context.Password);

            // 1Q7v1oV7OXIn9Q1kgXayb2KYTjzO64mfxWV2N5K6szjmfNf77NPmyWCD5ZMALkj1VD/VKv8yOZvszDjrE7WXDg==
            var encryptedPassword = HashHelper.Sha512(context.UserName + context.Password);

            var user = _userManager.Users
                       .FirstOrDefault(u => u.UserName == context.UserName &&
                                       u.Password == encryptedPassword);

            if (user == null)
            {
                context.AuthenticateResult = new AuthenticateResult("Invalid credentials");
                return(Task.FromResult(0));
            }

            context.AuthenticateResult = new AuthenticateResult(
                //user.Subject,
                user.Id,
                //user.UserClaims.First(c => c.ClaimType == Constants.ClaimTypes.GivenName).ClaimValue);
                user.Claims.First(c => c.ClaimType == IdentityServer3.Core.Constants.ClaimTypes.GivenName).ClaimValue);

            return(Task.FromResult(0));
        }
        public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            //TODO  RO FLOW to Azure AD Tenant, see unit tests for prototype.
            

            return base.AuthenticateLocalAsync(context);
        }
        public Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            if (context.UserName == "*****@*****.**" && context.Password == "secret")
            {
                context.AuthenticateResult = new AuthenticateResult("robink", "Robin van der Knaap");
            }

            return Task.FromResult(0);
        }
        public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            var user = Users.SingleOrDefault(x => x.Username == context.UserName && x.Password == context.Password);
            if (user != null)
            {
                context.AuthenticateResult = new AuthenticateResult(user.Subject, user.Username);
            }

            return Task.FromResult(0);
        }
 public async Task AuthenticateLocalAsync(LocalAuthenticationContext context)
 {
     context.AuthenticateResult = null;
     foreach (var service in this.services)
     {
         await service.AuthenticateLocalAsync(context);
         if (context.AuthenticateResult != null && !context.AuthenticateResult.IsError)
         {
             return;
         }
     }
 }
        public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            string username = context.UserName;
            string password = context.Password;

            InMemoryUser _user = Users.Get().Where(u => u.Username == username && u.Password == password).SingleOrDefault();

            if (_user != null)
            {
                context.AuthenticateResult = new AuthenticateResult(subject: _user.Subject, name: username);
            }

            return Task.FromResult(0);
        }
示例#11
0
        public Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            if (context.UserName == context.Password)
            {
                var p = IdentityServerPrincipal.Create(context.UserName, context.UserName, "password", "idsvr");
                context.AuthenticateResult = new AuthenticateResult(p);
            }
            else
            {
                context.AuthenticateResult = new AuthenticateResult("Username and/or password incorrect");
            }

            return Task.FromResult(0);
        }
		/// <summary>
		/// This methods gets called for local authentication (whenever the user uses the username and password dialog).
		/// </summary>
		/// <param name="context">The context.</param>
		/// <returns></returns>
		public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
		{
			var query =
				from u in _users
				where u.Username == context.UserName && u.Password == context.Password
				select u;

			var user = query.SingleOrDefault();
			if (user != null)
			{
				context.AuthenticateResult = new AuthenticateResult(user.Subject, GetDisplayName(user));
			}

			return Task.FromResult(0);
		}
        /// <summary>
        /// This method gets called for local authentication (whenever the user uses the username
        /// and password dialog).
        /// </summary>
        /// <param name="context">The authentication context.</param>
        /// <returns>A "null" result</returns>
        public Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            _log.Debug("User Database Connection String");
            _log.Debug(Settings.Default.UserDatabase);
            _log.Debug("User Query");
            _log.Debug(Settings.Default.UserQuery);

            using (var connection = new SqlConnection(Settings.Default.UserDatabase))
            {
                connection.Open();

                var command = new SqlCommand(Settings.Default.UserQuery, connection);

                var userParameter = new SqlParameter
                {
                    ParameterName = "@USER",
                    Value = context.UserName
                };

                var passwordParameter = new SqlParameter
                {
                    ParameterName = "@PASS",
                    Value = context.Password
                };

                command.Parameters.Add(userParameter);
                command.Parameters.Add(passwordParameter);

                var reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();

                    var nameIdentifier = (string)reader[0];

                    context.AuthenticateResult = new AuthenticateResult(
                        nameIdentifier,
                        context.UserName,
                        new List<Claim> { _databaseClaim },
                        "Database");
                }

                connection.Close();

                return Task.FromResult(0);
            }
        }
        public override async Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            var userName = context.UserName;
            var password = context.Password;

            using (var client = new HttpClient { BaseAddress = new Uri(this.usersApiUri) })
            using (var postResult = await client.PostAsync($"/api/users/{userName}/authenticate", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("password", password) })))
            {

                if (postResult.IsSuccessStatusCode)
                {
                    var claims = await GetClaimsAsync(client, userName, Enumerable.Empty<string>());
                    context.AuthenticateResult = new AuthenticateResult(userName, GetDisplayName(claims) ?? userName, claims);
                }
                else
                {
                    context.AuthenticateResult = new AuthenticateResult($"Could not sign in user {context.UserName}: received status code {postResult.StatusCode}");
                }
            }
        }
示例#15
0
        public override Task AuthenticateLocalAsync(IdentityServer3.Core.Models.LocalAuthenticationContext context)
        {
            using (var userRepository = new UserRepository())
            {
                // get user from repository
                var user = userRepository.GetUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.AuthenticateResult = new AuthenticateResult("Invalid credentials");
                    return(Task.FromResult(0));
                }

                context.AuthenticateResult = new AuthenticateResult(
                    user.Subject,
                    user.UserClaims.First(c => c.ClaimType == Constants.ClaimTypes.GivenName).ClaimValue);

                return(Task.FromResult(0));
            }
        }
示例#16
0
        public async Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            if (!this.userManager.SupportsUserPassword)
            {
                // log.ErrorFormat("User '{0}' tries to authenticate, but SupportsUserPassword is set to false on UserManager", context.UserName);
                return;
            }

            var user = await this.userManager.FindByNameAsync(context.UserName);
            if (user == null)
            {
                // log.WarnFormat("User '{0}' tries to authenticate but was not found", context.UserName);
                return;
            }

            if (this.userManager.SupportsUserLockout && await this.userManager.IsLockedOutAsync(user.Id))
            {
                // log.WarnFormat("User '{0}' tries to authenticate but is locked out", context.UserName);
                return;
            }
            if (!await this.userManager.CheckPasswordAsync(user, context.Password))
            {
                if (this.userManager.SupportsUserLockout)
                {
                    // log.WarnFormat("User '{0}' tries to log in with wrong password '{1}'", context.UserName, context.Password);
                    await this.userManager.AccessFailedAsync(user.Id);
                }

                return;
            }

            if (this.userManager.SupportsUserLockout)
                await this.userManager.ResetAccessFailedCountAsync(user.Id);

            var claims = await this.GetClaimsForAuthenticateResultAsync(user);
            var name = await this.GetDisplayNameForAccountAsync(user);
            context.AuthenticateResult = new AuthenticateResult(
                subject: user.Id.ToString(),
                name: name,
                claims: claims);
        }
        private async Task<TokenRequestValidationResult> ValidateResourceOwnerCredentialRequestAsync(NameValueCollection parameters)
        {
            Logger.Info("Start password token request validation");

            // if we've disabled local authentication, then fail
            if (_options.AuthenticationOptions.EnableLocalLogin == false ||
                _validatedRequest.Client.EnableLocalLogin == false)
            {
                LogError("EnableLocalLogin is disabled, failing with UnsupportedGrantType");
                return Invalid(Constants.TokenErrors.UnsupportedGrantType);
            }

            /////////////////////////////////////////////
            // check if client is authorized for grant type
            /////////////////////////////////////////////
            if (_validatedRequest.Client.Flow != Flows.ResourceOwner)
            {
                LogError("Client not authorized for resource owner flow");
                return Invalid(Constants.TokenErrors.UnauthorizedClient);
            }

            /////////////////////////////////////////////
            // check if client is allowed to request scopes
            /////////////////////////////////////////////
            if (!(await ValidateRequestedScopesAsync(parameters)))
            {
                LogError("Invalid scopes.");
                return Invalid(Constants.TokenErrors.InvalidScope);
            }

            /////////////////////////////////////////////
            // check resource owner credentials
            /////////////////////////////////////////////
            var userName = parameters.Get(Constants.TokenRequest.UserName);
            var password = parameters.Get(Constants.TokenRequest.Password);

            if (userName.IsMissing() || password.IsMissing())
            {
                LogError("Username or password missing.");
                return Invalid(Constants.TokenErrors.InvalidGrant);
            }

            if (userName.Length > _options.InputLengthRestrictions.UserName ||
                password.Length > _options.InputLengthRestrictions.Password)
            {
                LogError("Username or password too long.");
                return Invalid(Constants.TokenErrors.InvalidGrant);
            }

            _validatedRequest.UserName = userName;

            /////////////////////////////////////////////
            // check optional parameters and populate SignInMessage
            /////////////////////////////////////////////
            var signInMessage = new SignInMessage();

            // pass through client_id
            signInMessage.ClientId = _validatedRequest.Client.ClientId;

            // process acr values
            var acr = parameters.Get(Constants.AuthorizeRequest.AcrValues);
            if (acr.IsPresent())
            {
                if (acr.Length > _options.InputLengthRestrictions.AcrValues)
                {
                    LogError("Acr values too long.");
                    return Invalid(Constants.TokenErrors.InvalidRequest);
                }

                var acrValues = acr.FromSpaceSeparatedString().Distinct().ToList();

                // look for well-known acr value -- idp
                var idp = acrValues.FirstOrDefault(x => x.StartsWith(Constants.KnownAcrValues.HomeRealm));
                if (idp.IsPresent())
                {
                    signInMessage.IdP = idp.Substring(Constants.KnownAcrValues.HomeRealm.Length);
                    acrValues.Remove(idp);
                }

                // look for well-known acr value -- tenant
                var tenant = acrValues.FirstOrDefault(x => x.StartsWith(Constants.KnownAcrValues.Tenant));
                if (tenant.IsPresent())
                {
                    signInMessage.Tenant = tenant.Substring(Constants.KnownAcrValues.Tenant.Length);
                    acrValues.Remove(tenant);
                }

                // pass through any remaining acr values
                if (acrValues.Any())
                {
                    signInMessage.AcrValues = acrValues;
                }
            }

            _validatedRequest.SignInMessage = signInMessage;

            /////////////////////////////////////////////
            // authenticate user
            /////////////////////////////////////////////
            var authenticationContext = new LocalAuthenticationContext
            {
                UserName = userName,
                Password = password,
                SignInMessage = signInMessage
            };

            await _users.AuthenticateLocalAsync(authenticationContext);
            var authnResult = authenticationContext.AuthenticateResult;

            if (authnResult == null || authnResult.IsError || authnResult.IsPartialSignIn)
            {
                var error = Resources.Messages.InvalidUsernameOrPassword;
                if (authnResult != null && authnResult.IsError)
                {
                    error = authnResult.ErrorMessage;
                }
                if (authnResult != null && authnResult.IsPartialSignIn)
                {
                    error = "Partial signin returned from AuthenticateLocalAsync";
                }
                LogError("User authentication failed: " + error);
                await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, signInMessage, error);

                if (authnResult != null)
                {
                    return Invalid(Constants.TokenErrors.InvalidGrant, authnResult.ErrorMessage);
                }

                return Invalid(Constants.TokenErrors.InvalidGrant);
            }

            _validatedRequest.UserName = userName;
            _validatedRequest.Subject = authnResult.User;

            await RaiseSuccessfulResourceOwnerAuthenticationEventAsync(userName, authnResult.User.GetSubjectId(), signInMessage);
            Logger.Info("Password token request validation success.");
            return Valid();
        }
示例#18
0
 public async Task AuthenticateLocalAsync(LocalAuthenticationContext context)
 {
     await this.inMemoryUserService.AuthenticateLocalAsync(context);
 }
示例#19
0
        public override async Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            var user = await _userRepository
                .GetUserAsync(context.UserName, context.Password);

            context.AuthenticateResult = user == null
                ? new AuthenticateResult("Invalid credentials")
                : new AuthenticateResult(user.Subject, user.UserName);
        }
        public async Task<IHttpActionResult> LoginLocal(string signin, LoginCredentials model)
        {
            Logger.Info("Login page submitted");

            if (this.options.AuthenticationOptions.EnableLocalLogin == false)
            {
                Logger.Warn("EnableLocalLogin disabled -- returning 405 MethodNotAllowed");
                return StatusCode(HttpStatusCode.MethodNotAllowed);
            }

            if (signin.IsMissing())
            {
                Logger.Info("No signin id passed");
                return HandleNoSignin();
            }

            if (signin.Length > MaxSignInMessageLength)
            {
                Logger.Error("Signin parameter passed was larger than max length");
                return RenderErrorPage();
            }
            
            var signInMessage = signInMessageCookie.Read(signin);
            if (signInMessage == null)
            {
                Logger.Info("No cookie matching signin id found");
                return HandleNoSignin();
            }

            if (!(await IsLocalLoginAllowedForClient(signInMessage)))
            {
                Logger.ErrorFormat("Login not allowed for client {0}", signInMessage.ClientId);
                return RenderErrorPage();
            }

            if (model == null)
            {
                Logger.Error("no data submitted");
                return await RenderLoginPage(signInMessage, signin, localizationService.GetMessage(MessageIds.InvalidUsernameOrPassword));
            }

            if (String.IsNullOrWhiteSpace(model.Username))
            {
                ModelState.AddModelError("Username", localizationService.GetMessage(MessageIds.UsernameRequired));
            }
            
            if (String.IsNullOrWhiteSpace(model.Password))
            {
                ModelState.AddModelError("Password", localizationService.GetMessage(MessageIds.PasswordRequired));
            }

            model.RememberMe = options.AuthenticationOptions.CookieOptions.CalculateRememberMeFromUserInput(model.RememberMe);

            if (!ModelState.IsValid)
            {
                Logger.Warn("validation error: username or password missing");
                return await RenderLoginPage(signInMessage, signin, ModelState.GetError(), model.Username, model.RememberMe == true);
            }

            if (model.Username.Length > options.InputLengthRestrictions.UserName || model.Password.Length > options.InputLengthRestrictions.Password)
            {
                Logger.Error("username or password submitted beyond allowed length");
                return await RenderLoginPage(signInMessage, signin);
            }

            var authenticationContext = new LocalAuthenticationContext
            {
                UserName = model.Username,
                Password = model.Password,
                SignInMessage = signInMessage
            };

            await userService.AuthenticateLocalAsync(authenticationContext);
            
            var authResult = authenticationContext.AuthenticateResult;
            if (authResult == null)
            {
                Logger.WarnFormat("user service indicated incorrect username or password for username: {0}", model.Username);
                
                var errorMessage = localizationService.GetMessage(MessageIds.InvalidUsernameOrPassword);
                await eventService.RaiseLocalLoginFailureEventAsync(model.Username, signin, signInMessage, errorMessage);
                
                return await RenderLoginPage(signInMessage, signin, errorMessage, model.Username, model.RememberMe == true);
            }

            if (authResult.IsError)
            {
                Logger.WarnFormat("user service returned an error message: {0}", authResult.ErrorMessage);

                await eventService.RaiseLocalLoginFailureEventAsync(model.Username, signin, signInMessage, authResult.ErrorMessage);
                
                return await RenderLoginPage(signInMessage, signin, authResult.ErrorMessage, model.Username, model.RememberMe == true);
            }

            Logger.Info("Login credentials successfully validated by user service");

            await eventService.RaiseLocalLoginSuccessEventAsync(model.Username, signin, signInMessage, authResult);

            lastUserNameCookie.SetValue(model.Username);

            return await SignInAndRedirectAsync(signInMessage, signin, authResult, model.RememberMe);
        }
 /// <summary>
 /// This method gets called for local authentication (whenever the user uses the username and password dialog).
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 public virtual Task AuthenticateLocalAsync(LocalAuthenticationContext context)
 {
     return Task.FromResult(0);
 }
 public Task AuthenticateLocalAsync(LocalAuthenticationContext context)
 {
     return inner.AuthenticateLocalAsync(context);
 }
示例#23
0
 /// <summary>
 /// Authentication Account with AD
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
 {
     var username = context.UserName;
     var password = context.Password;
     var message = context.SignInMessage;
     try
     {
         if (ValidateCredentials(username, password))
         {
             using (var user = GetUser(username))
             {
                 if (user != null)
                 {
                     if (!user.IsAccountLockedOut())
                     {
                         //DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry;
                         //string ou = deUser.Properties["distinguishedName"].Value.ToString();
                         context.AuthenticateResult = new AuthenticateResult(username, username, GetDisplayNameForAccountAsync(user));
                     }
                     else
                     {
                         //use is lock on AD
                         return Task.FromResult(0);
                     }
                 }
             }
         }
         // The user name or password is incorrect
         return Task.FromResult(0);
     }
     catch(Exception ex)
     {
         // Server error
         return Task.FromResult(0);
     }
 }