public override void Execute(IRequest request, IResponse response, object requestDto)
        {
            try
            {
                var            cryptoKeyProvider = ServiceStackHost.Instance.Container.Resolve <ICryptoKeyProvider>();
                ICryptoKeyPair authZServerKeys   = cryptoKeyProvider.GetCryptoKey(CryptoKeyType.AuthZServer);
                ICryptoKeyPair apiServiceKeys    = cryptoKeyProvider.GetCryptoKey(CryptoKeyType.ApiService);

                var tokenAnalyzer = new StandardAccessTokenAnalyzer(authZServerKeys.PublicSigningKey,
                                                                    apiServiceKeys.PrivateEncryptionKey);
                var resourceServer = new ResourceServer(tokenAnalyzer);

                // Verify the signed bearer token (for specified scopes), and extract the user's identity
                AccessToken token = resourceServer.GetAccessToken((HttpRequestBase)request.OriginalRequest, scopes);

                // Assign this user to the current HTTP context
                var user = new OAuthPrincipal(token.User, GetUserRoles(token));
                ((HttpRequestBase)request.OriginalRequest).RequestContext.HttpContext.User = user;
            }
            catch (ProtocolFaultResponseException ex)
            {
                //TODO: if the token is invalid in some way (i.e. malformed) then return 400-BadRequest.
                // The token is either: expired or invalid or revoked, we need to return 401-Unauthorized
                response.AddHeader(HttpHeaders.WwwAuthenticate, @"Bearer");
                throw HttpErrorThrower.Unauthorized(ex.Message);
            }
        }
 protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     if (request.Headers.Authorization != null)
     {
         if (request.Headers.Authorization.Scheme == "Bearer")
         {
             //If there are authorization headers that use the Bearer token scheme, try to digest the token and, if available,
             //set the current user context.
             try
             {
                 var AuthServerPublicKey      = (RSACryptoServiceProvider)AuthorizationServerHost.AuthorizationServerCertificate.PublicKey.Key;
                 var ResourceServerPrivateKey = (RSACryptoServiceProvider)AuthorizationServerHost.ResourceServerCertificate.PrivateKey;
                 var resourceServer           = new ResourceServer(new StandardAccessTokenAnalyzer(AuthServerPublicKey, ResourceServerPrivateKey));
                 var principal = resourceServer.GetPrincipal(request);
                 HttpContext.Current.User = principal;
                 Thread.CurrentPrincipal  = principal;
             }
             catch (ProtocolFaultResponseException ex)
             {
                 //A protocol fault response exception is thrown in the case that a client cannot be properly authenticated by the provided
                 //token. To diagnose any errors you may be getting, you can re-throw or log ex.ErrorResponseMessage.
                 //For now, let's just inform the client that they're unauthorized for this resource.
                 SendUnauthorizedResponse();
             }
         }
     }
     else
     {
         //This API does not allow unauthenticated access, return an unauthorized status code.
         SendUnauthorizedResponse();
     }
     return(base.SendAsync(request, cancellationToken));
 }
        public OAuthServiceCall(HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            OriginalRequest  = request;
            ServiceCall      = ServiceFromString(request.PathInfo);
            ResponseCallback = util.GetStringParam(request, "callback");
            ResultFormat     = (util.GetIntParam(request, "json", 0) != 0) ? (String.IsNullOrEmpty(ResponseCallback) ? OutputFormat.JSON : OutputFormat.JSONP) : OutputFormat.XML;

            using (RSACryptoServiceProvider rsaSigning = new RSACryptoServiceProvider())
            {
                using (RSACryptoServiceProvider rsaEncryption = new RSACryptoServiceProvider())
                {
                    rsaSigning.ImportParameters(OAuth2AuthorizationServer.AuthorizationServerSigningPublicKey);
                    rsaEncryption.ImportParameters(OAuth2AuthorizationServer.CreateAuthorizationServerSigningKey());
                    ResourceServer server = new ResourceServer(new StandardAccessTokenAnalyzer(rsaSigning, rsaEncryption));
                    Token = server.GetAccessToken();

                    if (Token.Lifetime.HasValue && Token.UtcIssued.Add(Token.Lifetime.Value).CompareTo(DateTime.UtcNow) < 0)
                    {
                        throw new MyFlightbookException("oAuth2 - Token has expired!");
                    }
                    if (String.IsNullOrEmpty(Token.User))
                    {
                        throw new MyFlightbookException("Invalid oAuth token - no user");
                    }

                    GeneratedAuthToken = MFBWebService.AuthTokenFromOAuthToken(Token);
                }
            }
        }
Example #4
0
        public void TestResourceServer()
        {
            m_noAdmitCount = 0;
            m_admitCount   = 0;

            m_model = new Model();
            ((Model)m_model).RandomServer = new Randoms.RandomServer(54321, 100);

            ItemSource factory = CreatePatientGenerator("Patient_", 25, 5.0, 3.0);
            Queue      queue   = new Queue(m_model, "TestQueue", Guid.NewGuid());

            ConnectorFactory.Connect(factory.Output, queue.Input);

            NormalDistribution dist    = new NormalDistribution(m_model, "SvcDistribution", Guid.NewGuid(), 15.0, 3.0);
            IPeriodicity       per     = new Periodicity(dist, Periodicity.Units.Minutes);
            ResourceManager    rscPool = new ResourceManager(m_model, "RscMgr", Guid.NewGuid());

            for (int i = 0; i < 3; i++)
            {
                rscPool.Add(new Resource(m_model, "rsc_" + i, Guid.NewGuid(), 1.0, 1.0, true, true, true));
            }
            ResourceServer rs = new ResourceServer(m_model, "RscSvr", Guid.NewGuid(), per, new IResourceRequest[] { new SimpleResourceRequest(1.0, rscPool) });

            rs.PlaceInService();
            ConnectorFactory.Connect(queue.Output, rs.Input);

            factory.Output.PortDataPresented += new PortDataEvent(FactoryOutput_PortDataPresented);
            queue.LevelChangedEvent          += new QueueLevelChangeEvent(Queue_LevelChangedEvent);
            rs.ServiceBeginning += new ServiceEvent(Server_ServiceBeginning);
            rs.ServiceCompleted += new ServiceEvent(Server_ServiceCompleted);

            m_model.Start();
        }
        /// <summary>
        /// Handles the AuthenticateRequest event of the HttpApplication.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void context_AuthenticateRequest(object sender, EventArgs e)
        {
            // Don't read OAuth messages directed at the OAuth controller or else we'll fail nonce checks.
            if (this.IsOAuthControllerRequest())
            {
                return;
            }

            using (var crypto = OAuthResourceServer.CreateRSA()) {
                var tokenAnalyzer  = new SpecialAccessTokenAnalyzer(crypto, crypto);
                var resourceServer = new ResourceServer(tokenAnalyzer);
                var context        = this.application.Context;
                Task.Run(
                    async delegate {
                    ProtocolFaultResponseException exception = null;
                    try {
                        IPrincipal principal = await resourceServer.GetPrincipalAsync(new HttpRequestWrapper(context.Request));
                        context.User         = principal;
                        return;
                    } catch (ProtocolFaultResponseException ex) {
                        exception = ex;
                    }

                    var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
                    await errorResponse.SendAsync();
                }).Wait();
            }
        }
Example #6
0
        private static async Task <IPrincipal> VerifyOAuth2(HttpRequestMessage httpDetails, params string[] requiredScopes)
        {
            // for this sample where the auth server and resource server are the same site,
            // we use the same public/private key.
            var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey));

            return(await resourceServer.GetPrincipalAsync(httpDetails, requiredScopes : requiredScopes));
        }
Example #7
0
        public void TestResourceServerComplexDemands()
        {
            m_noAdmitCount = 0;
            m_admitCount   = 0;

            m_model = new Model();
            ((Model)m_model).RandomServer = new Randoms.RandomServer(54321, 100);

            ItemSource factory = CreatePatientGenerator("Patient_", 50, 5.0, 3.0);
            Queue      queue   = new Queue(m_model, "TestQueue", Guid.NewGuid());

            ConnectorFactory.Connect(factory.Output, queue.Input);

            NormalDistribution   dist    = new NormalDistribution(m_model, "SvcDistribution", Guid.NewGuid(), 240.0, 45.0);
            IPeriodicity         per     = new Periodicity(dist, Periodicity.Units.Minutes);
            SelfManagingResource nursing = new SelfManagingResource(m_model, "Nursing", Guid.NewGuid(), 7.0, 7.0, false, false, true);
            SelfManagingResource clerks  = new SelfManagingResource(m_model, "Clerks", Guid.NewGuid(), 6.0, 6.0, false, false, true);
            SelfManagingResource doctors = new SelfManagingResource(m_model, "Doctors", Guid.NewGuid(), 2.0, 2.0, false, false, true);

            MultiResourceTracker mrt = new MultiResourceTracker(m_model);

            mrt.Filter = ResourceEventRecordFilters.AcquireAndReleaseOnly;
            //mrt.Filter = ResourceTracker.Filters.AllEvents;
            mrt.AddTargets(nursing, clerks, doctors);

            IResourceRequest[] demands = new IResourceRequest[] {
                new SimpleResourceRequest(.20, nursing),
                new SimpleResourceRequest(.15, clerks),
                new SimpleResourceRequest(.05, doctors)
            };

            ResourceServer rs = new ResourceServer(m_model, "RscSvr", Guid.NewGuid(), per, demands);

            rs.PlaceInService();
            ConnectorFactory.Connect(queue.Output, rs.Input);

            factory.Output.PortDataPresented += new PortDataEvent(FactoryOutput_PortDataPresented);
            queue.LevelChangedEvent          += new QueueLevelChangeEvent(Queue_LevelChangedEvent);
            rs.ServiceBeginning += new ServiceEvent(Server_ServiceBeginning);
            rs.ServiceCompleted += new ServiceEvent(Server_ServiceCompleted);

            m_model.Start();

//          string dataFileName = Highpoint.Sage.Utility.DirectoryOperations.GetAppDataDir() + @"Data.csv";
//			System.IO.TextWriter tw = new System.IO.StreamWriter(dataFileName);
//			foreach ( ResourceEventRecord rer in mrt ) {
//				tw.WriteLine(rer.When.ToLongTimeString()+","
//					+rer.Resource.Name+","
//					+rer.Action.ToString()+","
//					+rer.Available	);
//			}
//			tw.Close();
//			System.Diagnostics.Process.Start("excel.exe","\""+dataFileName+"\"");

            Console.WriteLine(new CSVDumper(mrt, new CompoundComparer(ResourceEventRecord.ByAction(false), ResourceEventRecord.ByTime(false))).ToString());
        }
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            if (!base.CheckAccessCore(operationContext))
            {
                return(false);
            }

            var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            var requestUri  = operationContext.RequestContext.RequestMessage.Properties.Via;

            return(Task.Run(
                       async delegate {
                using (var crypto = OAuthResourceServer.CreateRSA()) {
                    var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto);
                    var resourceServer = new ResourceServer(tokenAnalyzer);
                    ProtocolFaultResponseException exception = null;
                    try {
                        IPrincipal principal =
                            await resourceServer.GetPrincipalAsync(httpDetails, requestUri, CancellationToken.None, operationContext.IncomingMessageHeaders.Action);
                        var policy = new OAuthPrincipalAuthorizationPolicy(principal);
                        var policies = new List <IAuthorizationPolicy> {
                            policy,
                        };

                        var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
                        if (operationContext.IncomingMessageProperties.Security != null)
                        {
                            operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
                        }
                        else
                        {
                            operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
                                ServiceSecurityContext = securityContext,
                            };
                        }

                        securityContext.AuthorizationContext.Properties["Identities"] = new List <IIdentity> {
                            principal.Identity,
                        };

                        return true;
                    } catch (ProtocolFaultResponseException ex) {
                        // Return the appropriate unauthorized response to the client.
                        exception = ex;
                    } catch (DotNetOpenAuth.Messaging.ProtocolException /* ex*/) {
                        ////Logger.Error("Error processing OAuth messages.", ex);
                    }

                    var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
                    await errorResponse.SendAsync();
                }

                return false;
            }).Result);
        }
        public void GetPrincipalWithMissingAccessToken()
        {
            var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null));

            var requestHeaders = new NameValueCollection {
                { "Authorization", "Bearer " },
            };
            var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders);

            Assert.That(() => resourceServer.GetPrincipal(request), Throws.InstanceOf <ProtocolException>());
        }
 private static async Task <IPrincipal> VerifyOAuth2Async(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes)
 {
     // for this sample where the auth server and resource server are the same site,
     // we use the same public/private key.
     using (var signing = Global.CreateAuthorizationServerSigningServiceProvider()) {
         using (var encrypting = Global.CreateResourceServerEncryptionServiceProvider()) {
             var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(signing, encrypting));
             return(await resourceServer.GetPrincipalAsync(httpDetails, requestUri, requiredScopes : requiredScopes));
         }
     }
 }
Example #11
0
        public void GetAccessTokenWithTotallyFakeToken()
        {
            var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null));

            var requestHeaders = new NameValueCollection {
                { "Authorization", "Bearer foobar" },
            };
            var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders);

            Assert.That(() => resourceServer.GetAccessTokenAsync(request).GetAwaiter().GetResult(), Throws.InstanceOf <ProtocolException>());
        }
Example #12
0
        /// <summary>
        /// OAuth resource provider.
        /// </summary>
        /// <param name="tokenStore">The token store</param>
        /// <param name="consumerStore">The consumer store</param>
        /// <param name="nonceStore">The nonce store.</param>
        public AuthResource(ITokenStore tokenStore, IConsumerStore consumerStore, INonceStore nonceStore)
        {
            _tokenStore    = tokenStore;
            _consumerStore = consumerStore;
            _nonceStore    = nonceStore;

            ValidateEx();

            // Create the resource provider.
            _resourceServer = new ResourceServer();
        }
Example #13
0
        /// <summary>
        /// Parses out server name from a resource server. Uses the Resource server Name unless it's a database server with a port number
        /// </summary>
        public static string GetServerNameForIpAddress(ResourceServer server)
        {
            var result = server.Name;
            // if it's a DB server than anything after the last comma (,) should be the port number
            var lastCommaIndex = result.LastIndexOf(',');

            result = (lastCommaIndex > 0 && server.ServerType == ServerType.Database) ? result.Substring(0, lastCommaIndex) : result;
            if (server.ServerType == ServerType.Database && result.Contains('\\'))
            {
                result = result.Split('\\')[0];
            }
            return(result);
        }
Example #14
0
        public async Task GetAccessTokenWithCorruptedToken()
        {
            var accessToken = await this.ObtainValidAccessTokenAsync();

            var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null));

            var requestHeaders = new NameValueCollection {
                { "Authorization", "Bearer " + accessToken.Substring(0, accessToken.Length - 1) + "zzz" },
            };
            var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders);

            Assert.That(() => resourceServer.GetAccessTokenAsync(request).GetAwaiter().GetResult(), Throws.InstanceOf <ProtocolException>());
        }
Example #15
0
        public async Task GetAccessTokenWithValidToken()
        {
            var accessToken = await this.ObtainValidAccessTokenAsync();

            var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null));

            var requestHeaders = new NameValueCollection {
                { "Authorization", "Bearer " + accessToken },
            };
            var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders);
            var resourceServerDecodedToken = await resourceServer.GetAccessTokenAsync(request);

            Assert.That(resourceServerDecodedToken, Is.Not.Null);
        }
Example #16
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Headers.Authorization != null)
            {
                if (request.Headers.Authorization.Scheme == "Bearer")
                {
                    var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AuthorizationServerHost.HardCodedCryptoKeyStore));
                    var principal      = await resourceServer.GetPrincipalAsync(request, cancellationToken);

                    HttpContext.Current.User = principal;
                    Thread.CurrentPrincipal  = principal;
                }
            }

            return(await base.SendAsync(request, cancellationToken));
        }
 public override void OnAuthorization(HttpActionContext actionContext)
 {
     try
     {
         var tokenAnalyzer =
             new StandardAccessTokenAnalyzer(
                 AuthServer.PublicSigningKey,
                 DataServer.PrivateEncryptionKey);
         var oauth2ResourceServer = new ResourceServer(tokenAnalyzer);
         ((ApiController)actionContext.ControllerContext.Controller).User =
             oauth2ResourceServer.GetPrincipal(actionContext.Request.GetRequestBase(), _oauth2Scopes) as PlayerPrincipal;
     }
     catch (ProtocolFaultResponseException ex)
     {
         HandleUnauthorizedRequest(actionContext, ex);
     }
 }
Example #18
0
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var rsa = new RSACryptoServiceProvider();

            rsa.ImportCspBlob(Convert.FromBase64String(ConfigurationManager.AppSettings["PrivateAsymmetricKey"]));
            var analyzer       = new StandardAccessTokenAnalyzer(rsa, rsa);
            var resourceServer = new ResourceServer(analyzer);

            try {
                httpContext.User = resourceServer.GetPrincipal(
                    httpContext.Request, this.Roles.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
            } catch (ProtocolException) {
                httpContext.User = null;
            }

            return(httpContext.User != null);
        }
Example #19
0
 public override void Execute(IHttpRequest request, IHttpResponse response, object requestDto)
 {
     try
     {
         var authServerKeys = AppHostBase.Instance.Container.ResolveNamed <ICryptoKeyPair>("authServer");
         var dataServerKeys = AppHostBase.Instance.Container.ResolveNamed <ICryptoKeyPair>("dataServer");
         var tokenAnalyzer  = new StandardAccessTokenAnalyzer(authServerKeys.PublicSigningKey,
                                                              dataServerKeys.PrivateEncryptionKey);
         var oauth2ResourceServer = new ResourceServer(tokenAnalyzer);
         var wrappedRequest       = new HttpRequestWrapper((HttpRequest)request.OriginalRequest);
         HttpContext.Current.User = oauth2ResourceServer.GetPrincipal(wrappedRequest, oauth2Scopes) as PlayerPrincipal;
     }
     catch (ProtocolFaultResponseException x)
     {
         HandleOAuth2Exception(request, response, x);
     }
 }
Example #20
0
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool isAuthorized = false;

            try
            {
                HttpRequestBase request = httpContext.Request;

                if (!string.IsNullOrEmpty(request.Headers["Authorization"]))
                {
                    if (request.Headers["Authorization"].StartsWith("Bearer "))
                    {
                        RSACryptoServiceProvider authorizationServerSigningPublicKey = AuthorizationServerHost.CreateRsaCryptoServiceProvider(AuthorizationServerHost.AuthorizationServerSigningPublicKey);
                        RSACryptoServiceProvider resourceServerEncryptionPrivateKey  = AuthorizationServerHost.CreateRsaCryptoServiceProvider(AuthorizationServerHost.ResourceServerEncryptionPrivateKey);

                        StandardAccessTokenAnalyzer tokenAnalyzer = new StandardAccessTokenAnalyzer(authorizationServerSigningPublicKey, resourceServerEncryptionPrivateKey);
                        ResourceServer resourceServer             = new ResourceServer(tokenAnalyzer);
                        IPrincipal     principal = resourceServer.GetPrincipal(request);

                        if (principal.Identity.IsAuthenticated)
                        {
                            HttpContext.Current.User = principal;
                            Thread.CurrentPrincipal  = principal;

                            isAuthorized = true;
                        }

                        var _token = resourceServer.GetAccessToken(request);

                        if (this.RequiredScopes.Any())
                        {
                            var token = resourceServer.GetAccessToken(request, this.RequiredScopes);
                        }
                    }
                }
            }
            catch
            {
                isAuthorized = false;
            }

            return(isAuthorized);
        }
Example #21
0
        public static string FileDownURL(IFile file)
        {
            if (file is Attachment)
            {
                file = file as Attachment;
            }
            else if (file is IESFile)
            {
                file = file as IESFile;
            }
            else if (file is IES.Resource.Model.File)
            {
                file = file as IES.Resource.Model.File;
            }

            ResourceServer server = StoreServie.ResourceServer_Get(file.ServerID);

            return(string.Format(downurl, server.Host, server.IISPort, server.IISFolder, file.FileName));
        }
Example #22
0
        /// <summary>
        /// Handles the AuthenticateRequest event of the HttpApplication.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void context_AuthenticateRequest(object sender, EventArgs e)
        {
            // Don't read OAuth messages directed at the OAuth controller or else we'll fail nonce checks.
            if (this.IsOAuthControllerRequest())
            {
                return;
            }

            using (var crypto = OAuthResourceServer.CreateRSA()) {
                var tokenAnalyzer  = new SpecialAccessTokenAnalyzer(crypto, crypto);
                var resourceServer = new ResourceServer(tokenAnalyzer);

                try {
                    IPrincipal principal = resourceServer.GetPrincipal(new HttpRequestWrapper(this.application.Context.Request));
                    this.application.Context.User = principal;
                } catch (ProtocolFaultResponseException ex) {
                    ex.CreateErrorResponse().Send();
                }
            }
        }
Example #23
0
        /// <summary>
        /// 文件在线浏览地址 :TODO
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string FileViewURL(IFile file)
        {
            if (file is Attachment)
            {
                file = file as Attachment;
            }
            else if (file is IESFile)
            {
                file = file as IESFile;
            }
            else if (file is IES.Resource.Model.File)
            {
                file = file as IES.Resource.Model.File;
            }

            string         ext    = StringHelp.GetFileNameExt(file.FileName).ToLower();
            ResourceServer server = StoreServie.ResourceServer_Get(file.ServerID);

            return(string.Format(downurl, server.Host, server.NginxPort, server.NginxFolder, file.FileName));
        }
Example #24
0
        public async Task InitializeAsync()
        {
            var token = await GenerateManagementApiToken();

            _apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"));

            // We need a client in order to create client grants
            _client = await _apiClient.Clients.CreateAsync(new ClientCreateRequest
            {
                Name = $"Integration testing {Guid.NewGuid():N}"
            });

            // We also need to create a resource server
            var identifier = Guid.NewGuid();

            _resourceServer = await _apiClient.ResourceServers.CreateAsync(new ResourceServerCreateRequest
            {
                Identifier       = "urn:" + identifier,
                Name             = $"Integration testing {identifier:N}",
                TokenLifetime    = 1,
                SigningAlgorithm = SigningAlgorithm.RS256,
                Scopes           = new List <ResourceServerScope>
                {
                    new ResourceServerScope
                    {
                        Value       = "scope1",
                        Description = "Scope number 1"
                    },
                    new ResourceServerScope
                    {
                        Value       = "scope2",
                        Description = "Scope number 2"
                    },
                    new ResourceServerScope
                    {
                        Value       = "scope3",
                        Description = "Scope number 3"
                    }
                }
            });
        }
        public async Task CreatePerformanceDashboardAgents_FreshSuccess()
        {
            // Arrange
            var machineName = "TestServer";
            var agentServer = new ResourceServer {
                Name = machineName, ArtifactID = 123
            };
            var servers = new List <ResourceServer> {
                agentServer
            };

            this.agentManagerMock.Setup(m => m.GetAgentServersAsync()).ReturnsAsync(servers);

            this.agentRepositoryMock.Setup(m =>
                                           m.ReadAgentWithTypeExists(It.Is <Guid>(g => Guids.Agent.CurrentAgentGuids.Contains(g)))).ReturnsAsync(false);

            var agentTypeId   = 1234;
            var agentTypeRefs =
                Guids.Agent.CurrentAgentGuids.Select(cg => new AgentTypeRef(new List <Guid> {
                cg
            })
            {
                ArtifactID = agentTypeId
            }).ToList();

            this.agentManagerMock.Setup(m => m.GetAgentTypesAsync()).ReturnsAsync(agentTypeRefs);

            this.agentManagerMock.Setup(m =>
                                        m.CreateSingleAsync(It.Is <Agent>(a => a.Server.ArtifactID == agentServer.ArtifactID))).ReturnsAsync(1);

            // Act
            var result = await this.agentManagerService.CreatePerformanceDashboardAgents(machineName);

            // Assert
            Assert.That(result.Count, Is.EqualTo(Guids.Agent.CurrentAgentGuids.Count));
            this.agentManagerMock.VerifyAll();
            this.agentRepositoryMock.VerifyAll();
        }
Example #26
0
 public static bool AuthUser(HttpRequestMessage request)
 {
     using (RSACryptoServiceProvider authorizationServerRsa = GetAuthorizationServerRsa())
     {
         using (RSACryptoServiceProvider resourceServerRsa = GetResourceServerRsa())
         {
             ResourceServer resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(authorizationServerRsa, resourceServerRsa));
             var            token          = resourceServer.GetAccessToken(request, new string[0]);
             if (token != null)
             {
                 IPrincipal principal = CreatePrincipal(token.User);
                 HttpContext.Current.User = principal;
                 Thread.CurrentPrincipal  = principal;
                 request.Headers.Add("UserName", token.User);
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
     }
 }
Example #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OAuthAuthorizeAttribute"/> class.
        /// </summary>
        public OAuthAuthorizeAttribute()
        {
            var standardAccessTokenAnalyzer = new StandardAccessTokenAnalyzer(EncryptionKeys.GetAuthorizationServerSigningPublicKey(), EncryptionKeys.GetResourceServerEncryptionPrivateKey());

            this.resourceServer = new ResourceServer(standardAccessTokenAnalyzer);
        }
Example #28
0
        private static async Task <IPrincipal> VerifyOAuth2Async(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes)
        {
            var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey));

            return(await resourceServer.GetPrincipalAsync(httpDetails, requestUri, requiredScopes : requiredScopes));
        }
Example #29
0
        /// <summary>
        /// Repeatable part of the program setup. Note that the threads and database must first be disposed or null.
        /// </summary>
        static void Setup()
        {
            // Dispose existing database connections
            Utils.DisposeDatabases();

            #region Apply AppSettings
            dynamic appSettings = Config["appSettings"];

            // Create log files in release mode only
            if (!DEBUG)
            {
                Log.Config("Creating log file");
                string log = appSettings.logDir;
                // Create the directory if it doesn't exist
                try
                {
                    if (!Directory.Exists(log))
                    {
                        Directory.CreateDirectory(log);
                    }
                }
                catch (Exception e)
                {
                    Log.Fatal($"{e.GetType().Name}: {e.Message}", e, false);
                    Terminate(14001);
                }
                log += "/latest.log";
                // Delete the file if it already exists
                if (File.Exists(log))
                {
                    File.Delete(log);
                }
                Log.OutputStreams.Add(File.CreateText(log));
            }
            #endregion

            Log.Config("Creating database connection...");
            Database = Utils.GetDatabase();

            try
            {
                // Compile razor .cshtml templates
                Templates.CompileAll();
            }
            catch (Exception e)
            {
                // Print any error and terminate
                Log.Fatal("Template compilation failed:");
                Log.Fatal($"{e.GetType().Name}: {e.Message}", e);
                Terminate(1);
            }

            #region Setup Threads
            dynamic performance = Config["performance"];

            for (int i = 0; i < (int)performance.apiThreads; i++)
            {
                var server = new JsonServer(JSONQueue);
                Servers.Add(server);
                server.Start();
            }
            for (int i = 0; i < (int)performance.htmlThreads; i++)
            {
                var server = new HTMLServer(listener.Queue);
                Servers.Add(server);
                server.Start();
            }
            for (int i = 0; i < (int)performance.resourceThreads; i++)
            {
                var server = new ResourceServer(ResourceQueue);
                Servers.Add(server);
                server.Start();
            }
            #endregion
        }
Example #30
0
 public OAuth2Handler(ResourceServer resourceServer)
 {
     m_ResourceServer = resourceServer;
 }