An OAuth 2.0 consumer designed for web applications.
Inheritance: ClientBase
        public IAuthorizationState RequestAccessToken(string refreshToken)
        {
            {
                WebServerClient consumer = new WebServerClient(ServerDescription, ClientID, ClientSecret)
                {
                    AuthorizationTracker = new AuthorizationTracker(Scope)
                };

                IAuthorizationState grantedAccess = PrepareAuthorizationState(refreshToken);

                if (grantedAccess != null)
                {
                    try
                    {
                        consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ClientSecret);
                        consumer.RefreshAuthorization(grantedAccess, null);

                        return grantedAccess;
                    }
                    catch (Exception ex)
                    {
                        log.Error("RefreshAuthorization() Exception:\r\n{0}\r\n", ex.ToString());
                    }
                }

                return null;
            }
        }
		public async Task ResourceOwnerPasswordCredentialGrant(bool anonymousClient) {
			var authHostMock = CreateAuthorizationServerMock();
			if (anonymousClient) {
				authHostMock.Setup(
					m =>
					m.IsAuthorizationValid(
						It.Is<IAuthorizationDescription>(
							d =>
							d.ClientIdentifier == null && d.User == ResourceOwnerUsername &&
							MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))).Returns(true);
			}

			Handle(AuthorizationServerDescription.TokenEndpoint).By(async (req, ct) => {
				var server = new AuthorizationServer(authHostMock.Object);
				return await server.HandleTokenRequestAsync(req, ct);
			});

			var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
			if (anonymousClient) {
				client.ClientIdentifier = null;
			}

			var authState = await client.ExchangeUserCredentialForTokenAsync(ResourceOwnerUsername, ResourceOwnerPassword, TestScopes);
			Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty);
			Assert.That(authState.RefreshToken, Is.Not.Null.And.Not.Empty);
		}
Example #3
0
 public static WebServerClient CreateClient()
 {
     AuthorizationServerDescription desc = GetAuthServerDescription();
     var client = new WebServerClient(desc, clientIdentifier: "475779814525.apps.googleusercontent.com");
     client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("plCPGSN2a218q7gHYmy0-BW1");
     return client;
 }
Example #4
0
 private WebServerClient CreateOAuth2Client() {
     var serverDescription = new AuthorizationServerDescription {
         TokenEndpoint = new Uri(tokenEndpointTextBox.Text)
     };
     var client = new WebServerClient(serverDescription, oauth2ClientIdTextBox.Text, oauth2ClientSecretTextBox.Text);
     return (client);
 }
 public virtual IAuthorizationState ProcessUserAuthorization(
     WebServerClient authClient, AuthorizationServerDescription authServer, IServiceBase authService)
 {
     return HostContext.Config.StripApplicationVirtualPath
         ? authClient.ProcessUserAuthorization(authService.Request.ToHttpRequestBase())
         : authClient.ProcessUserAuthorization();
 }
        // GET: Account
        public ActionResult Login(string returnUrl)
        {
            _webServerClient = OAuthConfiguration.InitializeWebServerClient();

            var result = _webServerClient.ProcessUserAuthorization(Request);
            if (result == null)
            {

                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization();

                //Clear returnUrl

                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else
            {
                var username = OAuthConfiguration.GetMe(result.AccessToken);
                var user = UserManager.FindByName(username);
                if (user != null)
                {
                    SignInManager.SignIn(user, false, false);
                }
                else
                {
                    var newuser = new ApplicationUser { UserName = username, Email = username };
                    UserManager.Create(newuser);
                    SignInManager.SignIn(newuser, false, false);
                }

                return RedirectToLocal(returnUrl);
            }

            return View();
        }
Example #7
0
        protected async void Button1_Click(object sender, EventArgs e)
        {
            var authServer = new AuthorizationServerDescription()
            {
                
                TokenEndpoint = new Uri("http://localhost:53022/OAuth/token "),
                ProtocolVersion = ProtocolVersion.V20
            };
            WebServerClient Client= new WebServerClient(authServer, "idefav", "1");

            var code =await Client.GetClientAccessTokenAsync(new string[] { "http://localhost:55045/IService1/DoWork" });
            string token = code.AccessToken;
            Service1Reference.Service1Client service1Client=new Service1Client();
            var httpRequest = (HttpWebRequest)WebRequest.Create(service1Client.Endpoint.Address.Uri);
            ClientBase.AuthorizeRequest(httpRequest,token);
            var httpDetails = new HttpRequestMessageProperty();
            httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
            
            using (var scope = new OperationContextScope(service1Client.InnerChannel))
            {
                
                if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
                {
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
                }
                else
                {
                    OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpDetails);
                }
                
                Button1.Text= service1Client.DoWork();
            }


        }
        protected virtual WebServerClient GetClient()
        {
            var client = new WebServerClient(description) {
                ClientIdentifier = clientId,
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret),
            };

            return client;
        }
Example #9
0
 private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
 {
     // Register the authenticator.
     var provider = new WebServerClient(GoogleAuthenticationServer.Description);
     provider.ClientIdentifier = ClientCredentials.ClientID;
     provider.ClientSecret = ClientCredentials.ClientSecret;
     var authenticator = 
         new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true };
     return authenticator;
 }
 private void InitializeWebServerClient()
 {
     var authorizationServerUri = new Uri("http://localhost:11625");
     var authorizationServer = new AuthorizationServerDescription
     {
         AuthorizationEndpoint = new Uri(authorizationServerUri, "/OAuth/Authorize"),
         TokenEndpoint = new Uri(authorizationServerUri, "/OAuth/Token")
     };
     _webServerClient = new WebServerClient(authorizationServer, "123456", "abcdef");
 }
 private WebServerClient GetClient(IOAuth2SignInSettings signInSettings)
 {
     AuthorizationServerDescription authorizationServerDescription = _endpointBuilder.Build(signInSettings);
     var client = new WebServerClient(authorizationServerDescription)
         {
             ClientIdentifier = signInSettings.ClientId,
             ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(signInSettings.ClientSecret)
         };
     return client;
 }
Example #12
0
        private static void InitializeWebServerClient()
        {
            var authorizationServer = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri(authorizationServerUri, "/oauth2/authorize"),
                TokenEndpoint = new Uri(authorizationServerUri, "/api/oauth2/token"),
            };

            _webServerClient = new WebServerClient(authorizationServer, "resource_owner_test", "resource_owner_test");
        }
Example #13
0
 private static void InitializeWebServerClient()
 {
     var authorizationServerUri = new Uri(Paths.AuthorizationServerBaseAddress);
     var authorizationServer = new AuthorizationServerDescription
     {
         AuthorizationEndpoint = new Uri(authorizationServerUri, Paths.AuthorizePath),
         TokenEndpoint = new Uri(authorizationServerUri, Paths.TokenPath)
     };
     _webServerClient = new WebServerClient(authorizationServer, Clients.Client1.Id, Clients.Client1.Secret);
 }
        public static WebServerClient CreateClient()
        {
            //pleasea contact hellopaisa for the credentials

            var desc = GetAuthServerDescription();
            //client ID provided
            var client = new WebServerClient(desc, clientIdentifier: "ID");
            //client secret/password provided
            client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("SECRET");

            return client;
        }
Example #15
0
        /// <summary>
        /// 使用DotNetOpenOAuth组件来模拟授权
        /// </summary>
        /// <returns></returns>
        public ActionResult TestAuthorize()
        {
            var authServer = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri("http://localhost:3335/OAuth/Authorize"),
                TokenEndpoint         = new Uri("http://localhost:3335/OAuth/Token")
            };

            var autoServerClient = new DotNetOpenAuth.OAuth2.WebServerClient(authServer, clientIdentifier: "fNm0EDIXbfuuDowUpAoq5GTEiywV8eg0TpiIVnV8", clientSecret: "clientSecret");

            autoServerClient.RequestUserAuthorization(new string[] { "scope1" }, new Uri("http://localhost:3335/OAuth/GetAccessToken"));
            return(new EmptyResult());
        }
        public ActionResult AuthorizationCodeGrant(AuthorizationCodeGrantViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var client = new WebServerClient(_authServerDescription, viewModel.ClientId, viewModel.ClientSecret);

                var request = client.PrepareRequestUserAuthorization(new[] { viewModel.Scope });

                request.Send();
            }

            return View(viewModel);
        }
 protected OAuth2Authenticator(
     AuthorizationServerDescription description,
     Func<string, AuthResult.Data> selector,
     string consumerKey,
     string consumerSecret,
     IEnumerable<string> scope)
 {
     _scope    = scope;
     _selector = selector;
     _client   = new WebServerClient(description)
     {
         ClientIdentifier           = consumerKey,
         ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(consumerSecret),
     };
 }
        //private void Save(string date)
        //{
        //    Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
        //    connectionConfiguration.AppSettings.Settings["access_token"].Value = date;
        //    connectionConfiguration.Save(ConfigurationSaveMode.Modified);
        //    ConfigurationManager.RefreshSection("appSettings");
        //}
        private static IAuthorizationState GetAccessToken()
        {
            var authorizationServer = new AuthorizationServerDescription
            {
                TokenEndpoint = new Uri(ConfigurationManager.AppSettings["Link_AccessToken"]),
                ProtocolVersion = ProtocolVersion.V20

            };
            var client = new WebServerClient(authorizationServer, ConfigurationManager.AppSettings["LinkHost"]);
            client.ClientIdentifier = ConfigurationManager.AppSettings["AppId"];
            client.ClientSecret = ConfigurationManager.AppSettings["AppSecret"];

            var state = client.GetClientAccessToken(null);
            return state;
        }
        /// <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);
        }
        public ActionResult AuthorizationCodeGrant(string code, string state)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            var model = new AuthorizationCodeGrantViewModel { ClientId = "demo-client-auth-code-identifier", ClientSecret = "demo-client-auth-code-secret-key", Scope = "user" };

            if (!string.IsNullOrWhiteSpace(code) && !string.IsNullOrWhiteSpace(state))
            {
                var client = new WebServerClient(_authServerDescription, model.ClientId, model.ClientSecret);

                this.ViewBag.AccessToken = client.ProcessUserAuthorization(this.Request);
            }

            this.ViewBag.AuthorizationCode = code;
            this.ViewBag.AuthorizationState = state;

            return this.View(model);
        }
Example #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var authorizationServer = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri("http://localhost:18001/Katana.Sandbox.WebServer/Authorize"),
                TokenEndpoint = new Uri("http://localhost:18001/Katana.Sandbox.WebServer/Token")
            };
            _webServerClient = new WebServerClient(authorizationServer, "123456", "abcdef");

            if (string.IsNullOrEmpty(AccessToken.Text))
            {
                var authorizationState = _webServerClient.ProcessUserAuthorization(new HttpRequestWrapper(Request));
                if (authorizationState != null)
                {
                    AccessToken.Text = authorizationState.AccessToken;
                    Page.Form.Action = Request.Path;
                }
            }
        }
		public async Task DecodeRefreshToken() {
			var refreshTokenSource = new TaskCompletionSource<string>();
			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);
					var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
					return await server.Channel.PrepareResponseAsync(response);
				});
			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					var response = await server.HandleTokenRequestAsync(req, ct);
					var authorization = server.DecodeRefreshToken(refreshTokenSource.Task.Result);
					Assert.That(authorization, Is.Not.Null);
					Assert.That(authorization.User, Is.EqualTo(ResourceOwnerUsername));
					return response;
				});

			var client = new WebServerClient(AuthorizationServerDescription);
			try {
				var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, };
				var authRedirectResponse = await client.PrepareRequestUserAuthorizationAsync(authState);
				this.HostFactories.CookieContainer.SetCookies(authRedirectResponse, ClientCallback);
				Uri authCompleteUri;
				using (var httpClient = this.HostFactories.CreateHttpClient()) {
					using (var response = await httpClient.GetAsync(authRedirectResponse.Headers.Location)) {
						response.EnsureSuccessStatusCode();
						authCompleteUri = response.Headers.Location;
					}
				}

				var authCompleteRequest = new HttpRequestMessage(HttpMethod.Get, authCompleteUri);
				this.HostFactories.CookieContainer.ApplyCookies(authCompleteRequest);
				var result = await client.ProcessUserAuthorizationAsync(authCompleteRequest);
				Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
				Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
				refreshTokenSource.SetResult(result.RefreshToken);
			} catch {
				refreshTokenSource.TrySetCanceled();
			}
		}
		public AuthorizationApi(string baseUrl, string consumerKey, string consumerSecret) {
            this.BaseUrl = baseUrl;
			
			ConsumerKey = consumerKey;
			ConsumerSecret = consumerSecret;

			var authEndpoint = new UriBuilder(BaseUrl);
			authEndpoint.Path += "/oauth/auth";
			
			var tokenEndpoint = new UriBuilder(BaseUrl);
            tokenEndpoint.Path += "/oauth/token";

			ServerDescription = new AuthorizationServerDescription {
				AuthorizationEndpoint = authEndpoint.Uri,
				TokenEndpoint = tokenEndpoint.Uri,
				ProtocolVersion = ProtocolVersion.V20
            };

            oauthClient = new WebServerClient(ServerDescription, ConsumerKey, ConsumerSecret);
		}
Example #24
0
        //Authentication Method
        public void Authenticate()
        {
            var serverDescription = new AuthorizationServerDescription();
            serverDescription.AuthorizationEndpoint = new Uri(AuthorizationEndpointUrl);
            serverDescription.TokenEndpoint = new Uri(TokenEndpointUrl);
            serverDescription.ProtocolVersion = ProtocolVersion.V20;

            var client = new WebServerClient(serverDescription);
            client.ClientIdentifier = ClientIdentifier;
            client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ClientSecret);

            var token = client.GetClientAccessToken();

            //var request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test/");
            ////System.Diagnostics.Process.Start("http://localhost:8080/test/");

            //request.Method = "GET";
            //client.AuthorizeRequest(request, token);
            //var response = request.GetResponse();

            //var postreqreader = new StreamReader(response.GetResponseStream());
            //var json = postreqreader.ReadToEnd();
        }
Example #25
0
        private IAuthorizationState GetAuthorization(WebServerClient client)
        {
            // If this user is already authenticated, then just return the auth state.
            IAuthorizationState state = AuthState;
            if (state != null)
            {
                return state;
            }

            // Check if an authorization request already is in progress.
            state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
            if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
            {
                // Store and return the credentials.
                HttpContext.Current.Session["AUTH_STATE"] = _state = state;
                return state;
            }

            // Otherwise do a new authorization request.
            string scope = TasksService.Scopes.TasksReadonly.GetStringValue();
            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope });
            response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
            return null;
        }
		public async Task AuthorizationCodeGrant() {
			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);
					var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
					return await server.Channel.PrepareResponseAsync(response, ct);
				});
			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					return await server.HandleTokenRequestAsync(req, ct);
				});

			var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
			var authState = new AuthorizationState(TestScopes) {
				Callback = ClientCallback,
			};
			var authRequestRedirect = await client.PrepareRequestUserAuthorizationAsync(authState);
			this.HostFactories.CookieContainer.SetCookies(authRequestRedirect, ClientCallback);
			Uri authRequestResponse;
			this.HostFactories.AllowAutoRedirects = false;
			using (var httpClient = this.HostFactories.CreateHttpClient()) {
				using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) {
					Assert.That(httpResponse.StatusCode, Is.EqualTo(HttpStatusCode.Redirect));
					authRequestResponse = httpResponse.Headers.Location;
				}
			}

			var authorizationResponse = new HttpRequestMessage(HttpMethod.Get, authRequestResponse);
			this.HostFactories.CookieContainer.ApplyCookies(authorizationResponse);
			var result = await client.ProcessUserAuthorizationAsync(authorizationResponse, CancellationToken.None);
			Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
			Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
		}
		public async Task ResourceOwnerScopeOverride() {
			var clientRequestedScopes = new[] { "scope1", "scope2" };
			var serverOverriddenScopes = new[] { "scope1", "differentScope" };
			var authServerMock = CreateAuthorizationServerMock();
			authServerMock
				.Setup(a => a.CheckAuthorizeResourceOwnerCredentialGrant(ResourceOwnerUsername, ResourceOwnerPassword, It.IsAny<IAccessTokenRequest>()))
				.Returns<string, string, IAccessTokenRequest>((un, pw, req) => {
					var response = new AutomatedUserAuthorizationCheckResponse(req, true, ResourceOwnerUsername);
					response.ApprovedScope.Clear();
					response.ApprovedScope.UnionWith(serverOverriddenScopes);
					return response;
				});

			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(authServerMock.Object);
					return await server.HandleTokenRequestAsync(req, ct);
				});

			var client = new WebServerClient(AuthorizationServerDescription, hostFactories: this.HostFactories);
			var result = await client.ExchangeUserCredentialForTokenAsync(ResourceOwnerUsername, ResourceOwnerPassword, clientRequestedScopes);
			Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes));
		}
		public async Task ClientCredentialScopeOverride() {
			var clientRequestedScopes = new[] { "scope1", "scope2" };
			var serverOverriddenScopes = new[] { "scope1", "differentScope" };
			var authServerMock = CreateAuthorizationServerMock();
			authServerMock
				.Setup(a => a.CheckAuthorizeClientCredentialsGrant(It.IsAny<IAccessTokenRequest>()))
				.Returns<IAccessTokenRequest>(req => {
					var response = new AutomatedAuthorizationCheckResponse(req, true);
					response.ApprovedScope.Clear();
					response.ApprovedScope.UnionWith(serverOverriddenScopes);
					return response;
				});

			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(authServerMock.Object);
					return await server.HandleTokenRequestAsync(req, ct);
				});

			var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
			var result = await client.GetClientAccessTokenAsync(clientRequestedScopes);
			Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
			Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes));
		}
		public async Task CreateAccessTokenSeesAuthorizingUserClientCredentialGrant() {
			var authServerMock = CreateAuthorizationServerMock();
			authServerMock
				.Setup(a => a.CheckAuthorizeClientCredentialsGrant(It.IsAny<IAccessTokenRequest>()))
				.Returns<IAccessTokenRequest>(req => {
					Assert.That(req.UserName, Is.Null);
					return new AutomatedAuthorizationCheckResponse(req, true);
				});

			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(authServerMock.Object);
					return await server.HandleTokenRequestAsync(req, ct);
				});

			var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
			var result = await client.GetClientAccessTokenAsync(TestScopes);
			Assert.That(result.AccessToken, Is.Not.Null);
		}
		public async Task CreateAccessTokenSeesAuthorizingUserResourceOwnerGrant() {
			var authServerMock = CreateAuthorizationServerMock();
			authServerMock
				.Setup(a => a.CheckAuthorizeResourceOwnerCredentialGrant(ResourceOwnerUsername, ResourceOwnerPassword, It.IsAny<IAccessTokenRequest>()))
				.Returns<string, string, IAccessTokenRequest>((un, pw, req) => {
					var response = new AutomatedUserAuthorizationCheckResponse(req, true, ResourceOwnerUsername);
					Assert.That(req.UserName, Is.EqualTo(ResourceOwnerUsername));
					return response;
				});

			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(authServerMock.Object);
					return await server.HandleTokenRequestAsync(req, ct);
				});

			var client = new WebServerClient(AuthorizationServerDescription, hostFactories: this.HostFactories);
			var result = await client.ExchangeUserCredentialForTokenAsync(ResourceOwnerUsername, ResourceOwnerPassword, TestScopes);
			Assert.That(result.AccessToken, Is.Not.Null);
		}
		public void CreateAuthorizingHandlerAuthorization() {
			var client = new WebServerClient(AuthorizationServerDescription);
			string bearerToken = "mytoken";
			var authorization = new Mock<IAuthorizationState>();
			authorization.SetupGet(a => a.AccessToken).Returns(bearerToken);
			var tcs = new TaskCompletionSource<HttpResponseMessage>();
			var expectedResponse = new HttpResponseMessage();

			var mockHandler = new DotNetOpenAuth.Test.Mocks.MockHttpMessageHandler((req, ct) => {
				Assert.That(req.Headers.Authorization.Scheme, Is.EqualTo(Protocol.BearerHttpAuthorizationScheme));
				Assert.That(req.Headers.Authorization.Parameter, Is.EqualTo(bearerToken));
				tcs.SetResult(expectedResponse);
				return tcs.Task;
			});
			var applicator = client.CreateAuthorizingHandler(authorization.Object, mockHandler);
			var httpClient = new HttpClient(applicator);
			var actualResponse = httpClient.GetAsync("http://localhost/someMessage").Result;
			Assert.That(actualResponse, Is.SameAs(expectedResponse));
		}