Exemplo n.º 1
0
        // POST /token
        public HttpResponseMessage AccessToken(HttpRequestMessage request)
        {
            var authServer = new AuthorizationServer(new OAuth2AuthorizationServer());
            var message    = authServer.HandleTokenRequest(request);

            return(message.AsHttpResponseMessage());
        }
        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);

            Response.ContentType = response.Content.Headers.ContentType.ToString();
            return(response.AsActionResult());
        }
        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);
        }
Exemplo n.º 4
0
        public AuthorizationContext GetContext(IUser user, SecurityIdentifier resourceDomain, AuthorizationContextDomainDetails domainDetails)
        {
            AuthorizationServer server = domainDetails.GetServer(false);

            Exception        lastException    = null;
            HashSet <string> attemptedServers = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            while (attemptedServers.Add(server.Name))
            {
                try
                {
                    this.logger.LogTrace("Attempting to create AuthorizationContext against server {server} in domain {domain} for user {user} requesting access to resource in domain {domain} ", server.Name, domainDetails.DomainDnsName, user.MsDsPrincipalName, resourceDomain);
                    return(new AuthorizationContext(user.Sid, server.Name, domainDetails.Mapping.DoNotRequireS4U ? AuthzInitFlags.Default : AuthzInitFlags.RequireS4ULogon));
                }
                catch (AuthorizationContextException ex) when(ex.InnerException is Win32Exception we && we.HResult == -2147467259)  //RPC_NOT_AVAILABLE
                {
                    lastException = ex;
                    this.logger.LogWarning(EventIDs.AuthZContextServerCantConnect, ex, "Unable to connect to server {server}", server.Name);
                    server = domainDetails.GetServer(true);
                }
                catch (Exception ex)
                {
                    lastException = ex;
                    this.logger.LogError(EventIDs.AuthZContextCreateError, ex, "Unable to create AuthorizationContext against server {server} in domain {domain}", server.Name, domainDetails.DomainDnsName);
                }
            }

            throw lastException ?? new Exception("Unable to create authorization context");
        }
Exemplo n.º 5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Request.IsSecureConnection)
        {
            throw new HttpException((int)HttpStatusCode.Forbidden, "Authorization requests MUST be on a secure channel");
        }

        if (String.IsNullOrEmpty(Request.PathInfo))
        {
            AuthorizationServer authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
            OutgoingWebResponse wr = authorizationServer.HandleTokenRequest();
            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(wr.Body);
            Response.End();
        }
        else
        {
            using (OAuthServiceCall service = new OAuthServiceCall(Request))
            {
                Response.Clear();
                Response.ContentType = service.ContentType;
                service.Execute(Response.OutputStream);
                Response.End();
            }
        }
    }
Exemplo n.º 6
0
        public ActionResult Issue()
        {
            var authorizationServer = new AuthorizationServer(new AuthorizationServerHost());
            var response            = authorizationServer.HandleTokenRequest(Request).AsActionResult();

            return(response);
        }
Exemplo n.º 7
0
        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));
        }
Exemplo n.º 8
0
        //[HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
        public ActionResult Authorise()
        {
            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.");
                }

                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));
            }
        }
Exemplo n.º 9
0
        //[HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
        public ActionResult Authorise()
        {
            var authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServerHost());
            var pendingRequest      = authorizationServer.ReadAuthorizationRequest();

            if (pendingRequest == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
            }
            var service          = ServiceFactory.GetOAuth2AuthService();
            var requestingClient = service.GetOAuthClient(pendingRequest.ClientIdentifier);

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

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

            return(View(model));
        }
Exemplo n.º 10
0
        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));
        }
Exemplo n.º 11
0
        private async Task <string> ObtainValidAccessTokenAsync()
        {
            string accessToken = null;
            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);
            accessToken = authState.AccessToken;

            return(accessToken);
        }
Exemplo n.º 12
0
        public async Task ListAuthorizationServerKeys()
        {
            var testClient = TestClient.Create();
            var testAuthorizationServerName = $"{SdkPrefix}:Test AuthZ Server ({TestClient.RandomString(4)})";

            var testAuthorizationServer = new AuthorizationServer
            {
                Name        = testAuthorizationServerName,
                Description = "Test Authorization Server",
                Audiences   = new string[] { "api://default" },
            };

            var createdAuthorizationServer = await testClient.AuthorizationServers.CreateAuthorizationServerAsync(testAuthorizationServer);

            try
            {
                var authorizationServerKeys = await createdAuthorizationServer.ListKeys().ToListAsync();

                authorizationServerKeys.Should().NotBeNull();
                authorizationServerKeys.Count.Should().BeGreaterThan(0);
            }
            finally
            {
                await createdAuthorizationServer.DeactivateAsync();

                await testClient.AuthorizationServers.DeleteAuthorizationServerAsync(createdAuthorizationServer.Id);
            }
        }
Exemplo n.º 13
0
        public async Task ListCreatedAuthorizationServer()
        {
            var testClient = TestClient.Create();
            var testAuthorizationServerName = $"{SdkPrefix}:Test AuthZ Server ({TestClient.RandomString(4)})";
            var testAuthorizationServer     = new AuthorizationServer
            {
                Name        = testAuthorizationServerName,
                Description = "Test Authorization Server",
                Audiences   = new string[] { "api://default" },
            };

            var createdAuthorizationServer = await testClient.AuthorizationServers.CreateAuthorizationServerAsync(testAuthorizationServer);

            try
            {
                var authorizationServerIds = await testClient.AuthorizationServers.ListAuthorizationServers().Select(server => server.Id).ToHashSetAsync();

                authorizationServerIds.Should().Contain(createdAuthorizationServer.Id);
            }
            finally
            {
                await createdAuthorizationServer.DeactivateAsync();

                await testClient.AuthorizationServers.DeleteAuthorizationServerAsync(createdAuthorizationServer.Id);
            }
        }
Exemplo n.º 14
0
        public async Task CreateOAuth2Scope()
        {
            var testClient = TestClient.Create();
            var testAuthorizationServerName = $"{SdkPrefix}:Test AuthZ Server ({TestClient.RandomString(4)})";

            var testAuthorizationServer = new AuthorizationServer
            {
                Name        = testAuthorizationServerName,
                Description = "Test Authorization Server",
                Audiences   = new string[] { "api://default" },
            };
            var testOAuthScope = new OAuth2Scope
            {
                Name = $"{SdkPrefix}:{nameof(CreateOAuth2Scope)}:TestOAuth2Scope({TestClient.RandomString(4)})",
            };

            var createdAuthorizationServer = await testClient.AuthorizationServers.CreateAuthorizationServerAsync(testAuthorizationServer);

            var createdOAuthScope = await createdAuthorizationServer.CreateOAuth2ScopeAsync(testOAuthScope);

            try
            {
                createdOAuthScope.Should().NotBeNull();
                createdOAuthScope.Name.Should().Be(testOAuthScope.Name);
            }
            finally
            {
                await createdAuthorizationServer.DeleteOAuth2ScopeAsync(createdOAuthScope.Id);

                await createdAuthorizationServer.DeactivateAsync();

                await testClient.AuthorizationServers.DeleteAuthorizationServerAsync(createdAuthorizationServer.Id);
            }
        }
Exemplo n.º 15
0
        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));
        }
Exemplo n.º 16
0
        public async Task ActivateAuthorizationServer()
        {
            var testClient = TestClient.Create();
            var testAuthorizationServerName = $"{SdkPrefix}:Test AuthZ Server ({TestClient.RandomString(4)})";

            var testAuthorizationServer = new AuthorizationServer
            {
                Name        = testAuthorizationServerName,
                Description = "Test Authorization Server",
                Audiences   = new string[] { "api://default" },
            };

            var createdAuthorizationServer = await testClient.AuthorizationServers.CreateAuthorizationServerAsync(testAuthorizationServer);

            try
            {
                createdAuthorizationServer.Should().NotBeNull();
                createdAuthorizationServer.Status.Should().Be("ACTIVE");

                await testClient.AuthorizationServers.DeactivateAuthorizationServerAsync(createdAuthorizationServer.Id);

                await testClient.AuthorizationServers.ActivateAuthorizationServerAsync(createdAuthorizationServer.Id);

                var retrievedDeactivatedAuthorizationServer = await testClient.AuthorizationServers.GetAuthorizationServerAsync(createdAuthorizationServer.Id);

                retrievedDeactivatedAuthorizationServer.Status.Should().Be("ACTIVE");
            }
            finally
            {
                await createdAuthorizationServer.DeactivateAsync();

                await testClient.AuthorizationServers.DeleteAuthorizationServerAsync(createdAuthorizationServer.Id);
            }
        }
Exemplo n.º 17
0
        public async Task DeleteAuthorizationServer()
        {
            var testClient = TestClient.Create();
            var testAuthorizationServerName = $"{SdkPrefix}:Test AuthZ Server ({TestClient.RandomString(4)})";

            var testAuthorizationServer = new AuthorizationServer
            {
                Name        = testAuthorizationServerName,
                Description = "Test Authorization Server",
                Audiences   = new string[] { "api://default" },
            };

            var createdAuthorizationServer = await testClient.AuthorizationServers.CreateAuthorizationServerAsync(testAuthorizationServer);

            createdAuthorizationServer.Should().NotBeNull();
            var retrievedAuthorizationServer = await testClient.AuthorizationServers.GetAuthorizationServerAsync(createdAuthorizationServer.Id);

            retrievedAuthorizationServer.Should().NotBeNull();

            await createdAuthorizationServer.DeactivateAsync();

            await testClient.AuthorizationServers.DeleteAuthorizationServerAsync(createdAuthorizationServer.Id);

            var ex = await Assert.ThrowsAsync <OktaApiException>(() => testClient.AuthorizationServers.GetAuthorizationServerAsync(createdAuthorizationServer.Id));

            ex.StatusCode.Should().Be(404);
        }
Exemplo n.º 18
0
 public OAuthController(AuthorizationServer authorizationServer, IRepository <Client> clientRep,
                        IRepository <User> userRep, IRepository <ClientAuthorization> clientAuthRep)
 {
     m_AuthorizationServer = authorizationServer;
     m_ClientRep           = clientRep;
     m_UserRep             = userRep;
     m_ClientAuthRep       = clientAuthRep;
 }
Exemplo n.º 19
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());
        }
Exemplo n.º 20
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());
     }
 }
Exemplo n.º 21
0
        public async Task GetAuthorizationServerPolicy()
        {
            var testClient = TestClient.Create();
            var testAuthorizationServerName = $"{SdkPrefix}:Test AuthZ Server ({TestClient.RandomString(4)})";

            var testAuthorizationServer = new AuthorizationServer
            {
                Name        = testAuthorizationServerName,
                Description = "Test Authorization Server",
                Audiences   = new string[] { "api://default" },
            };
            var testPolicy = new Policy
            {
                Type        = PolicyType.OAuthAuthorizationPolicy,
                Status      = "ACTIVE",
                Name        = "Test Policy",
                Description = "Test policy",
                Priority    = 1,
                Conditions  = new PolicyRuleConditions
                {
                    Clients = new ClientPolicyCondition
                    {
                        Include = new List <string> {
                            "ALL_CLIENTS"
                        },
                    },
                },
            };

            var createdAuthorizationServer = await testClient.AuthorizationServers.CreateAuthorizationServerAsync(testAuthorizationServer);

            var createdPolicy = await createdAuthorizationServer.CreatePolicyAsync(testPolicy);

            try
            {
                createdAuthorizationServer.Should().NotBeNull();
                createdPolicy.Should().NotBeNull();

                var retrievedPolicy = await createdAuthorizationServer.GetPolicyAsync(createdPolicy.Id);

                retrievedPolicy.Should().NotBeNull();
                retrievedPolicy.Id.Should().Be(createdPolicy.Id);
                retrievedPolicy.Name.Should().Be(createdPolicy.Name);
                retrievedPolicy.Description.Should().Be(createdPolicy.Description);
            }
            finally
            {
                await createdAuthorizationServer.DeletePolicyAsync(createdPolicy.Id);

                await createdAuthorizationServer.DeactivateAsync();

                await testClient.AuthorizationServers.DeleteAuthorizationServerAsync(createdAuthorizationServer.Id);
            }
        }
Exemplo n.º 22
0
        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);
        }
Exemplo n.º 23
0
        private OutgoingWebResponse GetResponse(IRequest request, CreateAccessToken jsonRequest)
        {
            var authZServer = new AuthorizationServer(OAuthorizationServer);

            if (request.ContentType == MimeTypes.Json)
            {
                // Request is coming from A JSON client
                return(authZServer.HandleTokenRequest(ConvertJsonRequestToFormRequest(request, jsonRequest)));
            }
            // Request is likely coming from DNOA client
            return(authZServer.HandleTokenRequest((HttpRequestBase)request.OriginalRequest));
        }
Exemplo n.º 24
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);
        }
Exemplo n.º 25
0
        public async Task UpdateOAuth2Claim()
        {
            var testClient = TestClient.Create();
            var testAuthorizationServerName = $"{SdkPrefix}:Test AuthZ Server ({TestClient.RandomString(4)})";

            var testAuthorizationServer = new AuthorizationServer
            {
                Name        = testAuthorizationServerName,
                Description = "Test Authorization Server",
                Audiences   = new string[] { "api://default" },
            };
            var testOAuthClaim = new OAuth2Claim
            {
                Name      = $"{SdkPrefix}_{nameof(UpdateOAuth2Claim)}_TestOAuth2Claim_{TestClient.RandomString(4)}",
                Status    = "INACTIVE",
                ClaimType = "RESOURCE",
                ValueType = "EXPRESSION",
                Value     = "\"driving!\"",
            };
            var testUpdatedOAuthClaim = new OAuth2Claim
            {
                Name      = $"{SdkPrefix}_{nameof(UpdateOAuth2Claim)}_TestOAuth2Claim_Updated_{TestClient.RandomString(4)}",
                Status    = "INACTIVE",
                ClaimType = "RESOURCE",
                ValueType = "EXPRESSION",
                Value     = "\"driving!\"",
            };

            var createdAuthorizationServer = await testClient.AuthorizationServers.CreateAuthorizationServerAsync(testAuthorizationServer);

            var createdOAuthClaim = await createdAuthorizationServer.CreateOAuth2ClaimAsync(testOAuthClaim);

            try
            {
                createdAuthorizationServer.Should().NotBeNull();
                createdOAuthClaim.Should().NotBeNull();
                createdOAuthClaim.Name.Should().Be(testOAuthClaim.Name);
                var updatedOAuthScope = await createdAuthorizationServer.UpdateOAuth2ClaimAsync(testUpdatedOAuthClaim, createdOAuthClaim.Id);

                updatedOAuthScope.Should().NotBeNull();
                updatedOAuthScope.Name.Should().Be(testUpdatedOAuthClaim.Name);
            }
            finally
            {
                await createdAuthorizationServer.DeleteOAuth2ClaimAsync(createdOAuthClaim.Id);

                await createdAuthorizationServer.DeactivateAsync();

                await testClient.AuthorizationServers.DeleteAuthorizationServerAsync(createdAuthorizationServer.Id);
            }
        }
Exemplo n.º 26
0
        public async Task CreateAccessTokenSeesAuthorizingUserAuthorizationCodeGrant()
        {
            var authServerMock = CreateAuthorizationServerMock();

            authServerMock
            .Setup(a => a.IsAuthorizationValid(It.IsAny <IAuthorizationDescription>()))
            .Returns <IAuthorizationDescription>(req => {
                Assert.That(req.User, Is.EqualTo(ResourceOwnerUsername));
                return(true);
            });

            Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
                async(req, ct) => {
                var server  = new AuthorizationServer(authServerMock.Object);
                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(authServerMock.Object);
                return(await server.HandleTokenRequestAsync(req, ct));
            });

            var client    = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
            var authState = new AuthorizationState(TestScopes)
            {
                Callback = ClientCallback,
            };
            var authRedirectResponse = await client.PrepareRequestUserAuthorizationAsync(authState);

            this.HostFactories.CookieContainer.SetCookies(authRedirectResponse, ClientCallback);
            Uri authCompleteUri;

            this.HostFactories.AllowAutoRedirects = false;
            using (var httpClient = this.HostFactories.CreateHttpClient()) {
                using (var response = await httpClient.GetAsync(authRedirectResponse.Headers.Location)) {
                    Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redirect));
                    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);
        }
Exemplo n.º 27
0
        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();
            }
        }
Exemplo n.º 28
0
        public async Task ListAuthorizationServerPolicies()
        {
            var testClient = TestClient.Create();
            var testAuthorizationServerName = $"{SdkPrefix}:Test AuthZ Server ({TestClient.RandomString(4)})";

            var testAuthorizationServer = new AuthorizationServer
            {
                Name        = testAuthorizationServerName,
                Description = "Test Authorization Server",
                Audiences   = new string[] { "api://default" },
            };
            var testPolicy = new Policy
            {
                Type        = PolicyType.OAuthAuthorizationPolicy,
                Status      = "ACTIVE",
                Name        = "Test Policy",
                Description = "Test policy",
                Priority    = 1,
                Conditions  = new PolicyRuleConditions
                {
                    Clients = new ClientPolicyCondition
                    {
                        Include = new List <string> {
                            "ALL_CLIENTS"
                        },
                    },
                },
            };

            var createdAuthorizationServer = await testClient.AuthorizationServers.CreateAuthorizationServerAsync(testAuthorizationServer);

            var createdPolicy = await createdAuthorizationServer.CreatePolicyAsync(testPolicy);

            try
            {
                var policies = await createdAuthorizationServer.ListPolicies().ToListAsync();

                policies.Should().NotBeNull();
                policies.Count.Should().BeGreaterThan(0);
                policies.Select(p => p.Id).ToHashSet().Should().Contain(createdPolicy.Id);
            }
            finally
            {
                await createdAuthorizationServer.DeletePolicyAsync(createdPolicy.Id);

                await createdAuthorizationServer.DeactivateAsync();

                await testClient.AuthorizationServers.DeleteAuthorizationServerAsync(createdAuthorizationServer.Id);
            }
        }
Exemplo n.º 29
0
        internal override void Run()
        {
            var authServer = new AuthorizationServer(this.authServerHost);

            var rpCoordinatingChannel = new CoordinatingOAuth2ClientChannel(this.client.Channel, this.IncomingMessageFilter, this.OutgoingMessageFilter);
            var opCoordinatingChannel = new CoordinatingOAuth2AuthServerChannel(authServer.Channel, this.IncomingMessageFilter, this.OutgoingMessageFilter);

            rpCoordinatingChannel.RemoteChannel = opCoordinatingChannel;
            opCoordinatingChannel.RemoteChannel = rpCoordinatingChannel;

            this.client.Channel = rpCoordinatingChannel;
            authServer.Channel  = opCoordinatingChannel;

            this.RunCore(this.client, authServer);
        }
Exemplo n.º 30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Request.IsSecureConnection)
            {
                throw new HttpException((int)HttpStatusCode.Forbidden, "Authorization requests MUST be on a secure channel");
            }

            if (String.IsNullOrEmpty(Request.PathInfo))
            {
                AuthorizationServer authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
                OutgoingWebResponse wr = authorizationServer.HandleTokenRequest();
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.Write(wr.Body);
                Response.End();
            }
            else
            {
                using (OAuthServiceCall service = new OAuthServiceCall(Request))
                {
                    Response.Clear();
                    Response.ContentType = service.ContentType;
                    service.Execute(Response.OutputStream);
                    Response.End();
                }
            }
        }
        catch (Exception ex)
        {
            var o = Request.Params["dbg"];
            if (o != null)
            {
                Response.Clear();
                Response.ContentType     = "text/plain";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.Write("Error: " + ex.Message + "\r\n");
                Response.Write(ex.ToStringDescriptive() + "\r\n");
                Response.Flush();
                Response.End();
            }
            else
            {
                throw;
            }
        }
    }