Authorization Server supporting the web server flow.
		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);
			}
		}
Esempio n. 2
0
        public async Task<ActionResult> Authorize(string username = null, string password = null)
        {
              
            if (username != null)
            {
                if (password != null)
                {
                    var entities = new AzurenEntities();
                    User u;
                    u = username.Contains("@") ? entities.Users.SingleOrDefault(m => m.Email == username) : entities.Users.SingleOrDefault(m => m.Username == username);
                    if (u == null || StringHelper.CalcPassword(password, u.Salt) != u.Password)
                    {
                        return RedirectToAction("Authorize", new { redirect_uri = Request.Params["redirect_uri"], client_id = Request.Params["client_id"], scope = Request.Params["scope"], error = true });
                    }
                    FormsAuthentication.SetAuthCookie(u.Username, true);
                    System.Web.HttpContext.Current.User = new RolePrincipal(new MyIdentity(u.Username, "Forms", true));
                }
            }
            if (!User.Identity.IsAuthenticated)
            {
                return Content("You must loggin first");
            }

            var authServer = new AuthorizationServer(new AuthorizationServerHost());
            var authRequest = await authServer.ReadAuthorizationRequestAsync(Request);
            var grantedResponse = authServer.PrepareApproveAuthorizationRequest(
                authRequest, this.User.Identity.Name, authRequest.Scope);
            IProtocolMessage responseMessage = grantedResponse;
            var response = await authServer.Channel.PrepareResponseAsync(responseMessage);
            return response.AsActionResult();
        }
        public ActionResult Issue()
        {
            var authorizationServer = new AuthorizationServer(new AuthorizationServerHost());
            var response = authorizationServer.HandleTokenRequest(Request).AsActionResult();

            return response;
        }
Esempio n. 4
0
        public ActionResult Authorise()
        {
            using (var server = (new OAuth2AuthorizationServer(new X509Certificate2(_absolutePathToPfx, _certificatePassword),
                            new X509Certificate2(_absolutePathToCertificate))))
            {
                var authorizationServer = new AuthorizationServer(server);

                var pendingRequest = authorizationServer.ReadAuthorizationRequest();
                if (pendingRequest == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
                }

                var requestingClient =
                    MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);

                // Consider auto-approving if safe to do so.
                if (((OAuth2AuthorizationServer)authorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest))
                {
                    var approval = authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
                    return authorizationServer.Channel.PrepareResponse(approval).AsActionResult();
                }

                var model = new AccountAuthorizeModel
                {
                    ClientApp = requestingClient.Name,
                    Scope = pendingRequest.Scope,
                    AuthorizationRequest = pendingRequest,
                };

                return View(model);
            }
        }
Esempio n. 5
0
		[HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
		public async Task<ActionResult> Authorize() {
			var authServer = new AuthorizationServer(new AuthorizationServerHost());
			var authRequest = await authServer.ReadAuthorizationRequestAsync(this.Request);
			this.ViewData["scope"] = authRequest.Scope;
			this.ViewData["request"] = this.Request.Url;
			return View();
		}
		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);
		}
 public OAuth2Controller() {
     // In this example, we're just newing up an auth server. A real implementation would use an IOC container
     // to resolve the dependencies and inject the auth server into our controller.
     var authServerKeys = CryptoKeyPair.LoadCertificate(HostingEnvironment.MapPath("~/bin/Certificates/auth-server.pfx"), "p@ssw0rd");
     var dataServerKeys = CryptoKeyPair.LoadCertificate(HostingEnvironment.MapPath("~/bin/Certificates/data-server.pfx"), "p@ssw0rd");
     var exampleAuthServer = new ExampleAuthorizationServer(new FakeCryptoKeyStore(),
         authServerKeys, dataServerKeys, new FakeOAuth2ClientStore(), new FakeUserStore());
     this.authServer = new AuthorizationServer(exampleAuthServer);
 }
Esempio n. 8
0
		public OAuthController(AuthorizationServer authorizationServer, string primaryTableName, string emailTableName, string cloudConfigurationName) {
			Requires.NotNull(authorizationServer, "authorizationServer");
			Requires.NotNullOrEmpty(cloudConfigurationName, "cloudConfigurationName");

			this.authorizationServer = authorizationServer;
			this.HttpClient = new HttpClient();

			var storage = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings[cloudConfigurationName].ConnectionString);
			var tableClient = storage.CreateCloudTableClient();
			this.ClientTable = new AddressBookContext(tableClient, primaryTableName, emailTableName);
		}
        public ActionResult Token()
        {
            var configuration = new IssuerConfiguration
            {
                EncryptionCertificate = new X509Certificate2(Server.MapPath("~/Certs/localhost.cer")),
                SigningCertificate = new X509Certificate2(Server.MapPath("~/Certs/localhost.pfx"), "a")
            };
            var authServer = new AuthorizationServer(new OAuth2Issuer(configuration));

            return authServer.HandleTokenRequest(Request).AsActionResult();
        }
		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));
		}
Esempio n. 11
0
		/// <summary>
		/// Initializes the <see cref="authorizationServer"/> field if it has not yet been initialized.
		/// </summary>
		private static void EnsureInitialized() {
			if (authorizationServer == null) {
				lock (InitializerLock) {
					if (authorizationServerDescription == null) {
						authorizationServerDescription = new AuthorizationServerDescription {
							AuthorizationEndpoint = new Uri(Utilities.ApplicationRoot, "OAuth.ashx"),
							TokenEndpoint = new Uri(Utilities.ApplicationRoot, "OAuth.ashx"),
						};
					}

					if (authorizationServer == null) {
						authorizationServer = new AuthorizationServer(new OAuthAuthorizationServer());
					}
				}
			}
		}
Esempio n. 12
0
        protected void Application_Start()
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            // 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;

            // Use a default in-memory provider application store. This is a class that is ideal for use in test
            // applications as it requires no further setup and can be used as both the crypto key- and nonce store.
            // In real-life situations you would of course implement your own crypto key- and nonce store, which will
            // most likely use some kind of persistent storage to store keys and nonces. As the nonces are kept in memory
            // only, it is not possible to refresh tokens as the issued tokens will have been removed from memory the moment
            // the refresh token request is being processed
            var standardProviderApplicationStore = new StandardProviderApplicationStore();
            var clientRepository = new InMemoryClientRepository();
            clientRepository.Save(new Client()
                {
                    Id = "demo-client-auth-code-identifier",
                    SecretKey = "demo-client-auth-code-secret-key",
                    CallbackUrl = new Uri("http://localhost/OAuth2WebClient/")
                });
            clientRepository.Save(new Client()
            {
                Id = "demo-client-credentials-identifier",
                SecretKey = "demo-client-credentials-secret-key"
            });
            clientRepository.Save(new Client()
            {
                Id = "demo-client-res-owner-identifier"
            });

            var userRepository = new InMemoryUserRepository();
            userRepository.Save(new User
                {
                    Name = "demo-user-username",
                    Password = "******"
                });

            var authorizationServerHost = new AuthorizationServerHost(standardProviderApplicationStore, standardProviderApplicationStore, clientRepository, userRepository);

            // Create our authorization server using our own, custom IAuthorizationServerHost implementation
            AuthorizationServer = new AuthorizationServer(authorizationServerHost);
        }
Esempio n. 13
0
		public async Task<ActionResult> Respond(string request, bool approval) {
			var authServer = new AuthorizationServer(new AuthorizationServerHost());
			var authRequest = await authServer.ReadAuthorizationRequestAsync(new Uri(request));
			IProtocolMessage responseMessage;
			if (approval) {
				var grantedResponse = authServer.PrepareApproveAuthorizationRequest(
					authRequest, this.User.Identity.Name, authRequest.Scope);
				responseMessage = grantedResponse;
			} else {
				var rejectionResponse = authServer.PrepareRejectAuthorizationRequest(authRequest);
				rejectionResponse.Error = Protocol.EndUserAuthorizationRequestErrorCodes.AccessDenied;
				responseMessage = rejectionResponse;
			}

			var response = await authServer.Channel.PrepareResponseAsync(responseMessage);
			return response.AsActionResult();
		}
		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();
			}
		}
Esempio n. 15
0
        public ActionResult AuthoriseResponse(bool isApproved)
        {
            using (OAuth2AuthorizationServer server = (new OAuth2AuthorizationServer(new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToPfx"], ConfigurationManager.AppSettings["CertificatePassword"]),
                            new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToCertificate"]))))
            {
                AuthorizationServer authorizationServer = new AuthorizationServer(server);
                var pendingRequest = authorizationServer.ReadAuthorizationRequest();
                if (pendingRequest == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
                }

                IDirectedProtocolMessage response;
                if (isApproved)
                {

                    // The authorization we file in our database lasts until the user explicitly revokes it.
                    // You can cause the authorization to expire by setting the ExpirationDateUTC
                    // property in the below created ClientAuthorization.
                    var client = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
                    client.ClientAuthorizations.Add(
                        new ClientAuthorization
                        {
                            Scope = OAuthUtilities.JoinScopes(pendingRequest.Scope),
                            User = MvcApplication.DataContext.Users.FirstOrDefault(u => u.Username == System.Web.HttpContext.Current.User.Identity.Name),
                            CreatedOnUtc = DateTime.UtcNow,
                        });
                    MvcApplication.DataContext.SaveChanges(); // submit now so that this new row can be retrieved later in this same HTTP request

                    // In this simple sample, the user either agrees to the entire scope requested by the client or none of it.
                    // But in a real app, you could grant a reduced scope of access to the client by passing a scope parameter to this method.
                    response = authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
                }
                else
                {
                    response = authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
                }

                return authorizationServer.Channel.PrepareResponse(response).AsActionResult();
            }
        }
		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 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 Task<HttpResponseMessage> Post(HttpRequestMessage request)
 {
     var authServer = new AuthorizationServer(new AuthorizationServerHost());
     return authServer.HandleTokenRequestAsync(request);
 }
Esempio n. 21
0
        /// <summary>
        /// The OAuth 2.0 token endpoint.
        /// </summary>
        /// <returns>The response to the Client.</returns>
        public ActionResult Token()
        {
            using (var server = (new OAuth2AuthorizationServer(new X509Certificate2(_absolutePathToPfx, _certificatePassword),
                            new X509Certificate2(_absolutePathToCertificate))))
            {
                var authorizationServer = new AuthorizationServer(server);
                OutgoingWebResponse response = authorizationServer.HandleTokenRequest(Request);

                return response.AsActionResult();
            }
        }
Esempio n. 22
0
 public async Task<ActionResult> Token()
 {
     var authServer = new AuthorizationServer(new AuthorizationServerHost());
     var t = await authServer.HandleTokenRequestAsync(Request);
     return t.AsActionResult();
 }
		public async Task GetClientAccessTokenReturnsApprovedScope() {
			string[] approvedScopes = new[] { "Scope2", "Scope3" };
			var authServer = CreateAuthorizationServerMock();
			authServer.Setup(
				a => a.IsAuthorizationValid(It.Is<IAuthorizationDescription>(d => d.User == null && d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes))))
					  .Returns(true);
			authServer.Setup(
				a => a.CheckAuthorizeClientCredentialsGrant(It.Is<IAccessTokenRequest>(d => d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes))))
					.Returns<IAccessTokenRequest>(req => {
						var response = new AutomatedAuthorizationCheckResponse(req, true);
						response.ApprovedScope.ResetContents(approvedScopes);
						return response;
					});
			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(authServer.Object);
					return await server.HandleTokenRequestAsync(req, ct);
				});

			var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
			var authState = await client.GetClientAccessTokenAsync(TestScopes);
			Assert.That(authState.Scope, Is.EquivalentTo(approvedScopes));
		}
		public async Task ClientCredentialGrant() {
			var authServer = CreateAuthorizationServerMock();
			authServer.Setup(
				a => a.IsAuthorizationValid(It.Is<IAuthorizationDescription>(d => d.User == null && d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes))))
				.Returns(true);
			authServer.Setup(
				a => a.CheckAuthorizeClientCredentialsGrant(It.Is<IAccessTokenRequest>(d => d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes))))
				.Returns<IAccessTokenRequest>(req => new AutomatedAuthorizationCheckResponse(req, true));
			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(authServer.Object);
					return await server.HandleTokenRequestAsync(req, ct);
				});
			var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
			var authState = await client.GetClientAccessTokenAsync(TestScopes);
			Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty);
			Assert.That(authState.RefreshToken, Is.Null);
		}
		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));
		}
Esempio n. 26
0
 /// <summary>
 /// The OAuth 2.0 token endpoint.
 /// </summary>
 /// <returns>The response to the Client.</returns>
 public ActionResult Token()
 {
     using (OAuth2AuthorizationServer server = (new OAuth2AuthorizationServer(new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToPfx"], ConfigurationManager.AppSettings["CertificatePassword"]),
                     new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToCertificate"]))))
     {
         AuthorizationServer authorizationServer = new AuthorizationServer(server);
         OutgoingWebResponse response = authorizationServer.HandleTokenRequest(this.Request);
         return response.AsActionResult();
     }
 }