public string BuildAuthorizeUrl()
        {
            var abosulteUri = new Uri(uriHelperService.GetAbsoluteUri());

            latestAuthorizeUrlCodeChallenge = GenerateNonce();
            latestAuthorizeUrlState         = GenerateNonce();

            if (clientSettings.RedirectAlwaysToHome)
            {
                latestAuthorizeUrRedirectUri = abosulteUri.GetLeftPart(UriPartial.Authority);
            }
            if (!clientSettings.RedirectAlwaysToHome)
            {
                latestAuthorizeUrRedirectUri = !string.IsNullOrEmpty(clientSettings.Auth0RedirectUri) ?  clientSettings.Auth0RedirectUri : abosulteUri.GetLeftPart(UriPartial.Path);
            }

            return($"https://{clientSettings.Auth0Domain}/authorize?" +
                   "&response_type=code" +
                   "&code_challenge_method=S256" +
                   $"code_challenge={latestAuthorizeUrlCodeChallenge}" +
                   $"&state={latestAuthorizeUrlState}" +
                   $"&client_id={clientSettings.Auth0ClientId}" +
                   $"&scope={clientSettings.Auth0Scope.Replace(" ", "%20")}" +
                   (!string.IsNullOrEmpty(clientSettings.Auth0Connection) ? "&connection=" + clientSettings.Auth0Connection : "") +
                   (!string.IsNullOrEmpty(clientSettings.Auth0Audience) ? "&audience=" + clientSettings.Auth0Audience : "") +
                   $"&redirect_uri={latestAuthorizeUrRedirectUri}");
        }
        public string GetHtml(int page, int limit, int count, IUriHelper uriHelper)
        {
            var    uri     = new Uri(uriHelper.GetAbsoluteUri());
            string baseUrl = uriHelper.GetAbsoluteUri().Split('?')[0];
            string filters = GetQueryStringFilters(uri);

            return(GetHtml(page, limit, count, baseUrl, filters));
        }
Exemple #3
0
        public async Task <T> GetJsonAuthorizedAsync <T>(string uri)
        {
            TryRetrieveToken();

            var response = await _httpClient.GetAsync("api/Gambler");

            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                _uriHelper.NavigateTo($"/login?returnUrl={_uriHelper.GetAbsoluteUri()}");

                return(await Task.FromResult(default(T)));
            }

            return(await _httpClient.GetJsonAsync <T>(uri));
        }
Exemple #4
0
        private void EnsureParameters()
        {
            if (parameters == null)
            {
                parameters = new KeyValueCollection();

                string url          = uri.GetAbsoluteUri();
                int    indexOfQuery = url.IndexOf('?');
                if (indexOfQuery >= 0)
                {
                    string   query = url.Substring(indexOfQuery + 1).ToLowerInvariant();
                    string[] items = query.Split('&');
                    foreach (string parameter in items)
                    {
                        string[] keyValue = parameter.Split('=');
                        if (keyValue.Length == 2)
                        {
                            parameters.Add(keyValue[0], keyValue[1]);
                        }
                        else
                        {
                            parameters.Add(keyValue[0], null);
                        }
                    }
                }
            }
        }
        public static string GetQueryParameterValue(this IUriHelper uriHelper, string key)
        {
            var uri = new Uri(uriHelper.GetAbsoluteUri());

            Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query).TryGetValue(key, out var value);
            return(value);
        }
        protected async override Task HandleAsync(AuthenticateAction action, IDispatcher dispatcher)
        {
            var currentUri = _uriHelper.GetAbsoluteUri();
            var host       = new Uri(currentUri).Host;
            var clientId   = new Guid("62c98281-193a-4884-a3a3-131eac593dff");

            if (host.Contains("jimhillr.dev"))
            {
                clientId = new Guid("1f14efd2-38c7-4dbd-a834-6b07233e1fb2");
            }
            var uriBuilder = new UriBuilder();

            uriBuilder.Scheme = "https";
            uriBuilder.Host   = "6umby.b2clogin.com";
            uriBuilder.Path   = "6umby.onmicrosoft.com/oauth2/v2.0/authorize";
            uriBuilder.Query  =
                "p=B2C_1_GumbySignUpSignIn" +
                "&client_id=" + clientId.ToString() +
                "&nonce=defaultNonce" +
                "&redirect_uri=" + currentUri +
                "&scope=openid" +
                "&response_type=id_token" +
                "&prompt=login";
            _uriHelper.NavigateTo(uriBuilder.ToString());
        }
Exemple #7
0
 public DocumentMetadataService(IDocumentMetadataSettingsProvider metadataProvider, IUriHelper uriHelper)
 {
     UriHelper                    = uriHelper;
     MetadataProvider             = metadataProvider;
     UriHelper.OnLocationChanged += OnLocationChanged;
     MetadataProvider.GetDefault()?.Apply(Metadata);
     LoadMetadataForPage(GetPageNameByLocation(UriHelper.GetAbsoluteUri()));
 }
        public string BuildAuthorizeUrl()
        {
            var abosulteUri  = new Uri(uriHelperService.GetAbsoluteUri());
            var responseType = string.Empty;

            latestAuthorizeUrlCodeChallenge = GenerateNonce();
            latestAuthorizeUrlState         = GenerateNonce();
            var nonce = GenerateNonce();

            Task.Run(async() => await jsRuntimeService.InvokeAsync <object>("setNonce", nonce)).ConfigureAwait(false);

            if (clientSettings.RedirectAlwaysToHome)
            {
                latestAuthorizeUrRedirectUri = abosulteUri.GetLeftPart(UriPartial.Authority);
            }
            if (!clientSettings.RedirectAlwaysToHome)
            {
                latestAuthorizeUrRedirectUri = !string.IsNullOrEmpty(clientSettings.Auth0RedirectUri) ? clientSettings.Auth0RedirectUri : abosulteUri.GetLeftPart(UriPartial.Path);
            }

            switch (clientSettings.AuthenticationGrant)
            {
            case AuthenticationGrantTypes.implicit_grant:
                responseType = "token id_token";
                break;

            default:
                responseType = "code";
                break;
            }

            return($"https://{clientSettings.Auth0Domain}/authorize?" +
                   $"response_type={responseType}" +
                   "&code_challenge_method=S256" +
                   $"&code_challenge={latestAuthorizeUrlCodeChallenge}" +
                   $"&state={latestAuthorizeUrlState}" +
                   $"&nonce={nonce}" +
                   $"&client_id={clientSettings.Auth0ClientId}" +
                   $"&scope={clientSettings.Auth0Scope.Replace(" ", "%20")}" +
                   (!string.IsNullOrEmpty(clientSettings.Auth0Connection) ? "&connection=" + clientSettings.Auth0Connection : "") +
                   (!string.IsNullOrEmpty(clientSettings.Auth0Audience) ? "&audience=" + clientSettings.Auth0Audience : "") +
                   $"&redirect_uri={latestAuthorizeUrRedirectUri}");
        }
Exemple #9
0
        protected override Task HandleAsync(Go action, IDispatcher dispatcher)
        {
            Uri fullUri = UriHelper.ToAbsoluteUri(action.NewUri);

            if (fullUri.ToString() != UriHelper.GetAbsoluteUri())
            {
                // Only navigate if we are not already at the URI specified
                UriHelper.NavigateTo(action.NewUri);
            }
            return(Task.CompletedTask);
        }
Exemple #10
0
        public override Task <IAction[]> HandleAsync(Go action)
        {
            Uri fullUri = UriHelper.ToAbsoluteUri(action.NewUri);

            if (fullUri.ToString() != UriHelper.GetAbsoluteUri())
            {
                // Only navigate if we are not already at the URI specified
                UriHelper.NavigateTo(action.NewUri);
            }
            return(Task.FromResult(new IAction[0]));
        }
Exemple #11
0
        private string GetCurrentUrl()
        {
            string currentUrl       = "/" + uri.ToBaseRelativePath(uri.GetBaseUri(), uri.GetAbsoluteUri());
            int    indexOfReturnUrl = currentUrl.IndexOf("?returnUrl");

            if (indexOfReturnUrl >= 0)
            {
                currentUrl = currentUrl.Substring(0, indexOfReturnUrl);
            }

            return(currentUrl);
        }
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            // hack: create a new HttpClient rather than relying on the registered service as the AuthenticationStateProvider is initialized prior to IUriHelper ( https://github.com/aspnet/AspNetCore/issues/11867 )
            HttpClient http   = new HttpClient();
            Uri        uri    = new Uri(urihelper.GetAbsoluteUri());
            string     apiurl = uri.Scheme + "://" + uri.Authority + "/~/api/User/authenticate";
            User       user   = await http.GetJsonAsync <User>(apiurl);

            var identity = user.IsAuthenticated
                ? new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.Username) }, "Identity.Application")
                : new ClaimsIdentity();

            return(new AuthenticationState(new ClaimsPrincipal(identity)));
        }
Exemple #13
0
        /// <summary>
        /// Adds location synchronization to the store. When the URI changes, a location-changing action will be dispatched.
        /// </summary>
        /// <param name="uriHelper">The application's UriHelper.</param>
        internal void InitializeLocationSynchronization(IUriHelper uriHelper)
        {
            if (_uriHelper == null && uriHelper != null && !_options.SuppressLocationSynchronization)
            {
                lock (_syncRoot)
                {
                    _uriHelper = uriHelper;
                    _uriHelper.OnLocationChanged += SynchronizeStateLocationWithUri;

                    _locationActionCreator = _options.LocationActionCreator ?? LocationActionCreatorFallback;
                }

                SynchronizeStateLocationWithUri(null, _uriHelper.GetAbsoluteUri());
            }
        }
Exemple #14
0
        public async Task Initialise()
        {
            int done = 10;

            while (done-- > 0)
            {
                if (ComponentContext.IsConnected)
                {
                    try
                    {
                        await LocalisationHelper.BuildLocalCulture();

                        await LocalisationHelper.BuildLocalTimeZone();

                        if (!HasApiKey)
                        {
                            SetApiKey(await LocalStorage.GetItemAsync <string>("GitterKey"));
                        }
                        break;
                    }
                    catch (Exception ex)
                    {
                        if (done == 1)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }

                await Task.Delay(1000);
            }
            if (HasApiKey)
            {
                initialised = true;
            }
            else
            {
                var currentUri  = UriHelper.GetAbsoluteUri();
                var baseUri     = UriHelper.GetBaseUri();
                var currentPage = UriHelper.ToBaseRelativePath(baseUri, currentUri);
                if (!currentPage.Equals(LOGINPAGE, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(currentPage))
                {
                    UriHelper.NavigateTo(LOGINPAGE);
                }
            }
        }
Exemple #15
0
        internal void Init(IUriHelper uriHelper)
        {
            if (_uriHelper != null || uriHelper == null)
            {
                return;
            }

            lock (_syncRoot)
            {
                _uriHelper = uriHelper;
                _uriHelper.OnLocationChanged += OnLocationChanged;
            }

            // TODO: Queue up any other actions, and let this apply to the initial state.
            DispatchLocation(new NewLocationAction {
                Location = _uriHelper.GetAbsoluteUri()
            });

            Console.WriteLine("Redux store initialized.");
        }
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            // hack: create a new HttpClient rather than relying on the registered service as the AuthenticationStateProvider is initialized prior to IUriHelper ( https://github.com/aspnet/AspNetCore/issues/11867 )
            HttpClient http   = new HttpClient();
            string     apiurl = ServiceBase.CreateApiUrl(sitestate.Alias, urihelper.GetAbsoluteUri(), "User") + "/authenticate";
            User       user   = await http.GetJsonAsync <User>(apiurl);

            ClaimsIdentity identity = new ClaimsIdentity();

            if (user.IsAuthenticated)
            {
                identity = new ClaimsIdentity("Identity.Application");
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Username));
                foreach (string role in user.Roles.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                }
            }
            return(new AuthenticationState(new ClaimsPrincipal(identity)));
        }
Exemple #17
0
        private async Task <string> RetrieveTokenAsync(DiscoveryResponse disco)
        {
            var path  = new Uri(uri.GetAbsoluteUri());
            var query = QueryHelpers.ParseQuery(path.Query);

            if (false == query.TryGetValue("code", out var code))
            {
                throw new Exception();
            }

            if (false == query.TryGetValue("state", out var state))
            {
                throw new Exception();
            }

            var redirect = new UriBuilder(client.BaseAddress)
            {
                Path = "callback"
            };

            var response = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
            {
                Address      = disco.TokenEndpoint,
                ClientId     = options.ClientId,
                Code         = code,
                CodeVerifier = state,
                RedirectUri  = redirect.ToString(),
                GrantType    = OidcConstants.GrantTypes.AuthorizationCode
            });

            if (response.IsError)
            {
                throw response.Exception;
            }

            return(response.AccessToken);
        }
Exemple #18
0
 /// <see cref="IMiddleware.Initialize(IStore)"/>
 public override void Initialize(IStore store)
 {
     base.Initialize(store);
     // If the URL changed before we initialized then dispatch an action
     Store.Dispatch(new Go(UriHelper.GetAbsoluteUri()));
 }
Exemple #19
0
 public HtmlTextService(HttpClient http, IUriHelper urihelper)
 {
     this.http = http;
     apiurl    = CreateApiUrl(urihelper.GetAbsoluteUri(), "HtmlText");
 }
Exemple #20
0
 public PageModuleService(HttpClient http, IUriHelper urihelper)
 {
     this.http = http;
     apiurl    = CreateApiUrl(urihelper.GetAbsoluteUri(), "PageModule");
 }
        public string BuildRouteApiUrl(string language, bool?hasRouteError)
        {
            string baseUrl = $"{_uriHelper.GetBaseUri()}/data/routes";

            string relativeUrl = $"{_uriHelper.ToBaseRelativePath(_uriHelper.GetBaseUri(), _uriHelper.GetAbsoluteUri())}";

            //Incorrect url
            if (hasRouteError.HasValue && hasRouteError.Value)
            {
                return($"{baseUrl}/error/{language}.json");
            }

            ISitecoreItem rootItem = _sitecoreItemService.GetSitecoreItemRootMock(language);

            if (rootItem.GetItSelfAndDescendants().Any(item => item.Url == "/" + relativeUrl) || relativeUrl == "")
            {
                if (relativeUrl.Length <= language.Length)
                {
                    return($"{baseUrl}/{language}.json");
                }

                return($"{baseUrl}{relativeUrl.Substring(language.Length)}/{language}.json");
            }


            return($"{baseUrl}/error/{language}.json");
        }
        public string BuildAuthorizeUrl()
        {
            var abosulteUri  = new Uri(uriHelperService.GetAbsoluteUri());
            var responseType = string.Empty;

            latestAuthorizeUrlCodeVerifier = GenerateNonce();
            latestAuthorizeUrlState        = GenerateNonce();
            var nonce = GenerateNonce();

            Task.Run(async() => await jsRuntimeService.InvokeAsync <object>("setNonce", nonce)).ConfigureAwait(false);

            if (clientSettings.RedirectAlwaysToHome)
            {
                latestAuthorizeUrRedirectUri = abosulteUri.GetLeftPart(UriPartial.Authority);
            }
            if (!clientSettings.RedirectAlwaysToHome)
            {
                latestAuthorizeUrRedirectUri = !string.IsNullOrEmpty(clientSettings.Auth0RedirectUri) ? clientSettings.Auth0RedirectUri : abosulteUri.GetLeftPart(UriPartial.Path);
            }

            switch (clientSettings.AuthenticationGrant)
            {
            case AuthenticationGrantTypes.implicit_grant:
                responseType = "token id_token";
                break;

            default:
                responseType = "code";
                break;
            }

            var host        = new Uri($"https://{clientSettings.Auth0Domain}");
            var customQuery = HttpUtility.ParseQueryString(host.Query);

            var queryParams = new Dictionary <string, string> {
                { "response_type", responseType },
                { "code_challenge_method", "S256" },
                { "code_challenge", GetSha256(latestAuthorizeUrlCodeVerifier) },
                { "state", latestAuthorizeUrlState },
                { "nonce", nonce },
                { "client_id", clientSettings.Auth0ClientId },
                { "scope", clientSettings.Auth0Scope.Replace(" ", "%20") }
            };

            if (!string.IsNullOrEmpty(clientSettings.Auth0Connection))
            {
                queryParams.Add("connection", clientSettings.Auth0Connection);
            }
            if (!string.IsNullOrEmpty(clientSettings.Auth0Audience))
            {
                queryParams.Add("audience", clientSettings.Auth0Audience);
            }

            queryParams.Add("redirect_uri", latestAuthorizeUrRedirectUri);

            var queryString = string.Join("&", queryParams.Select(x => x.Key + "=" + x.Value).ToArray());

            queryString += customQuery.AllKeys.Length > 0 ? "&" + customQuery.ToString() : string.Empty;

            var usriBuilder = new UriBuilder()
            {
                Scheme = host.Scheme,
                Host   = host.Host,
                Path   = GetPath(host),
                Query  = queryString
            };

            return(usriBuilder.Uri.AbsoluteUri);
        }
 public bool IsCurrentUriValid() => GetUriParts(_uriHelper.GetAbsoluteUri()).Length > 1;
 /// <summary>
 /// Creates a new instance of the routing feature
 /// </summary>
 /// <param name="uriHelper">Uri helper</param>
 public RoutingFeature(IUriHelper uriHelper)
 {
     InitialUrl = uriHelper.GetAbsoluteUri();
 }
        public static Dictionary <string, StringValues> GetQueryParameters(this IUriHelper uriHelper)
        {
            var uri = new Uri(uriHelper.GetAbsoluteUri());

            return(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query));
        }
Exemple #26
0
 public UserService(HttpClient http, IUriHelper urihelper)
 {
     this.http = http;
     apiurl    = CreateApiUrl(urihelper.GetAbsoluteUri(), "User");
 }
Exemple #27
0
 public ModuleDefinitionService(HttpClient http, IUriHelper urihelper)
 {
     this.http = http;
     apiurl    = CreateApiUrl(urihelper.GetAbsoluteUri(), "ModuleDefinition");
 }