public async Task ImplicitGrant() {
			var coordinatorClient = new UserAgentClient(AuthorizationServerDescription);
			coordinatorClient.ClientCredentialApplicator = null; // implicit grant clients don't need a secret.
			Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					var request = await server.ReadAuthorizationRequestAsync(req, ct);
					Assert.That(request, Is.Not.Null);
					IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request;
					Assert.That(accessTokenRequest.ClientAuthenticated, Is.False);
					var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
					return await server.Channel.PrepareResponseAsync(response, ct);
				});
			{
				var client = new UserAgentClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
				var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, };
				var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true);
				Assert.That(request.ResponseType, Is.EqualTo(EndUserAuthorizationResponseType.AccessToken));
				var authRequestRedirect = await client.Channel.PrepareResponseAsync(request);
				Uri authRequestResponse;
				this.HostFactories.AllowAutoRedirects = false;
				using (var httpClient = this.HostFactories.CreateHttpClient()) {
					using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) {
						authRequestResponse = httpResponse.Headers.Location;
					}
				}

				var incoming =
					await client.Channel.ReadFromRequestAsync(new HttpRequestMessage(HttpMethod.Get, authRequestResponse), CancellationToken.None);
				var result = await client.ProcessUserAuthorizationAsync(authState, incoming, CancellationToken.None);
				Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
				Assert.That(result.RefreshToken, Is.Null);
			}
		}
        public AuthorizeResult Authorize(Uri url, string username, string password)
        {
            var authServer = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = null, // We are not actually using authorization, just authentication.
                TokenEndpoint = url
            };

            var client = new UserAgentClient(authServer, ClientIdentifier, ClientCredentialApplicator.PostParameter(ClientSecret));

            IAuthorizationState state;

            try
            {
                state = client.ExchangeUserCredentialForToken(username, password);
            }
            catch (Exception e)
            {
                var error = e.Message;

                if (e.InnerException != null)
                    error = string.Format("{0} Inner exception: {1}", error, e.InnerException.Message);

                return new AuthorizeResult
                {
                    Error = error
                };
            }

            return new AuthorizeResult
            {
                AuthorizationState = state
            };
        }
		public void ImplicitGrant() {
			var coordinatorClient = new UserAgentClient(AuthorizationServerDescription);
			var coordinator = new OAuth2Coordinator<UserAgentClient>(
				AuthorizationServerDescription,
				AuthorizationServerMock,
				coordinatorClient,
				client => {
					var authState = new AuthorizationState {
						Callback = ClientCallback,
					};
					var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true);
					Assert.AreEqual(EndUserAuthorizationResponseType.AccessToken, request.ResponseType);
					client.Channel.Respond(request);
					var incoming = client.Channel.ReadFromRequest();
					var result = client.ProcessUserAuthorization(authState, incoming);
					Assert.IsNotNullOrEmpty(result.AccessToken);
					Assert.IsNull(result.RefreshToken);
				},
				server => {
					var request = server.ReadAuthorizationRequest();
					IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request;
					Assert.IsFalse(accessTokenRequest.ClientAuthenticated);
					server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
				});

			coordinatorClient.ClientSecret = null; // implicit grant clients don't need a secret.
			coordinator.Run();
		}
 public HomeController() {
     var authServer = new AuthorizationServerDescription() {
         AuthorizationEndpoint = new Uri("http://localhost:49810/OAuth/Authorise"),
         TokenEndpoint = new Uri("http://localhost:49810/OAuth/Token"),
     };
     this.Client = new UserAgentClient(authServer, "samplewebapiconsumer", "samplesecret");
     this.Authorization = new AuthorizationState();
     this.Authorization.Callback = new Uri("http://localhost:18529/");
 }
Exemple #5
0
        private void oauth2BeginButton_Click(object sender, RoutedEventArgs e)
        {
            var authServer = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription {
                AuthorizationEndpoint = new Uri(this.oauth2AuthorizationUrlBox.Text),
            };

            if (this.oauth2TokenEndpointBox.Text.Length > 0)
            {
                authServer.TokenEndpoint = new Uri(this.oauth2TokenEndpointBox.Text);
            }

            try {
                var client = new OAuth2.UserAgentClient(authServer, this.oauth2ClientIdentifierBox.Text, this.oauth2ClientSecretBox.Text);

                var authorizePopup = new Authorize2(client);
                authorizePopup.Authorization.Scope.AddRange(OAuthUtilities.SplitScopes(this.oauth2ScopeBox.Text));
                authorizePopup.Owner = this;
                bool?result = authorizePopup.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    var requestUri = new UriBuilder(this.oauth2ResourceUrlBox.Text);
                    if (this.oauth2ResourceHttpMethodList.SelectedIndex > 0)
                    {
                        requestUri.AppendQueryArgument("access_token", authorizePopup.Authorization.AccessToken);
                    }

                    var request = (HttpWebRequest)WebRequest.Create(requestUri.Uri);
                    request.Method = this.oauth2ResourceHttpMethodList.SelectedIndex < 2 ? "GET" : "POST";
                    if (this.oauth2ResourceHttpMethodList.SelectedIndex == 0)
                    {
                        client.AuthorizeRequest(request, authorizePopup.Authorization);
                    }

                    using (var resourceResponse = request.GetResponse()) {
                        using (var responseStream = new StreamReader(resourceResponse.GetResponseStream())) {
                            this.oauth2ResultsBox.Text = responseStream.ReadToEnd();
                        }
                    }
                }
                else
                {
                    return;
                }
            } catch (Messaging.ProtocolException ex) {
                MessageBox.Show(this, ex.Message);
            } catch (WebException ex) {
                string responseText = string.Empty;
                if (ex.Response != null)
                {
                    using (var responseReader = new StreamReader(ex.Response.GetResponseStream())) {
                        responseText = responseReader.ReadToEnd();
                    }
                }
                MessageBox.Show(this, ex.Message + "  " + responseText);
            }
        }
        private static void Main()
        {
            // DotNetOpenAuth only issues access tokens when the client uses an HTTPS connection. As we will most
            // likely run the server on our local development machine with only a self-signed SSL certificate, setting up 
            // connection to the server will fail as the SSL certificate is considered invalid by the .NET framework. 
            // To circumvent this, we add the line below that will consider all SSL certificates as valid, including
            // self-signed certificaties. Note: this should only be used for testing purposes.
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

            // The description of the authorization server to which we will be connecting. The most important component
            // is the token endpoint, which is the URL at which the server listens for token requests
            var authorizationServerDescription = new AuthorizationServerDescription
                                                     {
                                                         TokenEndpoint = new Uri("https://localhost:44303/tokens"),
                                                         ProtocolVersion = ProtocolVersion.V20
                                                     };

            // Create the client with which we will be connecting to the server.
            var userAgentClient = new UserAgentClient(authorizationServerDescription, clientIdentifier: "demo-client-1", clientSecret: "demo-client-secret-1");

            // The scope that we request for the client. Note: this can also be null if we don't want to request any specific 
            // scope or more than one scope if we want to request an access token that is valid for several scopes
            var clientScopes = new[] { "demo-scope-client-1" };

            // Request a new client access token for the specified scopes (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4)
            // This method will use the client identifier and client secret used when constructing the UserAgentClient instance
            var clientAccessToken = userAgentClient.GetClientAccessToken(clientScopes);

            // Output some information about the retrieved client access token
            Console.WriteLine("[RETRIEVED CLIENT ACCESS TOKEN]");
            Console.WriteLine("Access token: {0}", clientAccessToken.AccessToken);
            Console.WriteLine("Expiration time: {0}", clientAccessToken.AccessTokenExpirationUtc);
            Console.WriteLine("Scope: {0}",  OAuthUtilities.JoinScopes(clientAccessToken.Scope));

            // The scope that we request for the user. Note: this can also be null if we don't want to request any specific 
            // scope or more than one scope if we want to request an access token that is valid for several scopes
            var userScopes = new[] { "demo-scope-1" };

            // Request a new user access token for the specified user and the specified scopes (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#page-35)
            var userAccessToken = userAgentClient.ExchangeUserCredentialForToken("demo-user-1", "demo-user-password-1", userScopes);

            // Output some information about the retrieved user access token
            Console.WriteLine("\n[RETRIEVED USER ACCESS TOKEN]");
            Console.WriteLine("Access token: {0}", userAccessToken.AccessToken);
            Console.WriteLine("Refresh token: {0}", userAccessToken.RefreshToken);
            Console.WriteLine("Expiration time: {0}", userAccessToken.AccessTokenExpirationUtc);
            Console.WriteLine("Scope: {0}", OAuthUtilities.JoinScopes(userAccessToken.Scope));

            var refreshed = userAgentClient.RefreshAuthorization(userAccessToken);

            Console.WriteLine("\n[REFRESHING USER ACCESS TOKEN]");
            Console.WriteLine("Access token refreshed: {0}", refreshed);

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
Exemple #7
0
 public HomeController()
 {
     var a = Guid.NewGuid().ToString("N");
     var authServer = new AuthorizationServerDescription()
     {
         AuthorizationEndpoint = new Uri("http://localhost:4251/OAuth/Authorize"),
         TokenEndpoint = new Uri("http://localhost:4251/OAuth/Token"),
     };
     Client = new UserAgentClient(authServer, "samplewebapiconsumer", "samplesecret");
     Authorization = new AuthorizationState { Callback = new Uri("http://localhost:4494/") };
 }
		internal Authorize2(UserAgentClient client, IAuthorizationState authorizationState) {
			Contract.Requires(client != null, "client");
			Contract.Requires(authorizationState != null, "authorizationState");

			this.InitializeComponent();

			this.client = client;
			this.Authorization = authorizationState;
			Uri authorizationUrl = this.client.RequestUserAuthorization(this.Authorization);
			this.webBrowser.Navigate(authorizationUrl.AbsoluteUri); // use AbsoluteUri to workaround bug in WebBrowser that calls Uri.ToString instead of Uri.AbsoluteUri leading to escaping errors.
		}
		public async Task ErrorResponseTest() {
			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					return await server.HandleTokenRequestAsync(req, ct);
				});
			var request = new AccessTokenAuthorizationCodeRequestC(AuthorizationServerDescription) { ClientIdentifier = ClientId, ClientSecret = ClientSecret, AuthorizationCode = "foo" };
			var client = new UserAgentClient(AuthorizationServerDescription, hostFactories: this.HostFactories);
			var response = await client.Channel.RequestAsync<AccessTokenFailedResponse>(request, CancellationToken.None);
			Assert.That(response.Error, Is.Not.Null.And.Not.Empty);
			Assert.That(response.Error, Is.EqualTo(Protocol.AccessTokenRequestErrorCodes.InvalidRequest));
		}
        static async void MainAsync(string[] args)
        {
            // Ignore SSL cert errors for now
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

            // The description of the authorization server to which we will be connecting. The most important component
            // is the token endpoint, which is the URL at which the server listens for token requests
            var authorizationServerDescription = new AuthorizationServerDescription
            {
                // Must use actual computer name as DotNetOpenAuth will throw exception if the computer name used does not match the server name
                TokenEndpoint = new Uri("https://localhost:44300/api/token"),
                ProtocolVersion = ProtocolVersion.V20
            };

            // Create the client with which we will be connecting to the server.
            var client = new UserAgentClient(authorizationServerDescription, clientIdentifier: "client1", clientSecret: "secret1");
            
            // The scope that we request for the client. Note: this can also be null if we don't want to request any specific 
            // scope or more than one scope if we want to request an access token that is valid for several scopes
            //var scope = new[] { "demo-scope-client-1" };

            // Request a new client access token for the specified scopes (http://tools.ietf.org/html/rfc6749#section-4.4)
            // This method will use the client identifier and client secret used when constructing the UserAgentClient instance
            // NOTE: Must use actual computer name in client AuthorizationServerDescription as DotNetOpenAuth will throw exception if the computer name used does not match the server name
            var result = await client.GetClientAccessTokenAsync(); //scope

            // Output some information about the retrieved client access token
            Console.WriteLine("[RETRIEVED CLIENT ACCESS TOKEN]");
            Console.WriteLine("Access token: {0}", result.AccessToken);
            Console.WriteLine("Expiration time: {0}", result.AccessTokenExpirationUtc);
            Console.WriteLine("Scope: {0}", OAuthUtilities.JoinScopes(result.Scope));

            // Now try to access a resource to validate the bearer token
            var httpClient = new OAuthHttpClient(result.AccessToken)
            {
                // Must use actual computer name as DotNetOpenAuth will throw exception if the computer name used does not match the server na
                BaseAddress = new Uri("https://localhost:44300/api/values")
            };
            Console.WriteLine();
            Console.WriteLine("Calling web api…");
            Console.WriteLine();
            var response = httpClient.GetAsync("").Result;
            if (response.StatusCode==HttpStatusCode.OK)
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            else
                Console.WriteLine(response);
            Console.ReadLine();

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
        public HomeController()
        {
            var authServer = new AuthorizationServerDescription
                {
                    AuthorizationEndpoint = new Uri(AuthorizationEndpoint),
                    TokenEndpoint = new Uri(TokenEndpoint),
                };

            Client = new UserAgentClient(authServer, ClientId, ClientSecret);
            Authorization = new AuthorizationState
                {
                    Callback = new Uri(AuthorizationCallback)
                };
        }
        /// <summary>
        ///     Create an HTTP Handler that supports OAuth user authentication.
        /// </summary>
        /// <param name="authBaseUri">The base auth URI e.g. https://auth.alitudeangel.com</param>
        /// <param name="clientId">Your client ID</param>
        /// <param name="clientSecret">Your client secret</param>
        /// <param name="scopes">Requested scopes</param>
        /// <param name="existingState">(optional) An existing state object from a previous session. May be null.</param>
        /// <param name="requireUserToken">true to aquire a user token, false to get a client only token.</param>
        /// <param name="redirectUri">The redirect URI to use for user token auth. Must match the registered URI for your client ID.</param>
        /// <param name="codeProvider">Implementation to use to get an authorization code URI from an auth login URI.</param>
        /// <returns>
        ///     A <see cref="ClientHandlerInfo"/> object that contains the auth state and the handler. The auth state may be persisted and passed
        ///     back in on future runs of the application to save login state.
        /// </returns>
        public static ClientHandlerInfo Create(
            string authBaseUri,
            string clientId,
            string clientSecret,
            IEnumerable<string> scopes,
            AuthorizationState existingState,
            bool requireUserToken,
            string redirectUri,
            IAuthorizeCodeProvider codeProvider)
        {
            AuthorizationServerDescription serverDescription = GetServerDescription(authBaseUri);
            ClientBase client;
            IAuthorizationState state = existingState;

            if (requireUserToken)
            {
                if (codeProvider == null || string.IsNullOrEmpty(redirectUri))
                {
                    throw new ArgumentNullException(nameof(codeProvider),
                        $"{nameof(codeProvider)} or {nameof(redirectUri)} cannot be null if {nameof(requireUserToken)} is true.");
                }

                var userClient = new UserAgentClient(serverDescription, clientId, ClientCredentialApplicator.PostParameter(clientSecret));
                if (state == null)
                {
                    // Open browser here
                    var returnTo = new Uri(redirectUri);
                    Uri uri = userClient.RequestUserAuthorization(scopes, returnTo: returnTo);
                    Uri result = codeProvider.GetCodeUri(uri, returnTo).Result;

                    state = new AuthorizationState {Callback = returnTo};
                    state.Scope.AddRange(scopes);
                    state = userClient.ProcessUserAuthorization(result, state);
                }

                client = userClient;
            }
            else
            {
                client = new WebServerClient(serverDescription, clientId, ClientCredentialApplicator.PostParameter(clientSecret));
                state = state ?? client.GetClientAccessToken(scopes);
            }

            return new ClientHandlerInfo(client.CreateAuthorizingHandler(state), state);
        }
Exemple #13
0
        private async void oauth2BeginButton_Click(object sender, RoutedEventArgs e)
        {
            var authServer = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription {
                AuthorizationEndpoint = new Uri(this.oauth2AuthorizationUrlBox.Text),
            };

            if (this.oauth2TokenEndpointBox.Text.Length > 0)
            {
                authServer.TokenEndpoint = new Uri(this.oauth2TokenEndpointBox.Text);
            }

            try {
                var client = new OAuth2.UserAgentClient(authServer, this.oauth2ClientIdentifierBox.Text, this.oauth2ClientSecretBox.Text);

                var authorizePopup = new Authorize2(client);
                authorizePopup.Authorization.Scope.AddRange(OAuthUtilities.SplitScopes(this.oauth2ScopeBox.Text));
                authorizePopup.Authorization.Callback = new Uri("http://www.microsoft.com/en-us/default.aspx");
                authorizePopup.Owner = this;
                authorizePopup.ClientAuthorizationView.RequestImplicitGrant = this.flowBox.SelectedIndex == 1;
                bool?result = authorizePopup.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    var request = new HttpRequestMessage(
                        new HttpMethod(((ComboBoxItem)this.oauth2ResourceHttpMethodList.SelectedValue).Content.ToString()),
                        this.oauth2ResourceUrlBox.Text);
                    using (var httpClient = new HttpClient(client.CreateAuthorizingHandler(authorizePopup.Authorization))) {
                        using (var resourceResponse = await httpClient.SendAsync(request)) {
                            this.oauth2ResultsBox.Text = await resourceResponse.Content.ReadAsStringAsync();
                        }
                    }
                }
            } catch (Messaging.ProtocolException ex) {
                MessageBox.Show(this, ex.Message);
            } catch (WebException ex) {
                string responseText = string.Empty;
                if (ex.Response != null)
                {
                    using (var responseReader = new StreamReader(ex.Response.GetResponseStream())) {
                        responseText = responseReader.ReadToEnd();
                    }
                }
                MessageBox.Show(this, ex.Message + "  " + responseText);
            }
        }
        private IAuthorizationState GetAccessToken(string refresh)
        {
            var authorizationServer = new AuthorizationServerDescription
            {
                TokenEndpoint = new Uri(this.TokenUri),
                ProtocolVersion = ProtocolVersion.V20,
            };

            var client = new UserAgentClient(authorizationServer, this.ClientId, this.ClientSecret);
            IAuthorizationState ostate;
            if (refresh == null)
                ostate = client.GetClientAccessToken(new[] { this.API_EndpointUri });
            else
            {
                ostate = new AuthorizationState(new[] { this.API_EndpointUri });
                ostate.RefreshToken = refresh;
                client.RefreshAuthorization(ostate);
            }
            return ostate;
        }
        public Uri GetAuthorizationUri()
        {
            _endPoint = "https://start.exactonline.com";

            _authorization = new AuthorizationState
            {
                Callback = new Uri("http://localhost:19648/home/exoauth2")
            };

            var serverDescription = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri(string.Format("{0}/api/oauth2/auth", _endPoint)),
                TokenEndpoint = new Uri(string.Format("{0}/api/oauth2/token", _endPoint))
            };

            _oAuthClient = new UserAgentClient(serverDescription, "eb93389b-9532-46ca-9b24-898a38e91c22", "jYzWXVFiE87C");
            _oAuthClient.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("jYzWXVFiE87C");

            return _oAuthClient.RequestUserAuthorization(_authorization);
        }
        public string RetrieveAuthorization(UserAgentClient client, IAuthorizationState authorizationState)
        {
            if (!HttpListener.IsSupported)
            {
                throw new NotSupportedException("HttpListener is not supported by this platform.");
            }

            // Create a HttpListener for the specified url.
            //string url = string.Format(LoopbackCallback, GetRandomUnusedPort(), Util.ApplicationName);
            string url = string.Format(LoopbackCallback, GetRandomUnusedPort());
            authorizationState.Callback = new Uri(url);
            var webserver = new HttpListener();
            webserver.Prefixes.Add(url);

            // Retrieve the authorization url.
            Uri authUrl = client.RequestUserAuthorization(authorizationState);

            try
            {
                // Start the webserver.
                webserver.Start();

                // Open the browser.
                Process.Start(authUrl.ToString() + "&access_type=offline&approval_prompt=force");

                // Wait for the incoming connection, then handle the request.
                return HandleRequest(webserver.GetContext());

            }
            catch (HttpListenerException ex)
            {
                throw new NotSupportedException("The HttpListener threw an exception.", ex);
            }
            finally
            {
                // Stop the server after handling the one request.
                webserver.Stop();

            }
        }
        public string RetrieveAuthorization(UserAgentClient client, IAuthorizationState authorizationState)
        {
            // Create the Url.
            authorizationState.Callback = new Uri(OutOfBandCallback);
            Uri url = client.RequestUserAuthorization(authorizationState);

            // Show the dialog.
            if (!Application.RenderWithVisualStyles)
            {
                Application.EnableVisualStyles();
            }

            Application.DoEvents();
            string authCode = OAuth2AuthorizationDialog.ShowDialog(url);
            Application.DoEvents();

            if (string.IsNullOrEmpty(authCode))
            {
                return null; // User cancelled the request.
            }

            return authCode;
        }
        private static IAuthorizationState GetAccessToken(string refresh)
        {
            var authorizationServer = new AuthorizationServerDescription
            {
                TokenEndpoint = new Uri(TokenEndpoint),
                ProtocolVersion = ProtocolVersion.V20,
            };

            // get a reference to the auth server
            var client = new UserAgentClient(authorizationServer, ClientId, ClientSecret);

            // now get a token
            IAuthorizationState authorizationState;
            if (refresh == null)
            {
                authorizationState =
                    client.ExchangeUserCredentialForToken(TestUsername, TestPassword, new[] { ApiEndpoint });
            }
            else
            {
                // we had previously authenticated so we can use the token rather than the credentials to get a new access token
                authorizationState = new AuthorizationState(new[] { ApiEndpoint })
                    {
                        RefreshToken = refresh
                    };
                client.RefreshAuthorization(authorizationState);
            }

            // return result
            return authorizationState;
        }
Exemple #19
0
 public static Uri GetAuthorization(UserAgentClient appClient)
 {
     return appClient.RequestUserAuthorization(GetState());
 }
		internal Authorize2(UserAgentClient client) {
			Requires.NotNull(client, "client");

			this.InitializeComponent();
			this.clientAuthorizationView.Client = client;
		}
		internal Authorize2(UserAgentClient client) {
			this.InitializeComponent();
			this.clientAuthorizationView.Client = client;
		}
		internal Authorize2(UserAgentClient client) {
			Contract.Requires(client != null, "client");

			this.InitializeComponent();
			this.clientAuthorizationView.Client = client;
		}
        private static IAuthorizationState GetAccessToken(string refresh)
        {
            var authorizationServer = new AuthorizationServerDescription
            {
                //AuthorizationEndpoint = new Uri(AUTHORIZATION_ENDPOINT),
                TokenEndpoint = new Uri(TOKEN_ENDPOINT),
                ProtocolVersion = ProtocolVersion.V20,
            };

            // get a reference to the auth server
            var client = new UserAgentClient(authorizationServer, CLIENT_ID, CLIENT_SECRET);

            // now get a token
            IAuthorizationState ostate;
            if (refresh == null)
                ostate = client.ExchangeUserCredentialForToken(TEST_USERNAME, TEST_PASSWORD, new[] { API_ENDPOINT });
            else
            {
                // we had previously authenticated so we can use the token rather than the credentials to get a new access token
                ostate = new AuthorizationState(new[] { API_ENDPOINT });
                ostate.RefreshToken = refresh;
                client.RefreshAuthorization(ostate);
            }

            // return result
            return ostate;
        }