Defines constants for key user token policies.
상속: IFormattable
예제 #1
0
        public static string RequestTokenForApplication(UserTokenPolicy policy, string clientId, string clientSecret, string scope = null)
        {
            var task = RequestTokenForApplicationAsync(policy, clientId, clientSecret, scope);

            task.Wait();
            return(task.Result);
        }
예제 #2
0
        /// <summary>
        /// Returns the UserTokenPolicies supported by the server.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        /// <returns>Returns a collection of UserTokenPolicy objects, the return type is <seealso cref="UserTokenPolicyCollection"/> . </returns>
        public virtual UserTokenPolicyCollection GetUserTokenPolicies(ApplicationConfiguration configuration, EndpointDescription description)
        {
            int policyId = 0;
            UserTokenPolicyCollection policies = new UserTokenPolicyCollection();

            if (configuration.ServerConfiguration == null || configuration.ServerConfiguration.UserTokenPolicies == null)
            {
                return(policies);
            }

            foreach (UserTokenPolicy policy in configuration.ServerConfiguration.UserTokenPolicies)
            {
                UserTokenPolicy clone = (UserTokenPolicy)policy.MemberwiseClone();

                if (String.IsNullOrEmpty(policy.SecurityPolicyUri))
                {
                    // ensure each policy has a unique id.
                    if (description.SecurityMode == MessageSecurityMode.None)
                    {
                        // ensure a security policy is specified for user tokens.
                        clone.SecurityPolicyUri = SecurityPolicies.Basic256;
                        clone.PolicyId          = Utils.Format("{0}", ++policyId);
                    }
                    else
                    {
                        clone.PolicyId = Utils.Format("{0}", policyId++);
                    }

                    policyId++;
                }
                else
                {
                    clone.PolicyId = Utils.Format("{0}", policyId++);
                }

                policies.Add(clone);
            }

            return(policies);
        }
예제 #3
0
        /// <summary>
        /// Returns the UserTokenPolicies supported by the server.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        /// <returns>Returns a collection of UserTokenPolicy objects, the return type is <seealso cref="UserTokenPolicyCollection"/> . </returns>
        public virtual UserTokenPolicyCollection GetUserTokenPolicies(ApplicationConfiguration configuration, EndpointDescription description)
        {
            UserTokenPolicyCollection policies = new UserTokenPolicyCollection();

            if (configuration.ServerConfiguration == null || configuration.ServerConfiguration.UserTokenPolicies == null)
            {
                return(policies);
            }

            foreach (UserTokenPolicy policy in configuration.ServerConfiguration.UserTokenPolicies)
            {
                // ensure a security policy is specified for user tokens.
                if (description.SecurityMode == MessageSecurityMode.None)
                {
                    if (String.IsNullOrEmpty(policy.SecurityPolicyUri))
                    {
                        UserTokenPolicy clone = (UserTokenPolicy)policy.MemberwiseClone();
                        clone.SecurityPolicyUri = SecurityPolicies.Basic256;
                        policies.Add(clone);
                        continue;
                    }
                }

                policies.Add(policy);
            }

            // ensure each policy has a unique id.
            for (int ii = 0; ii < policies.Count; ii++)
            {
                if (String.IsNullOrEmpty(policies[ii].PolicyId))
                {
                    policies[ii].PolicyId = Utils.Format("{0}", ii);
                }
            }

            return(policies);
        }
예제 #4
0
        /// <summary>
        /// Called before the server starts.
        /// </summary>
        /// <param name="configuration">The object that stores the configurable configuration information for a UA application.</param>
        protected virtual void OnServerStarting(ApplicationConfiguration configuration)
        {
            // fetch properties and configuration.
            Configuration    = configuration;
            ServerProperties = LoadServerProperties();

            // ensure at least one security policy exists.
            if (configuration.ServerConfiguration != null)
            {
                if (configuration.ServerConfiguration.SecurityPolicies.Count == 0)
                {
                    configuration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy());
                }

                // ensure at least one user token policy exists.
                if (configuration.ServerConfiguration.UserTokenPolicies.Count == 0)
                {
                    UserTokenPolicy userTokenPolicy = new UserTokenPolicy();

                    userTokenPolicy.TokenType = UserTokenType.Anonymous;
                    userTokenPolicy.PolicyId  = userTokenPolicy.TokenType.ToString();

                    configuration.ServerConfiguration.UserTokenPolicies.Add(userTokenPolicy);
                }
            }

            // load the instance certificate.
            if (configuration.SecurityConfiguration.ApplicationCertificate != null)
            {
                InstanceCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find(true).Result;
            }

            if (InstanceCertificate == null)
            {
                throw new ServiceResultException(
                          StatusCodes.BadConfigurationError,
                          "Server does not have an instance certificate assigned.");
            }

            if (!InstanceCertificate.HasPrivateKey)
            {
                throw new ServiceResultException(
                          StatusCodes.BadConfigurationError,
                          "Server does not have access to the private key for the instance certificate.");
            }

            // load certificate chain.
            InstanceCertificateChain = new X509Certificate2Collection(InstanceCertificate);
            List <CertificateIdentifier> issuers = new List <CertificateIdentifier>();

            configuration.CertificateValidator.GetIssuers(InstanceCertificateChain, issuers).Wait();

            for (int i = 0; i < issuers.Count; i++)
            {
                InstanceCertificateChain.Add(issuers[i].Certificate);
            }

            // use the message context from the configuration to ensure the channels are using the same one.
            MessageContext = configuration.CreateMessageContext();

            // assign a unique identifier if none specified.
            if (String.IsNullOrEmpty(configuration.ApplicationUri))
            {
                configuration.ApplicationUri = X509Utils.GetApplicationUriFromCertificate(InstanceCertificate);

                if (String.IsNullOrEmpty(configuration.ApplicationUri))
                {
                    configuration.ApplicationUri = Utils.Format(
                        "http://{0}/{1}/{2}",
                        Utils.GetHostName(),
                        configuration.ApplicationName,
                        Guid.NewGuid());
                }
            }

            // initialize namespace table.
            MessageContext.NamespaceUris = new NamespaceTable();
            MessageContext.NamespaceUris.Append(configuration.ApplicationUri);

            // assign an instance name.
            if (String.IsNullOrEmpty(configuration.ApplicationName) && InstanceCertificate != null)
            {
                configuration.ApplicationName = InstanceCertificate.GetNameInfo(X509NameType.DnsName, false);
            }

            // save the certificate validator.
            CertificateValidator = configuration.CertificateValidator;
        }
예제 #5
0
        /// <summary>
        /// Called before the server starts.
        /// </summary>
        /// <param name="configuration">The object that stores the configurable configuration information for a UA application.</param>
        protected virtual void OnServerStarting(ApplicationConfiguration configuration)
        {            
            // fetch properties and configuration.
            Configuration = configuration;
            ServerProperties = LoadServerProperties();
            
            // ensure at least one security policy exists.
            if (configuration.ServerConfiguration != null)
            {
                if (configuration.ServerConfiguration.SecurityPolicies.Count == 0)
                {                   
                    configuration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy());
                }
                
                // ensure at least one user token policy exists.
                if (configuration.ServerConfiguration.UserTokenPolicies.Count == 0)
                {                   
                    UserTokenPolicy userTokenPolicy = new UserTokenPolicy();
                    
                    userTokenPolicy.TokenType = UserTokenType.Anonymous;
                    userTokenPolicy.PolicyId  = userTokenPolicy.TokenType.ToString();

                    configuration.ServerConfiguration.UserTokenPolicies.Add(userTokenPolicy);
                }
            }

            // load the instance certificate.
            if (configuration.SecurityConfiguration.ApplicationCertificate != null)
            {
                InstanceCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find(true);
            }

            if (InstanceCertificate == null)
            {
                throw new ServiceResultException(
                    StatusCodes.BadConfigurationError,
                    "Server does not have an instance certificate assigned.");
            }

            if (!InstanceCertificate.HasPrivateKey)
            {
                throw new ServiceResultException(
                    StatusCodes.BadConfigurationError,
                    "Server does not have access to the private key for the instance certificate.");
            }

            //load certificate chain
            //InstanceCertificateChain = new X509Certificate2Collection(InstanceCertificate);
            //List<CertificateIdentifier> issuers = new List<CertificateIdentifier>();
            //configuration.CertificateValidator.GetIssuers(InstanceCertificate, issuers);
            //for (int i = 0; i < issuers.Count; i++)
            //{
            //    InstanceCertificateChain.Add(issuers[i].Certificate);
            //}
            
            // use the message context from the configuration to ensure the channels are using the same one.
            MessageContext = configuration.CreateMessageContext();
            
            // assign a unique identifier if none specified.
            if (String.IsNullOrEmpty(configuration.ApplicationUri))
            {
                configuration.ApplicationUri = Utils.GetApplicationUriFromCertficate(InstanceCertificate);
                
                if (String.IsNullOrEmpty(configuration.ApplicationUri))
                {
                    configuration.ApplicationUri = Utils.Format(
                        "http://{0}/{1}/{2}", 
                        System.Net.Dns.GetHostName(),
                        configuration.ApplicationName, 
                        Guid.NewGuid());
                }
            }

            // initialize namespace table.
            MessageContext.NamespaceUris = new NamespaceTable();
            MessageContext.NamespaceUris.Append(configuration.ApplicationUri);
            
            // assign an instance name.
            if (String.IsNullOrEmpty(configuration.ApplicationName) && InstanceCertificate != null)
            {
                configuration.ApplicationName = InstanceCertificate.GetNameInfo(X509NameType.DnsName, false);
            }

            // save the certificate validator.
            CertificateValidator = configuration.CertificateValidator;
        }
예제 #6
0
        public static async Task <string> RequestTokenForApplicationAsync(UserTokenPolicy policy, string clientId, string clientSecret, string scope = null)
        {
            if (policy == null)
            {
                throw new ArgumentNullException("policy");
            }

            JwtEndpointParameters parameters = new JwtEndpointParameters();

            parameters.FromJson(policy.IssuerEndpointUrl);

            var configuration = await DiscoverAsync(new Uri(parameters.AuthorityUrl + "/.well-known/openid-configuration"));

            if (String.IsNullOrEmpty(scope) && parameters.Scopes != null && parameters.Scopes.Count > 0)
            {
                scope = String.Empty;

                foreach (var entry in parameters.Scopes)
                {
                    if (scope.Length > 0)
                    {
                        scope += " ";
                    }

                    scope += entry;
                }
            }

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();

                Dictionary <string, string> fields = new Dictionary <string, string>();

                fields["grant_type"]    = "client_credentials";
                fields["client_id"]     = clientId;
                fields["client_secret"] = clientSecret;

                if (!String.IsNullOrEmpty(parameters.ResourceId))
                {
                    fields["resource"] = parameters.ResourceId;
                }

                if (!String.IsNullOrEmpty(scope))
                {
                    fields["scope"] = scope;
                }

                var content = new System.Net.Http.FormUrlEncodedContent(fields);
                HttpResponseMessage response = await client.PostAsync(configuration.TokenEndpoint, content);

                if (!response.IsSuccessStatusCode)
                {
                    throw new SecurityTokenException("The could not authorize client.");
                }

                var strm = await response.Content.ReadAsStreamAsync();

                var reader = new JsonTextReader(new System.IO.StreamReader(strm));

                while (reader.Read())
                {
                    if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "access_token")
                    {
                        if (reader.Read() && reader.TokenType == JsonToken.String)
                        {
                            return((string)reader.Value);
                        }
                    }
                }
            }

            throw new SecurityTokenException("The authorization server did not return a valid JWT.");
        }
예제 #7
0
        /// <summary>
        /// Caches application description and list of available endpoints.
        /// </summary>
        private void InitializeApplicationDescription()
        {
            // this method is caches the information the first time a client connects.
            if (m_application == null)
            {
                // the serviceCertificate element in the app.config file controls what certificate is loaded.
                m_serverCertificate = OperationContext.Current.Host.Credentials.ServiceCertificate.Certificate;

                // the URL may be the discovery or the session endpoint. need to store the session endpoint.
                string endpointUrl = OperationContext.Current.Channel.LocalAddress.ToString();
                
                if (endpointUrl.EndsWith("/discovery", StringComparison.InvariantCulture))
                {
                    endpointUrl = endpointUrl.Substring(0, endpointUrl.Length - "/discovery".Length);
                }

                // The EndpointDescription stores the information specified in the ISessionEndpoint binding.
                // This structure is used in the UA discovery services and allows client applications to 
                // discover what security settings are used by the server. 

                EndpointDescription endpoint = new EndpointDescription();

                endpoint.EndpointUrl = endpointUrl;
                endpoint.SecurityMode = MessageSecurityMode.SignAndEncrypt_3;
                endpoint.SecurityPolicyUri = SecurityPolicies.Basic128Rsa15;
                endpoint.ServerCertificate = m_serverCertificate.GetRawCertData();
                endpoint.TransportProfileUri = Profiles.WsHttpXmlTransport;

                endpoint.Server = new ApplicationDescription();
                endpoint.Server.ApplicationUri = ApplicationUri;
                endpoint.Server.ApplicationType = ApplicationType.Server_0;
                endpoint.Server.DiscoveryUrls = new ListOfString();
                endpoint.Server.DiscoveryUrls.Add(endpointUrl + "/discovery");

                // no authorization supported at this time.
                UserTokenPolicy userTokenPolicy = new UserTokenPolicy();
                userTokenPolicy.TokenType = UserTokenType.Anonymous_0;
                endpoint.UserIdentityTokens = new ListOfUserTokenPolicy();
                endpoint.UserIdentityTokens.Add(userTokenPolicy);

                m_application = endpoint.Server;

                // If the server supports multiple bindings it will need multiple EndpointDescriptions. These
                // structures can be constructed automatically from the bindings in the OperationContext object
                // This example simply hard codes the settings so a mismatch between the app.config could cause
                // problems.
                
                m_endpoints = new ListOfEndpointDescription();
                m_endpoints.Add(endpoint);
            }
        }
 public UserTokenItem(UserTokenType tokenType)
 {
     Policy = new UserTokenPolicy(tokenType);
 }
 public UserTokenItem(UserTokenPolicy policy)
 {
     Policy = policy;
 }