Exemple #1
0
        public string CreateAuthorizeUrl(
            string clientId,
            string responseType,
            string scope        = null,
            string redirectUri  = null,
            string state        = null,
            string nonce        = null,
            string loginHint    = null,
            string acrValues    = null,
            string responseMode = null,
            object extra        = null)
        {
            var url = _authorizeRequest.CreateAuthorizeUrl(
                clientId: clientId,
                responseType: responseType,
                scope: scope,
                redirectUri: redirectUri,
                state: state,
                nonce: nonce,
                loginHint: loginHint,
                acrValues: acrValues,
                responseMode: responseMode,
                extra: extra);

            return(url);
        }
Exemple #2
0
        private async void btnOidcTokenHybrid_Click(object sender, EventArgs e)
        {
            var request = new AuthorizeRequest(Preferences.AuthorizationEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: txtOidcClientIdHybrid.Text,
                responseType: OidcConstants.ResponseTypes.CodeIdTokenToken,
                responseMode: OidcConstants.ResponseModes.FormPost,
                scope: txtOidcScopesHybrid.Text,
                redirectUri: txtOidcRedirectUriHybrid.Text,
                state: CryptoRandom.CreateUniqueId(),
                nonce: CryptoRandom.CreateUniqueId());

            LaunchBrowser(url);

            Tuple <string, string, string> tuple = await GetResponseFromAuthorizationServer(txtOidcRedirectUriHybrid.Text + "/", "hybrid");

            txtOidcCodeHybrid.Text              = tuple.Item1;
            txtOidcIdTokenHybrid.Text           = tuple.Item2;
            txtOidcIdTokenHybridParsed.Text     = ParseJwt(tuple.Item2);
            txtOidcAccessTokenHybrid.Text       = tuple.Item3;
            txtOidcAccessTokenHybridParsed.Text = ParseJwt(tuple.Item3);

            lastAccessToken = txtOidcAccessTokenHybrid.Text;

            btnOidcGetProfileHybrid.Enabled = true;
        }
Exemple #3
0
        public async Task CallBack(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                var state = CryptoRandom.CreateRandomKeyString(64);
                var nonce = CryptoRandom.CreateRandomKeyString(64);

                var request = new AuthorizeRequest(Configuration.AuthorizeEndpoint);
                var url     = request.CreateAuthorizeUrl(
                    clientId: "padmate_AuthorizationCode",
                    responseType: "code",
                    scope: "dpcontrolapiscope",
                    redirectUri: Configuration.CodeCallBackUrl,
                    state: state,
                    nonce: nonce);

                Process.Start(url);
            }
            else
            {
                var client = new TokenClient(
                    Configuration.TokenEndpoint,
                    "padmate_AuthorizationCode",
                    "padmate_authorizationcode_secret");

                var response = await client.RequestAuthorizationCodeAsync(code, Configuration.CodeCallBackUrl);

                await this.CallApi(response.AccessToken);
            }
        }
Exemple #4
0
        protected async Task <string> DefaultGetAuthorizationCode(string authorizationEndpoint)
        {
            CurrentStateToken = GenerateAuthorizationStateToken();
            var request      = new AuthorizeRequest(authorizationEndpoint);
            var authorizeUri = request.CreateAuthorizeUrl(ClientId, OidcConstants.ResponseTypes.Code, Scope, RedirectUriRoot, CurrentStateToken);

            var redirectUri = await AuthUriAcquirer.GetAuthorizationUriAsync(authorizeUri, RedirectUriRoot);

            if (string.IsNullOrEmpty(redirectUri))
            {
                return(null);
            }

            var returnedStateToken = StateCodeRegex.Match(redirectUri).Groups[1].Value;

            if (returnedStateToken != CurrentStateToken)
            {
                return(null);
            }

            var authCode = AuthCodeRegex.Match(redirectUri).Groups[1].Value;

            authCode = WebUtility.UrlDecode(authCode);
            return(authCode);
        }
        protected Uri GetAuthenticationUri()
        {
            var authRequest = new AuthorizeRequest(Configuration.AuthorizeUri);
            var redirectUri = GetRedirectUri().AbsoluteUri;
            var authUrl     = authRequest.CreateAuthorizeUrl(Constants.Authentication.ClientId,
                                                             Constants.Authentication.ResponseType, Constants.Authentication.Scope,
                                                             redirectUri, nonce: GenerateNOnce());

            return(new Uri(authUrl));
        }
Exemple #6
0
        public string BuildAuthorizeUrl(string authorizeEndpoint, string clientId, string scopes, Uri requestUri, string state, string nonce)
        {
            var request = new AuthorizeRequest(authorizeEndpoint);

            return(request.CreateAuthorizeUrl(
                       clientId: clientId,
                       responseType: "code",
                       scope: scopes,
                       redirectUri: $"{requestUri.Scheme}{Uri.SchemeDelimiter}{requestUri.Authority}{requestUri.AbsolutePath}",
                       state: state,
                       nonce: nonce));
        }
        public void SignIn(OAuthApplication oAuthApplication, ref OAuthToken token)
        {
            var request = new AuthorizeRequest(authorizationUrl);
            var url     = request.CreateAuthorizeUrl(
                clientId: oAuthApplication.ClientID,
                responseType: OidcConstants.ResponseTypes.Code,
                scope: _scope,
                state: oAuthApplication.ApplicationID.ToString(),
                redirectUri: AuthenticationHandler.ReturnUrl);

            throw new PXRedirectToUrlException(url, PXBaseRedirectException.WindowMode.InlineWindow, "Authenticate");
        }
        public string GetRedirectUrl(string state)
        {
            var request = new AuthorizeRequest(_googleOptions.AuthorizeEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: _googleOptions.ClientId,
                responseType: _googleOptions.ResponseType,
                scope: _googleOptions.Scope,
                redirectUri: _googleOptions.RedirectUrl,
                state: state);

            return(url);
        }
        public string GetAuthenticationRedirectUrl(string state, string nonce)
        {
            var request = new AuthorizeRequest(AuthorizeEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: ClientId,
                responseType: "code",
                scope: Scope,
                redirectUri: SignInCallbackUrl,
                state: state,
                nonce: nonce);

            return(url);
        }
Exemple #10
0
        private void RequestToken(string scope, string responseType)
        {
            var request  = new AuthorizeRequest(Constants.AuthorizeEndpoint);
            var startUrl = request.CreateAuthorizeUrl(
                clientId: "hybridclient",
                responseType: responseType,
                scope: scope,
                redirectUri: "oob://localhost/wpfclient",
                state: "random_state",
                nonce: "random_nonce");

            _login.Show();
            _login.Start(new Uri(startUrl), new Uri("oob://localhost/wpfclient"));
        }
Exemple #11
0
        public async static Task <AuthorizeResponse> DoImplicitFlowAsync(
            Uri endpoint,
            string clientId,
            string responseType,
            string scope,
            Uri redirectUri)
        {
            var request = new AuthorizeRequest(endpoint);
            var state   = Guid.NewGuid().ToString("N");
            var nonce   = Guid.NewGuid().ToString("N");

            var startUri = request.CreateAuthorizeUrl(
                clientId:     clientId,
                responseType: responseType,
                scope:        scope,
                redirectUri:  redirectUri.AbsoluteUri,
                state:        state,
                nonce:        nonce,
                responseMode: "form_post");

            try
            {
                var result = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.UseHttpPost,
                    new Uri(startUri));

                if (result.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    return(new AuthorizeResponse(result.ResponseData));
                }
                else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
                {
                    throw new Exception("User cancelled authentication");
                }
                else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    throw new Exception("HTTP Error returned by AuthenticateAsync() : " + result.ResponseErrorDetail.ToString());
                }
                else
                {
                    throw new Exception("Error returned by AuthenticateAsync() : " + result.ResponseStatus.ToString());
                }
            }
            catch
            {
                // Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
                throw;
            }
        }
        public ActionResult LogIn()
        {
            var nonce = CryptoRandom.CreateRandomKeyString(64);

            Session["nonce"] = nonce;
            var request = new AuthorizeRequest(_authorizeEndpoint);
            var url     = request.CreateAuthorizeUrl(
                _clientId,
                "code",
                _scopes,
                $"{_redirectUri}",
                responseMode: "form_post");

            return(Redirect(url));
        }
Exemple #13
0
        private void RequestToken(string scope, string responseType)
        {
            var request  = new AuthorizeRequest(Constants.AuthorizeEndpoint);
            var startUrl = request.CreateAuthorizeUrl(
                clientId: "implicitclient",
                responseType: responseType,
                scope: scope,
                redirectUri: "oob://localhost/wpfclient",
                state: "random_state",
                nonce: "random_nonce" /**,
                                       * loginHint: "alice",
                                       * acrValues: "idp:Google b c" **/);

            _login.Show();
            _login.Start(new Uri(startUrl), new Uri("oob://localhost/wpfclient"));
        }
        private static string CreateUrl(OidcSettings settings, OpenIdConnectConfiguration config, string nonce, string verifier)
        {
            var challenge = verifier.ToCodeChallenge();
            var request   = new AuthorizeRequest(config.AuthorizationEndpoint);

            return(request.CreateAuthorizeUrl(
                       clientId: settings.ClientId,
                       responseType: "code id_token",
                       scope: settings.Scope,
                       redirectUri: settings.RedirectUri,
                       nonce: nonce,
                       responseMode: OidcConstants.ResponseModes.FormPost,
                       acrValues: settings.AcrValues,
                       codeChallenge: settings.UsePkce ? challenge : null,
                       codeChallengeMethod: settings.UsePkce ? OidcConstants.CodeChallengeMethods.Sha256 : null));
        }
Exemple #15
0
        private static string CreateOAuthStartUrl(string authority, CryptoNumbers cryptoNumbers)
        {
            // FUTURE: discover authorize endpoint via ".well-known/openid-configuration"
            var request = new AuthorizeRequest(authority + "/connect/authorize");

            return(request.CreateAuthorizeUrl(
                       clientId: ClientId,
                       responseType: "id_token code",
                       responseMode: "form_post",
                       scope: "openid profile email offline_access piweb",
                       redirectUri: RedirectUri,
                       state: cryptoNumbers.State,
                       nonce: cryptoNumbers.Nonce,
                       codeChallenge: cryptoNumbers.Challenge,
                       codeChallengeMethod: OidcConstants.CodeChallengeMethods.Sha256));
        }
Exemple #16
0
        private RedirectUrlDto GetAuthorizeUrl(IPAddress ip, IProviderOptions providerOptions)
        {
            var request = new AuthorizeRequest(providerOptions.AuthorizeEndpoint);
            var state   = SaveState(ip);

            var url = request.CreateAuthorizeUrl(
                clientId: providerOptions.ClientId,
                responseType: providerOptions.ResponseType,
                scope: providerOptions.Scope,
                redirectUri: providerOptions.RedirectUrl,
                state: state);

            return(new RedirectUrlDto
            {
                Url = url
            });
        }
        private string RequestTokenAccessAuthorizationCode()
        {
            string accessToken = GetAccessTokenFromCookie();

            if (!string.IsNullOrEmpty(accessToken))
            {
                return(accessToken);
            }

            AuthorizeRequest authorizeRequest = new AuthorizeRequest(IdentityAuthorizeUri);
            var state = HttpContext.Request.Url.OriginalString;

            var url = authorizeRequest.CreateAuthorizeUrl("identitycode", "code", "api", IdentitySTSCallbackUri, state);

            HttpContext.Response.Redirect(url);
            return(null);
        }
Exemple #18
0
        private string CreateUrl()
        {
            _nonce    = CryptoRandom.CreateUniqueId(32);
            _verifier = CryptoRandom.CreateUniqueId(32);
            var challenge = _verifier.ToCodeChallenge();

            var request = new AuthorizeRequest(_config.AuthorizationEndpoint);

            return(request.CreateAuthorizeUrl(
                       clientId: _settings.ClientId,
                       responseType: "code id_token",
                       scope: _settings.Scope,
                       redirectUri: _settings.RedirectUri,
                       nonce: _nonce,
                       responseMode: OidcConstants.ResponseModes.FormPost,
                       codeChallenge: challenge,
                       codeChallengeMethod: OidcConstants.CodeChallengeMethods.Sha256));
        }
        private string GetAuthorizeUrl(string scope)
        {
            var state = Guid.NewGuid().ToString("N");

            SetTempState(state);

            //Make Authorization request
            var request = new AuthorizeRequest(AppController.authorizeUrl);

            string url = request.CreateAuthorizeUrl(
                clientId: AppController.clientid,
                responseType: OidcConstants.AuthorizeResponse.Code,
                scope: scope,
                redirectUri: AppController.redirectUrl,
                state: state);

            return(url);
        }
        public ActionResult Index(string scopes)
        {
            var state = Guid.NewGuid().ToString("N");
            var nonce = Guid.NewGuid().ToString("N");

            SetTempState(state, nonce);

            var request = new AuthorizeRequest(Constants.AuthorizeEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: Constants.client_id,
                responseType: "code",
                scope: "openid email profile contact auth offline_access",
                redirectUri: Constants.CallbackPath,
                state: state,
                nonce: nonce);

            return(Redirect(url));
        }
Exemple #21
0
        public ActionResult Index(string scopes)
        {
            var state = Guid.NewGuid().ToString("N");
            var nonce = Guid.NewGuid().ToString("N");

            SetTempState(state, nonce);

            var request = new AuthorizeRequest(Constants.AuthorizeEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId:     "codeclient",
                responseType: "code",
                scope:        scopes,
                redirectUri:  "https://localhost:44312/callback",
                state:        state,
                nonce:        nonce);

            return(Redirect(url));
        }
Exemple #22
0
        private async void btnGetTokenImplicit_Click(object sender, EventArgs e)
        {
            var state = Guid.NewGuid().ToString("N");

            var request = new AuthorizeRequest(Preferences.AuthorizationEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: "implicit.client",
                responseType: "token",
                scope: txtScopesImplicit.Text,
                redirectUri: txtRedirectUriImplicit.Text,
                state: state);

            LaunchBrowser(url);

            Tuple <string, string, string> tuple = await this.GetResponseFromAuthorizationServer(txtRedirectUriImplicit.Text + "/", "implicit");

            txtAccessTokenImplicit.Text = "Check access token in the browser as the part after the # doesn't get trasfered to the server. Copy and paste here.";
        }
        public string Connect(string scopes)
        {
            var state = Guid.NewGuid().ToString("N");
            var nonce = Guid.NewGuid().ToString("N");

            SetTempState(state, nonce);

            var request = new AuthorizeRequest(AuthorizeEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: "codeclient",
                responseType: "code",
                scope: scopes,
                redirectUri: "http://localhost:55820/ManualCodeFlowDemo/callback",
                state: state,
                nonce: nonce);

            return(url);
        }
        // GET: OAuth
        public ActionResult Index(string scopes)
        {
            var state = Guid.NewGuid().ToString("N");
            var nonce = Guid.NewGuid().ToString("N");

            SetTempState(state, nonce);

            var request = new AuthorizeRequest(Constants.AuthorizeEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: "app1",
                responseType: "code",
                scope: "resource openid offline_access",
                redirectUri: Constants.AuthCallback,
                state: state,
                nonce: nonce);

            return(Redirect(url));
        }
Exemple #25
0
        /// <summary>
        /// Gets an authorization code from the IdP
        /// </summary>
        /// <param name="clientId">The client id.</param>
        /// <param name="scopes">The scopes.</param>
        /// <param name="redirectUri">The redirect uri.</param>
        /// <returns></returns>
        private async Task <string> GetCode(string clientId, string scopes, string redirectUri)
        {
            var state = Guid.NewGuid().ToString("N");
            var nonce = Guid.NewGuid().ToString("N");

            var request = new AuthorizeRequest(Preferences.AuthorizationEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: clientId,
                responseType: "code",
                scope: scopes,
                redirectUri: redirectUri,
                state: state,
                nonce: nonce);

            LaunchBrowser(url);

            Tuple <string, string, string> tuple = await GetResponseFromAuthorizationServer(redirectUri + "/", "code");

            return(tuple.Item1);
        }
Exemple #26
0
        private async Task LoginUsingUsernameAndPasswordAsync()
        {
            const string responseType = "code id_token"; //implicit flow: "id_token token"

            // Space-separated list of scopes we want to receive
            var scopes = $"openid email profile offline_access {TimesheetConstants.ApiScope}";
            var nonce  = GenerateNonce(); // Unique token for the authorization request.

            try
            {
                var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
                var request     = new AuthorizeRequest(TimesheetConstants.AuthorizeEndpoint);
                var authUrl     = request.CreateAuthorizeUrl(TimesheetConstants.ClientId, responseType, scopes, redirectUri.ToString(), nonce: nonce);
                var requestUri  = new Uri(authUrl);

                var result =
                    await
                    WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, redirectUri);

                if (result.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    // Successful authentication, but we only have the ID token.
                    var response = new AuthorizeResponse(result.ResponseData);

                    // We need to ask for the access token and refresh tokens now.
                    var tokenResponse = await GetAuthTokenAsync(response);

                    // Store the tokens in the password vault
                    ApiService.StoreTokenInVault(tokenResponse);

                    // And finish the login process
                    await FinishLoginAsync(tokenResponse);
                }
            }
            catch (Exception ex)
            {
                var dlg = new MessageDialog(ex.Message, "Error");
                await dlg.ShowAsync();
            }
        }
Exemple #27
0
        public IActionResult Index(string scopes)
        {
            var state = Guid.NewGuid().ToString("N");
            var nonce = Guid.NewGuid().ToString("N");

            //SetTempState(state, nonce);

            // discover endpoints from metadata
            var disco = DiscoveryClient.GetAsync("http://localhost:5001").Result;

            var request = new AuthorizeRequest(disco.AuthorizeEndpoint);

            var url = request.CreateAuthorizeUrl(
                clientId: "code.client",
                responseType: "code",
                scope: scopes,
                redirectUri: "http://localhost:5760/callback",
                state: state,
                nonce: nonce);

            return(Redirect(url));
        }
Exemple #28
0
        public static async Task <AuthorizeResponse> GetAuthorizeResponseAsync(this IdentityServerPipeline idSvrPipeline, string clientId, string redirectUri, string responseType, string scope, string state = "state", string nonce = "nonce")
        {
            var old = idSvrPipeline.BrowserClient.AllowAutoRedirect;

            try
            {
                idSvrPipeline.BrowserClient.AllowAutoRedirect = false;

                var authorization = new AuthorizeRequest(IdentityServerPipeline.AuthorizeEndpoint);
                var url           = authorization.CreateAuthorizeUrl(clientId, responseType, scope, redirectUri, state, nonce);

                var authorizeResponse = await idSvrPipeline.BrowserClient.GetAsync(url);

                authorizeResponse.StatusCode.Should().Be(HttpStatusCode.Found);

                var location = authorizeResponse.Headers.Location.ToString();
                return(new AuthorizeResponse(location));
            }
            finally
            {
                idSvrPipeline.BrowserClient.AllowAutoRedirect = old;
            }
        }
        public override void Process(HttpRequestArgs args)
        {
            if (Context.Database == null || Context.Site == null) return;
            // Not checking IDAM authentication of content editors
            if ((new[] { "shell", "login", "admin" }).Contains(Context.Site.Name)) return;
            // force login only for normal website usage, not for preview / debugging / experienceediting / profiling
            if (!Context.PageMode.IsNormal) return;

            if (Context.User.IsAuthenticated) return;
            if (!SiteManager.CanEnter(Context.Site.Name, Context.User)) return;
            if (Context.Item != null && Context.Item.Access.CanRead()) return;
            if (Context.Item == null && args.PermissionDenied)
            {
                // generate nonces and set temporary cookie
                var state = Guid.NewGuid().ToString("N");
                var nonce = Guid.NewGuid().ToString("N");

                var cookie = new CookieHelper(Settings.TempCookieName, args.Context);
                cookie.SetValue("state", state);
                cookie.SetValue("nonce", nonce);
                cookie.SetValue("returnUrl", args.Context.Request.Url.ToString());
                cookie.Save();

                var request = new AuthorizeRequest(Settings.AuthorizeEndpoint);

                var url = request.CreateAuthorizeUrl(
                    clientId: Settings.ClientId,
                    responseType: "code",
                    scope: Settings.Scope,
                    redirectUri: Settings.SignInCallbackUrl,
                    state: state,
                    nonce: nonce);

                // Redirect the user to the login page of the identity provider
                WebUtil.Redirect(url);
            }
        }
Exemple #30
0
        public async Task <bool> Authorize(WebView webView)
        {
            var areq = new AuthorizeRequest(_baseAddress + "/connect/authorize");
            var uri  = areq.CreateAuthorizeUrl(clientId: "codeclient", responseType: "code", scope: "read write offline_access",
                                               redirectUri: _authorizeHelperAddress,
                                               acrValues: $"puid:{_puid}");

            _tokenResponse = null;
            evt.Reset();

            webView.NavigationCompleted += WebView_NavigationCompleted;
            webView.Navigate(new Uri(uri));

            await Task.Run(() => evt.WaitOne());

            webView.NavigateToString("");
            StoreProtect("token", _token);

            if (_tokenResponse == null || _tokenResponse.IsError)
            {
                return(false);
            }
            return(true);
        }