Ejemplo n.º 1
0
        public override async Task Invoke(IOwinContext context)
        {
            IContentFormatter contentFormatter =
                context.GetDependencyResolver().Resolve <IContentFormatter>();

            IAppMetadataProvider appMetadataProvider =
                context.GetDependencyResolver().Resolve <IAppMetadataProvider>();

            context.Response.ContentType = "application/json; charset=utf-8";

            await context.Response.WriteAsync(contentFormatter.Serialize(await appMetadataProvider.GetAppMetadata()), context.Request.CallCancelled);
        }
        public override Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            if (_App == null)
            {
                _App = dependencyResolver.Resolve <AppEnvironment>();
            }

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            string redirectUriHost = $"{context.Request.Scheme}://{context.Request.Host.Value}{_App.GetHostVirtualPath()}SignIn";
            string redirectUri     = $"{_App.GetSsoUrl()}/connect/authorize?scope={string.Join(" ", _App.Security.Scopes)}&client_id={_App.GetSsoDefaultClientId()}&redirect_uri={redirectUriHost}&response_type=id_token token";

            string pathname = _App.GetHostVirtualPath() + (context.Request.Path != null ? context.Request.Path.Value.Substring(1) : string.Empty);

            string state = $@"{{""pathname"":""{pathname}""}}";

            string nonce = randomStringProvider.GetRandomString(12);

            context.Response.Redirect($"{redirectUri}&state={state}&nonce={nonce}");

            return(Task.CompletedTask);
        }
Ejemplo n.º 3
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            IContentFormatter contentFormatter = dependencyResolver.Resolve <IContentFormatter>();

            if (_baseRedirectUri == null)
            {
                IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver
                                                                 .Resolve <IAppEnvironmentProvider>();

                AppEnvironment activEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

                _baseRedirectUri = $"{activEnvironment.Security.SSOServerUrl}/connect/authorize?scope={string.Join(" ", activEnvironment.Security.Scopes)}&client_id={activEnvironment.Security.ClientName}&redirect_uri={activEnvironment.GetConfig("ClientHostBaseUri", context.Request.Host.Value)}{activEnvironment.GetConfig("ClientHostVirtualPath", "/")}SignIn&response_type=id_token token";
            }

            string nonce = randomStringProvider.GetRandomNonSecureString(12);

            string stateArgs = string.Join(string.Empty, context.Request.Path.Value.SkipWhile(c => c == '/'));

            string redirectUrl = $"{_baseRedirectUri}&state={stateArgs}&nonce={nonce}";

            context.Response.Redirect(redirectUrl);
        }
        public override Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            if (_App == null)
            {
                _App = dependencyResolver.Resolve <AppEnvironment>();
            }

            string afterLogoutRedirect_uri = context.Request.Query["redirect_uri"] ?? $"{context.Request.Scheme}://{context.Request.Host.Value}{_App.GetHostVirtualPath()}SignOut";

            string ssoRedirectUri = $"{_App.GetSsoUrl()}/connect/endsession?post_logout_redirect_uri={afterLogoutRedirect_uri}";

            string stateArgs = context.Request.Query["state"] ?? "{}";

            context.Response.Redirect($"{ssoRedirectUri}&id_token_hint={(context.Request.Query["id_token"])}&state={stateArgs}");

            context.Authentication.SignOut("custom", "Bearer");

            return(Task.CompletedTask);
        }
Ejemplo n.º 5
0
        public override Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            if (_App == null)
            {
                _App = dependencyResolver.Resolve <AppEnvironment>();
            }

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            string client_Id = context.Request.Query["client_id"] ?? _App.GetSsoDefaultClientId();
            string afterLoginRedirect_uri = context.Request.Query["redirect_uri"] ?? $"{context.Request.Scheme}://{context.Request.Host.Value}{_App.GetHostVirtualPath()}SignIn";

            string ssoRedirectUri = $"{_App.GetSsoUrl()}/connect/authorize?scope={string.Join(" ", _App.Security.Scopes)}&client_id={client_Id}&redirect_uri={afterLoginRedirect_uri}&response_type=id_token token";

            string stateArgs = context.Request.Query["state"] ?? "{}";

            string nonce = randomStringProvider.GetRandomString(12);

            string url = $"{ssoRedirectUri}&state={stateArgs}&nonce={nonce}";

            if (context.Request.Query["acr_values"] != null)
            {
                url += $"&acr_values={context.Request.Query["acr_values"]}";
            }

            context.Response.Redirect(url);

            return(Task.CompletedTask);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// The invoke.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public override async Task Invoke(IOwinContext context)
        {
            var dependencyResolver = context.GetDependencyResolver().Resolve <IDependencyResolver>();
            var operationContext   = dependencyResolver.Resolve <IRequestInfo>() as IOperationContext;

            var    correlationIdFromRequestHeader = context.Request.Headers["CorrelationId"];
            string correlationId = string.Empty;

            if (!string.IsNullOrEmpty(correlationIdFromRequestHeader))
            {
                correlationId = correlationIdFromRequestHeader;
            }
            else
            {
                correlationId = Guid.NewGuid().ToString();
            }
            operationContext.CorrelationId = correlationId;

            dependencyResolver.RegisterInstacnceAsUnityOfWork(operationContext);

            var response = context.Response;

            response.OnSendingHeaders(state =>
            {
                var resp = (OwinResponse)state;

                if ((resp.ContentLength != null || resp.StatusCode != 200) && resp.Headers.Get("CorrelationId") == null)
                {
                    resp.Headers.Add("CorrelationId", new[] { correlationId });
                }
            }, response);

            await this.Next.Invoke(context);
        }
Ejemplo n.º 7
0
        public override Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

            AppEnvironment activEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            if (_baseRedirectUri == null)
            {
                _baseRedirectUri = $"{activEnvironment.Security.SSOServerUrl}/connect/authorize?scope={string.Join(" ", activEnvironment.Security.Scopes)}&client_id={activEnvironment.Security.ClientName}&redirect_uri={activEnvironment.GetConfig("ClientHostBaseUri", context.Request.Host.Value)}{activEnvironment.GetConfig("ClientHostVirtualPath", "/")}SignIn&response_type=id_token token";
            }

            string pathname = activEnvironment.GetConfig("ClientHostVirtualPath", "/") + (context.Request.Path.HasValue ? context.Request.Path.Value.Substring(1) : string.Empty);

            string state = $@"{{""pathname"":""{pathname}""}}";

            string nonce = randomStringProvider.GetRandomNonSecureString(12);

            string redirectUrl = $"{_baseRedirectUri}&state={state}&nonce={nonce}";

            context.Response.Redirect(redirectUrl);

            return(Task.CompletedTask);
        }
Ejemplo n.º 8
0
        public override async Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IContentFormatter contentFormatter =
                context.GetDependencyResolver().Resolve <IContentFormatter>();

            IAppMetadataProvider appMetadataProvider =
                context.GetDependencyResolver().Resolve <IAppMetadataProvider>();

            context.Response.ContentType = "application/json; charset=utf-8";

            await context.Response.WriteAsync(contentFormatter.Serialize(await appMetadataProvider.GetAppMetadata().ConfigureAwait(false)), context.Request.CallCancelled).ConfigureAwait(false);
        }
Ejemplo n.º 9
0
        public override Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            if (_App == null)
            {
                _App = dependencyResolver.Resolve <AppEnvironment>();
            }

            string defaultPath = _App.GetHostVirtualPath();
            string defaultPathWithoutEndingSlashIfIsNotRoot = defaultPath == "/" ? defaultPath : defaultPath.Substring(0, defaultPath.Length - 1);

            string signInPage = $@"
<html>
    <head>
        <title>Signing in... Please wait</title>
        <script type='application/javascript'>
            var parts = location.hash.replace('#','').split('&');
            var expiresTimeInSeconds = Number(parts[3].split('=')[1]);
            var expiresDate = new Date();
            expiresDate.setTime(expiresDate.getTime() + (expiresTimeInSeconds * 1000));
            var expiresDateAsUTCString = expiresDate.toUTCString();
            for (var i = 0; i < parts.length; i++) {{
                var partStr = parts[i];
                var keyValue = partStr.split('=');
                var key = keyValue[0];
                var value = keyValue[1];
                if (key == 'access_token' || key == 'token_type'){{
                    document.cookie = partStr + ';expires=' + expiresDateAsUTCString + ';path={defaultPathWithoutEndingSlashIfIsNotRoot}';
                }}
                localStorage['{defaultPath}' + key] = value;
            }}
            localStorage['{defaultPath}login_date'] = new Date();
            var state = JSON.parse(decodeURIComponent(localStorage['{defaultPath}state'].replace(/\+/g, ' ')));
            localStorage['{defaultPath}state'] = JSON.stringify(state);
            if(state.AutoClose == null || state.AutoClose == false) {{
                location = state.pathname || '{defaultPath}';
            }}
            else {{
                window.close();
            }}
        </script>
    </head>
    <body>
        <h1>Signing in... Please wait</h1>
    </body>
</html>
";

            context.Response.ContentType = "text/html; charset=utf-8";

            return(context.Response.WriteAsync(signInPage, context.Request.CallCancelled));
        }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task Invoke(IOwinContext context)
        {
            var dependencyResolver = context.GetDependencyResolver().Resolve <IDependencyResolver>();
            var requestInfo        = dependencyResolver.Resolve <IRequestInfo>();
            var ipAddress          = context.Request.Headers.ContainsKey("x-forwarded-for") ? (string.IsNullOrEmpty(context.Request.Headers.GetValues("x-forwarded-for").First()) ? context.Request.RemoteIpAddress : context.Request.Headers.GetValues("x-forwarded-for").First().Split(',').First().Split(':').First()) : context.Request.RemoteIpAddress;

            requestInfo.IpAddress = ipAddress;
            await this.Next.Invoke(context);
        }
        public virtual bool IfIsNotLoggedIn(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return(context.GetDependencyResolver().Resolve <IUserInformationProvider>().IsAuthenticated() == false);
        }
Ejemplo n.º 12
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            string defaultPage = await dependencyResolver.Resolve <IDefaultHtmlPageProvider>().GetDefaultPageAsync(CancellationToken.None);

            context.Response.ContentType = "text/html; charset=utf-8";

            await context.Response.WriteAsync(defaultPage);
        }
Ejemplo n.º 13
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            string htmlPage = File.ReadAllText(dependencyResolver.Resolve <IPathProvider>().MapStaticFilePath(dependencyResolver.Resolve <AppEnvironment>().GetConfig(AppEnvironment.KeyValues.IndexPagePath, AppEnvironment.KeyValues.IndexPagePathDefaultValue)));

            string indexPageContents = await dependencyResolver.Resolve <IHtmlPageProvider>().GetHtmlPageAsync(htmlPage, context.Request.CallCancelled);

            context.Response.ContentType = "text/html; charset=utf-8";

            await context.Response.WriteAsync(indexPageContents, context.Request.CallCancelled);
        }
Ejemplo n.º 14
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            IRequestInformationProvider requestInformationProvider =
                dependencyResolver.Resolve <IRequestInformationProvider>();

            LogRequest(logger, requestInformationProvider);

            await Next.Invoke(context);
        }
Ejemplo n.º 15
0
        public override Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            IUserInformationProvider userInformationProvider =
                dependencyResolver.Resolve <IUserInformationProvider>();

            LogUserInformation(logger, userInformationProvider);

            return(Next.Invoke(context));
        }
Ejemplo n.º 16
0
        public override Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            AppEnvironment activeAppEnvironment = dependencyResolver.Resolve <AppEnvironment>();

            string defaultPath = activeAppEnvironment.GetHostVirtualPath();
            string defaultPathWithoutEndingSlashIfIsNotRoot = defaultPath == "/" ? defaultPath : defaultPath.Substring(0, defaultPath.Length - 1);

            IUrlStateProvider urlStateProvider = dependencyResolver.Resolve <IUrlStateProvider>();

            dynamic state = urlStateProvider.GetState(context.Request.Uri);

            bool autoCloseIsTrue = false;

            try
            {
                autoCloseIsTrue = state.AutoClose == true;
            }
            catch { }

            string singOutPage = $@"
<html>
    <head>
        <title>Signing out... Please wait</title>
        <script type='application/javascript'>
            localStorage.removeItem('{defaultPath}access_token');
            localStorage.removeItem('{defaultPath}expires_in');
            localStorage.removeItem('{defaultPath}id_token');
            localStorage.removeItem('{defaultPath}login_date');
            localStorage.removeItem('{defaultPath}scope');
            localStorage.removeItem('{defaultPath}session_state');
            localStorage.removeItem('{defaultPath}state');
            localStorage.removeItem('{defaultPath}token_type');
            var cookies = document.cookie.split('; ');
            for (var i = 0; i < cookies.length; i++)
            {{
                var cookie = cookies[i];
                var eqPos = cookie.indexOf('=');
                var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
                if(name == 'access_token' || name == 'token_type')
                    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path={defaultPathWithoutEndingSlashIfIsNotRoot}';
            }}
            {(autoCloseIsTrue ? "window.close();" : $"location = '{defaultPath}';")}
Ejemplo n.º 17
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

            AppEnvironment activeAppEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            string defaultPath = activeAppEnvironment.GetHostVirtualPath();
            string defaultPathWithoutEndingSlashIfIsNotRoot = defaultPath == "/" ? defaultPath : defaultPath.Substring(0, defaultPath.Length - 1);

            string signInPage = $@"
<html>
    <head>
        <title>Signing in... Please wait</title>
        <script type='application/javascript'>
            var parts = location.hash.replace('#','').split('&');
            var expireTimeInSeconds = Number(parts[3].split('=')[1]);
            var now = new Date();
            var time = now.getTime();
            var expireTime = time + (expireTimeInSeconds * 1000);
            now.setTime(expireTime);
            var nowAsGMTString = now.toUTCString();
            for (var i = 0; i < parts.length; i++) {{
                var partStr = parts[i];
                var keyValue = partStr.split('=');
                var key = keyValue[0];
                var value = keyValue[1];
                if (key == 'access_token' || key == 'token_type'){{
                    document.cookie = partStr + ';expires=' + nowAsGMTString + ';path={defaultPathWithoutEndingSlashIfIsNotRoot}';
                }}
                localStorage['{defaultPath}' + key] = value;
            }}
            localStorage['{defaultPath}login_date'] = new Date();
            var state = JSON.parse(decodeURIComponent(localStorage['{defaultPath}state'].replace(/\+/g, ' ')));
            localStorage['{defaultPath}state'] = JSON.stringify(state);
            location = state.pathname || '{defaultPath}';
        </script>
    </head>
    <body>
        <h1>Signing in... Please wait</h1>
    </body>
</html>
";

            context.Response.ContentType = "text/html; charset=utf-8";

            await context.Response.WriteAsync(signInPage, context.Request.CallCancelled);
        }
Ejemplo n.º 18
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

            AppEnvironment activeAppEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            string defaultPath = activeAppEnvironment.GetHostVirtualPath();
            string defaultPathWithoutEndingSlashIfIsNotRoot = defaultPath == "/" ? defaultPath : defaultPath.Substring(0, defaultPath.Length - 1);

            string singOutPage = $@"
<html>
    <head>
        <title>Signing out... Please wait</title>
        <script type='application/javascript'>
            localStorage.removeItem('{defaultPath}access_token');
            localStorage.removeItem('{defaultPath}expires_in');
            localStorage.removeItem('{defaultPath}id_token');
            localStorage.removeItem('{defaultPath}login_date');
            localStorage.removeItem('{defaultPath}scope');
            localStorage.removeItem('{defaultPath}session_state');
            localStorage.removeItem('{defaultPath}state');
            localStorage.removeItem('{defaultPath}token_type');
            var cookies = document.cookie.split('; ');
            for (var i = 0; i < cookies.length; i++)
            {{
                var cookie = cookies[i];
                var eqPos = cookie.indexOf('=');
                var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
                if(name == 'access_token' || name == 'token_type')
                    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path={defaultPathWithoutEndingSlashIfIsNotRoot}';
            }}
            location = '{defaultPath}';
        </script>
    </head>
    <body>
        <h1>Signing out... Please wait</h1>
    </body>
</html>
";

            context.Response.ContentType = "text/html; charset=utf-8";

            await context.Response.WriteAsync(singOutPage, context.Request.CallCancelled);
        }
Ejemplo n.º 19
0
        public override async Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            string htmlPage = await File.ReadAllTextAsync(dependencyResolver.Resolve <IPathProvider>().MapStaticFilePath(dependencyResolver.Resolve <AppEnvironment>().GetConfig(AppEnvironment.KeyValues.IndexPagePath, AppEnvironment.KeyValues.IndexPagePathDefaultValue) !)).ConfigureAwait(false);

            string indexPageContents = await dependencyResolver.Resolve <IHtmlPageProvider>().GetHtmlPageAsync(htmlPage, context.Request.CallCancelled).ConfigureAwait(false);

            context.Response.ContentType = "text/html; charset=utf-8";

            await context.Response.WriteAsync(indexPageContents, context.Request.CallCancelled).ConfigureAwait(false);
        }
Ejemplo n.º 20
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver
                                                             .Resolve <IAppEnvironmentProvider>();

            AppEnvironment activeAppEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            string redirectUriHost = $"{context.Request.Scheme}://{context.Request.Host.Value}{activeAppEnvironment.GetHostVirtualPath()}SignOut";

            string redirectUri = $"{activeAppEnvironment.GetSsoUrl()}/connect/endsession?post_logout_redirect_uri={redirectUriHost}";

            context.Response.Redirect(redirectUri + "&id_token_hint=" + context.Request.Query["id_token"]);

            context.Authentication.SignOut("custom", "Barear");
        }
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            IUserInformationProvider userInformationProvider =
                dependencyResolver.Resolve <IUserInformationProvider>();

            if (userInformationProvider.IsAuthenticated())
            {
                logger.AddLogData("UserId", userInformationProvider.GetCurrentUserId());
                logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
            }

            await Next.Invoke(context);
        }
Ejemplo n.º 22
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            if (_baseRedirectUri == null)
            {
                IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver
                                                                 .Resolve <IAppEnvironmentProvider>();

                AppEnvironment activEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

                _baseRedirectUri = $"{activEnvironment.Security.SSOServerUrl}/connect/endsession?post_logout_redirect_uri={activEnvironment.GetConfig("ClientHostBaseUri", context.Request.Host.Value)}{activEnvironment.GetConfig("ClientHostVirtualPath", "/")}SignOut";
            }

            context.Response.Redirect(_baseRedirectUri + "&id_token_hint=" + context.Request.Query["id_token"]);

            context.Authentication.SignOut("custom", "Barear");
        }
Ejemplo n.º 23
0
        public override Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            IRequestInformationProvider requestInformationProvider =
                dependencyResolver.Resolve <IRequestInformationProvider>();

            LogRequest(logger, requestInformationProvider);

            return(Next.Invoke(context));
        }
Ejemplo n.º 24
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

            AppEnvironment activeAppEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            string redirectUriHost = $"{context.Request.Scheme}://{context.Request.Host.Value}{activeAppEnvironment.GetHostVirtualPath()}SignIn";
            string redirectUri     = $"{activeAppEnvironment.GetSsoUrl()}/connect/authorize?scope={string.Join(" ", activeAppEnvironment.Security.Scopes)}&client_id={activeAppEnvironment.Security.ClientId}&redirect_uri={redirectUriHost}&response_type=id_token token";

            string stateArgs = string.Join(string.Empty, context.Request.Path.Value.SkipWhile(c => c == '/'));

            string nonce = randomStringProvider.GetRandomNonSecureString(12);

            context.Response.Redirect($"{redirectUri}&state={stateArgs}&nonce={nonce}");
        }
        public override async Task Invoke(IOwinContext context)
        {
            var resolver = context.GetDependencyResolver();
            var authService = resolver.GetService<IAuthService>();

            //System.Runtime.Caching
            var authenticatedUser = authService.Authenticate(context.Request.User.Identity.Name);

            if(authenticatedUser == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                using (var sw = new StreamWriter(context.Response.Body))
                {
                    await sw.WriteAsync("You are unauthorized to access this resource.");
                }
                return;
            }

            context.Request.User = authenticatedUser;
            Thread.CurrentPrincipal = context.Request.User;
            
            await Next.Invoke(context);
        }
Ejemplo n.º 26
0
        public override async Task Invoke(IOwinContext context)
        {
            var resolver    = context.GetDependencyResolver();
            var authService = resolver.GetService <IAuthService>();

            //System.Runtime.Caching
            var authenticatedUser = authService.Authenticate(context.Request.User.Identity.Name);

            if (authenticatedUser == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                using (var sw = new StreamWriter(context.Response.Body))
                {
                    await sw.WriteAsync("You are unauthorized to access this resource.");
                }
                return;
            }

            context.Request.User    = authenticatedUser;
            Thread.CurrentPrincipal = context.Request.User;

            await Next.Invoke(context);
        }
        public override Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

            AppEnvironment activeAppEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            string redirectUriHost = $"{context.Request.Scheme}://{context.Request.Host.Value}{activeAppEnvironment.GetHostVirtualPath()}SignIn";
            string redirectUri     = $"{activeAppEnvironment.GetSsoUrl()}/connect/authorize?scope={string.Join(" ", activeAppEnvironment.Security.Scopes)}&client_id={activeAppEnvironment.Security.ClientId}&redirect_uri={redirectUriHost}&response_type=id_token token";

            string pathname = activeAppEnvironment.GetHostVirtualPath() + (context.Request.Path.HasValue ? context.Request.Path.Value.Substring(1) : string.Empty);

            string state = $@"{{""pathname"":""{pathname}""}}";

            string nonce = randomStringProvider.GetRandomNonSecureString(12);

            context.Response.Redirect($"{redirectUri}&state={state}&nonce={nonce}");

            return(Task.CompletedTask);
        }
 public virtual Task <string> GetDefaultPageAsync(CancellationToken cancellationToken)
 {
     return(Task.FromResult(Engine.Razor.Run("defaultPageTemplate", typeof(IDependencyResolver),
                                             _owinContext.GetDependencyResolver())));
 }
Ejemplo n.º 29
0
        private void HandleException(System.Exception ex, IOwinContext context)
        {
            string       exceptionMessage = "";
            AppException exception        = null;
            var          logger           = context.GetDependencyResolver().Resolve <ILogger>();

            bool showNestedMessage = this._exceptionConfiguration.ShowNestedMessage();

            if (ex is AppException)
            {
                exception = (AppException)ex;
                //    exceptionMessage = $"An handled exception occured with StatusCode {exception.HttpStatusCode}";


                if (exception.Content.Value is ExceptionMessage)
                {
                    ExceptionMessage exMessage = exception.Content.Value as ExceptionMessage;

                    var exceptionMsg =
                        $"An AppException is initiated with HttpStatusCode: {(int)exception.HttpStatusCode}, \nOrginalAppException: {JsonConvert.SerializeObject(exMessage, Formatting.Indented, new JsonSerializerSettings { MaxDepth = 5 })}, \n OrginalException: {JsonConvert.SerializeObject(ex, Formatting.Indented, new JsonSerializerSettings { MaxDepth = 5 })}";

                    if (ex is Exceptions.ExternalRequestException || ex is Exceptions.ConfigException)
                    {
                        logger.Exception(new System.Exception(exceptionMsg));
                    }
                    else
                    {
                        logger.Warning(() => exceptionMsg);
                    }



                    if (exMessage.ErrorCodeValue != BaseErrorCodes.CommandValidation)
                    {
                        exMessage.IsDetailExposable = showNestedMessage;
                    }
                }
            }
            else
            {
                exception =
                    (AppException)
                    context.GetDependencyResolver()
                    .Resolve <InternalServerErrorException>()
                    .GetException(BaseErrorCodes.UnhandledException, ex, showNestedMessage, ex.Message);
                exceptionMessage = $"An exception occured with StatusCode {exception.HttpStatusCode}";
                logger
                .Exception(new System.Exception($"{exceptionMessage}, \n OrginalException:- {JsonConvert.SerializeObject(ex, Formatting.Indented, new JsonSerializerSettings { MaxDepth = 5 })}"));
            }



            context.Response.ReasonPhrase = exception.ReasonPhrase;
            context.Response.StatusCode   = (int)exception.HttpStatusCode;
            context.Response.ContentType  = "application/json";
            var jsonSerializerSettings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            };
            var json = JsonConvert.SerializeObject(exception.Content.Value, jsonSerializerSettings);

            context.Response.Write(json);
        }
Ejemplo n.º 30
0
 public virtual bool IsDefaultPageAndNotLoggedIn(IOwinContext cntx)
 {
     return(cntx.GetDependencyResolver().Resolve <IUserInformationProvider>().IsAuthenticated() == false);
 }
        private void PerformLog(LogEntry logEntry)
        {
            TelemetryClient          telemetryClient         = null;
            IUserInformationProvider userInformationProvider = null;
            bool isPerRequestTelemetryClient = false;

            if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.RequestUri)))
            {
                IOwinContext owinContext = OwinContext.Value;

                IDependencyResolver resolver = owinContext.GetDependencyResolver();

                telemetryClient = resolver.Resolve <TelemetryClient>();

                userInformationProvider = resolver.Resolve <IUserInformationProvider>();

                isPerRequestTelemetryClient = true;
            }

            List <KeyVal> keyValues = logEntry.LogData.Select(ld =>
            {
                string k = ld.Key;

                if (k == nameof(IRequestInformationProvider.HttpMethod) ||
                    k == nameof(IRequestInformationProvider.RequestUri) ||
                    k == nameof(IRequestInformationProvider.UserAgent) ||
                    k == "UserId" ||
                    k == "ResponseStatusCode" ||
                    k == nameof(IRequestInformationProvider.ClientIp) ||
                    ld.Value == null)
                {
                    return(null);
                }

                string v = null;

                if (ld.Value is string valueAsStr)
                {
                    v = valueAsStr;
                }

                if (k == "ClientLogs" || k == "OperationArgs")
                {
                    v = Formatter.Serialize(ld.Value);
                }
                else
                {
                    v = ld.Value.ToString();
                }

                return(new KeyVal {
                    Key = k, Value = v
                });
            })
                                      .Where(d => d != null)
                                      .ToList();

            try
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppEnvironmentName), Value = logEntry.AppEnvironmentName
                });

                if (logEntry.AppServerProcessId.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerProcessId), Value = logEntry.AppServerProcessId.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerAppDomainName), Value = logEntry.AppServerAppDomainName
                });

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerOSVersion), Value = logEntry.AppServerOSVersion
                });

                if (logEntry.AppServerDateTime.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerDateTime), Value = logEntry.AppServerDateTime.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerName), Value = logEntry.AppServerName
                });

                if (logEntry.AppWasInDebugMode.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppWasInDebugMode), Value = logEntry.AppWasInDebugMode.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerUserAccountName), Value = logEntry.AppServerUserAccountName
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppVersion), Value = logEntry.AppVersion
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.ApplicationName), Value = logEntry.ApplicationName
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Severity), Value = logEntry.Severity
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Message), Value = logEntry.Message
                });

                if (logEntry.Id.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.Id), Value = logEntry.Id.ToString()
                    });
                }

                if (logEntry.AppServerThreadId.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerThreadId), Value = logEntry.AppServerThreadId.ToString()
                    });
                }

                if (isPerRequestTelemetryClient == true)
                {
                    if (userInformationProvider.IsAuthenticated())
                    {
                        telemetryClient.Context.User.AccountId = telemetryClient.Context.User.AuthenticatedUserId = userInformationProvider.GetCurrentUserId();
                    }

                    LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));
                    if (userAgent != null)
                    {
                        telemetryClient.Context.User.UserAgent = (string)userAgent.Value;
                    }

                    foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                    {
                        if (!telemetryClient.Context.Properties.ContainsKey(keyVal.Key))
                        {
                            telemetryClient.Context.Properties.Add(keyVal.Key, keyVal.Value);
                        }
                    }
                }
                else
                {
                    telemetryClient = new TelemetryClient();

                    Dictionary <string, string> customData = new Dictionary <string, string>();

                    foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                    {
                        if (!customData.ContainsKey(keyVal.Key))
                        {
                            customData.Add(keyVal.Key, keyVal.Value);
                        }
                    }

                    Exception ex = null;

                    try
                    {
                        customData.TryGetValue("ExceptionTypeAssemblyQualifiedName", out string exceptionTypeAssemblyQualifiedName);

                        if (!string.IsNullOrEmpty(exceptionTypeAssemblyQualifiedName))
                        {
                            ex = (Exception)Activator.CreateInstance(Type.GetType(exceptionTypeAssemblyQualifiedName) ?? throw new InvalidOperationException($"{exceptionTypeAssemblyQualifiedName} could not be found"), args: new object[] { logEntry.Message });
                        }
                    }
                    catch { }

                    if (ex == null)
                    {
                        switch (logEntry.Severity)
                        {
                        case "Information":
                            ex = new InformationException(logEntry.Message);
                            break;

                        case "Warning":
                            ex = new WarningException(logEntry.Message);
                            break;

                        case "Error":
                            ex = new ErrorException(logEntry.Message);
                            break;

                        case "Fatal":
                            ex = new FatalException(logEntry.Message);
                            break;

                        default:
                            ex = new Exception(logEntry.Message);
                            break;
                        }
                    }

                    telemetryClient.TrackException(ex, customData);
                }
            }
            finally
            {
                telemetryClient.Flush();
            }
        }