Ejemplo n.º 1
0
        public static IActionResult GetSignalRInfo(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "signalrInfo/{hubName}")] HttpRequest req,
            string hubName,
            IBinder binder,
            ILogger log
            )
        {
            try
            {
                var principal = AuthUtilities.ResolveClaimsPrincipal(req);

                var info = binder.Bind <SignalRConnectionInfo>(new SignalRConnectionInfoAttribute
                {
                    HubName = hubName,
                    UserId  = principal.Identity.Name
                });

                return(new OkObjectResult(info));
            }
            catch (Exception e)
            {
                var error = $"GetSignalRInfo failed: {e.Message}";

                log.LogError(error);

                return(new BadRequestObjectResult(error));
            }
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> Authenticate(UserLogin user)
        {
            try
            {
                if (user != null)
                {
                    var result = await _context.Account.Where(p => p.EmailAddress == user.username).SingleOrDefaultAsync();

                    if (AuthUtilities.HashPassword(user.password) == result.HashedPassword)
                    {
                        result.Logins++;
                        _context.Account.Update(result);
                        await _context.SaveChangesAsync();

                        return(Ok("You are authenticated!"));
                    }
                    else
                    {
                        return(BadRequest("You've entered the wrong username and or password."));
                    }
                }
                return(BadRequest("Invalid request."));
            }
            catch (System.Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Ejemplo n.º 3
0
        public async Task <ActionResult <IUser> > Login([FromBody] User payload)
        {
            try
            {
                var newUser = await _userService.CheckCredentials(payload.Login, payload.Password, _config);

                if (newUser == null)
                {
                    return(StatusCode(460, "Login failed!"));
                }
                var jwt = AuthUtilities.GenerateJwtToken(_config.PrivateKey, newUser.Id);
                newUser.Password = null;
                HttpContext.Response.Headers.Add("x-auth-token", $"{jwt}");
                return(Ok(newUser));
            }
            catch (AdminNotFoundException)
            {
                return(StatusCode(461, "Admin user not found!"));
            }
            catch
            {
                // For security issues
                // ReSharper disable once ThrowFromCatchWithNoInnerException
                throw new LoginOperationException("Internal server error occurred during login operation.");
            }
        }
Ejemplo n.º 4
0
        public static Task SendMessage(
            [HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "sendNotification/{userId}")]
            HttpRequest req,
            object message,
            string userId,
            [SignalR(HubName = "notificationsHub")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            try
            {
                var principal = AuthUtilities.ResolveClaimsPrincipal(req);

                return(signalRMessages.AddAsync(
                           new SignalRMessage
                {
                    UserId = userId,
                    Target = "sendNotification",
                    Arguments = new[] { message }
                }));
            }
            finally
            {
                log.LogError("Send Notification Error");
            }
        }
Ejemplo n.º 5
0
        public User Insert(string userName, string password)
        {
            try
            {
                if (userRepository.Select(nameof(User.UserName), userName).FirstOrDefault() != null)
                {
                    return(null);
                }

                var(salt, hash) = AuthUtilities.Create(password);

                var user = new User
                {
                    UserName     = userName,
                    PasswordSalt = Encoding.Default.GetString(salt),
                    PasswordHash = Encoding.Default.GetString(hash)
                };

                userRepository.Add(user);

                return(user);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 6
0
        public async Task <User> ComputePasswordHashAndAddUser(User user, ConfigEnvironment config)
        {
            user.Password = AuthUtilities.ComputeSha256Hash(user.Password, config.Salt);
            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return(user);
        }
Ejemplo n.º 7
0
        /// <exception cref="T:System.Reflection.TargetInvocationException">On the .NET Framework 4.6.1 and earlier versions only: The algorithm was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible.</exception>
        /// <exception cref="T:System.FormatException">includes an unsupported specifier. Supported format specifiers are listed in the Remarks section.</exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">Enlarging the value of this instance would exceed <see cref="P:System.Text.StringBuilder.MaxCapacity" />.</exception>
        /// <exception cref="T:System.ArgumentNullException"></exception>
        /// <exception cref="T:System.ObjectDisposedException">The object has already been disposed.</exception>
        /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (for more information, see Character Encoding in .NET)
        ///  -and-
        ///  <see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
        /// <exception cref="T:Microsoft.EntityFrameworkCore.DbUpdateException">An error is encountered while saving to the database.</exception>
        /// <exception cref="T:Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException">A concurrency violation is encountered while saving to the database.
        ///                 A concurrency violation occurs when an unexpected number of rows are affected during save.
        ///                 This is usually because the data in the database has been modified since it was loaded into memory.</exception>
        public async Task <User> ComputePasswordHashAndAddUser(User user, ConfigEnvironment config)
        {
            user.Password = AuthUtilities.ComputeSha256Hash(user.Password, config.Salt);
            await _context.Users.AddAsync(user);

            _logger.LogInformation($"Registered user with password: {user.Password.Substring(0, 5)}...");
            await _context.SaveChangesAsync();

            return(user);
        }
Ejemplo n.º 8
0
 public IActionResult HashPassword([FromBody] string password)
 {
     try
     {
         return(Ok(AuthUtilities.HashPassword(password)));
     }
     catch (System.Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
Ejemplo n.º 9
0
        public User Validate(string userName, string password)
        {
            try
            {
                var user = userRepository.Select(nameof(User.UserName), userName).First();

                var isValid = AuthUtilities.Validate(password, user);

                return(isValid ? user : null);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 10
0
        public async Task <ActionResult <LoginSuccessResponseDto> > Authorize([FromBody] LoginPasswordDto payload)
        {
            payload.TrimProperties();
            var hash = AuthUtilities.ComputeSha256Hash(payload.Password, _salt);
            var user = await _context.Users.SingleOrDefaultAsync(c => c.Login.Equals(payload.Login) && c.Password.Equals(hash));

            if (user != null)
            {
                var jwt = AuthUtilities.GenerateJWTToken(_privateKey, user.Id);
                var res = new LoginSuccessResponseDto(user, jwt);
                return(Ok(res));
            }
            else
            {
                return(StatusCode(410, "Login failed."));
            }
        }
Ejemplo n.º 11
0
        public static async Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie, string resourceId)
        {
            var extraParameters = AuthUtilities.EncodeResumptionCookie(resumptionCookie);

            AuthenticationSettings authenticationSettings = AuthenticationSettings.GetFromAppSettings();

            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authenticationSettings.EndpointUrl + "/" + authenticationSettings.Tenant);

            Uri redirectUri = new Uri(authenticationSettings.RedirectUrl);
            var uri         = await context.GetAuthorizationRequestUrlAsync(
                resourceId,
                authenticationSettings.ClientId,
                redirectUri,
                Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser,
                $"state={extraParameters}&response_mode=form_post");

            return(uri.ToString());
        }
Ejemplo n.º 12
0
        public async Task <ActionResult> NewUser(CoreUser user)
        {
            try
            {
                foreach (var item in user.Account)
                {
                    item.HashedPassword = AuthUtilities.HashPassword(user.TempPassword);
                }

                _context.CoreUser.Add(user);
                await _context.SaveChangesAsync();

                return(Ok("User Saved!"));
            }
            catch (System.Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Ejemplo n.º 13
0
        public async Task <ActionResult <IUser> > Post([FromBody] UserRegisterDto payload)
        {
            var host   = Request.Headers.GetHost();
            var i18n   = HttpContext.GetUserLanguage().CreateFactory();
            var result = await _userFacade.Register(payload, i18n, host);

            if (result.Succeed)
            {
                var newUser = result.Data;
                var jwt     = AuthUtilities.GenerateJWTToken(_config.PrivateKey, newUser.Id);
                HttpContext.Response.Headers.Add("x-auth-token", $"{jwt}");
                newUser.Password = null;
                return(Ok(newUser));
            }
            else
            {
                return(StatusCode(result.FailStatusCode, result.FailStatusMessage));
            }
        }
Ejemplo n.º 14
0
        /// <exception cref="T:System.Reflection.TargetInvocationException">On the .NET Framework 4.6.1 and earlier versions only: The algorithm was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible.</exception>
        /// <exception cref="T:System.FormatException">includes an unsupported specifier. Supported format specifiers are listed in the Remarks section.</exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">Enlarging the value of this instance would exceed <see cref="P:System.Text.StringBuilder.MaxCapacity" />.</exception>
        /// <exception cref="T:System.ArgumentNullException"></exception>
        /// <exception cref="T:System.ObjectDisposedException">The object has already been disposed.</exception>
        /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (for more information, see Character Encoding in .NET)
        ///  -and-
        ///  <see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
        /// <exception cref="T:System.InvalidOperationException">(Asynchronous) The sequence contains more than one element that satisfies the condition in the predicate.</exception>
        /// <exception cref="T:WebApi.Services.AdminNotFoundException">Admin not found in database!</exception>
        public async Task <User> CheckCredentials(string login, string password, ConfigEnvironment config)
        {
            var generatedHash = AuthUtilities.ComputeSha256Hash(password, config.Salt);
            var user          = await _context.Users.SingleOrDefaultAsync(c => c.Login.Trim() == login);

            if (user == null)
            {
                _logger.LogError($"Admin not found in database. Login: {login}");
                throw new AdminNotFoundException("Admin not found in database!");
            }
            var hashAssert = user.Password == generatedHash;

            if (!hashAssert)
            {
                _logger.LogError($"Wrong password for user {login}. " +
                                 $"Provided hash: {generatedHash.Substring(0, 5)}... " +
                                 $"Stored hash: {user.Password.Substring(0, 5)}...");
            }
            return(hashAssert ? user : null);
        }
Ejemplo n.º 15
0
        internal static Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie, string siteRelativeUrl, string authScope)
        {
            // https://mstackbv.sharepoint.com/sites/processes/?client_id=f485755d-217f-4d4f-a3ba-395af4d73d3e&scope=AllSites.Read&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A3978%2Fapi%2Foauth

            SharePointSettings settings = SharePointSettings.GetFromAppSettings();
            string             authUri  = $"{settings.TenantUrl}{siteRelativeUrl}/_layouts/15/OAuthAuthorize.aspx";

            var state = AuthUtilities.EncodeResumptionCookie(resumptionCookie);

            NameValueCollection queryParams = new NameValueCollection();

            queryParams.Add("client_id", settings.ClientId);
            queryParams.Add("scope", authScope);
            queryParams.Add("response_type", "code");
            queryParams.Add("redirect_uri", settings.RedirectUrl);
            queryParams.Add("state", state);

            authUri += AuthUtilities.ToQueryString(queryParams);
            return(Task.FromResult(authUri));
        }
Ejemplo n.º 16
0
        public async Task <ActionResult <IUser> > Register([FromBody] User payload)
        {
            if (await _context.Users.AsQueryable().AnyAsync())
            {
                return(StatusCode(462, "Main user was already registered"));
            }
            if (_userService.ThereIsAlreadyUserWithThisLogin(payload.Login))
            {
                return(StatusCode(460, "Login is already used!"));
            }
            try
            {
                var newUser = await _userService.ComputePasswordHashAndAddUser(payload, _config);

                var jwt = AuthUtilities.GenerateJwtToken(_config.PrivateKey, newUser.Id);
                newUser.Password = null;
                HttpContext.Response.Headers.Add("x-auth-token", $"{jwt}");
                return(Ok(newUser));
            }
            catch { return(StatusCode(461, "Internal server error occurred during register operation.")); }
        }
Ejemplo n.º 17
0
        public static Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie, string resourceId)
        {
            // https://start.exactonline.nl/api/oauth2/auth?client_id=01b85808-0248-47a8-9f25-08acd900f788&redirect_uri=http://www.mstack.nl&response_type=code&force_login=0&state=test

            var settings = AuthenticationSettings.GetFromAppSettings();

            string stateParameter = AuthUtilities.EncodeResumptionCookie(resumptionCookie);

            NameValueCollection queryParams = new NameValueCollection();

            queryParams.Add("client_id", settings.ClientId);
            queryParams.Add("redirect_uri", settings.RedirectUrl);
            queryParams.Add("response_type", "code");
            queryParams.Add("force_login", "0");
            queryParams.Add("state", stateParameter);

            string queryString = AuthUtilities.ToQueryString(queryParams);
            string result      = "https://start.exactonline.nl/api/oauth2/auth" + queryString;

            return(Task.FromResult(result));
        }