working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,076 snippets matching: web.config

    public by cghersi  4302  2  8  0

    A generic purpose Configuration Reader for .NET apps and web sites in C#

    This class can be extended to provide the capability to read the content of your configuration file, e.g. the web.config in web sites, the app.config in applications as well as a custom file for other purposes
    using System;
    using System.Configuration;
    using System.Web;
    using System.IO;
    using System.Xml.Linq;
    using System.Xml;
    using System.Collections;
    using System.Collections.Generic;
    using log4net;
    using log4net.Config;
    
    public abstract class ConfigReader
    {
        #region PROTECTED PARAMETERS
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
        protected string m_lastErrorMessage = string.Empty;
    
        protected XDocument m_customConfig = null;  //custom config XML file
        protected string m_name = string.Empty; //just an example of a string property to be read
        protected bool m_logWarnings = false; //just an example of a boolean property to be read
    
        protected string m_rootLocalPath;
            
        #endregion
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
        #region PUBLIC PROPERTIES
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
        public string LastError { get { return m_lastErrorMessage;  } }
        public string Name { get { return m_name; } }
    	public bool LogWarnings { get { return m_logWarnings; } }
      
        #endregion
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
        #region Constructors
    
        protected ConfigReader() 
        {
        }
    
        public virtual bool Initialize(string rootPath)
        {
            m_rootLocalPath = rootPath;
    
            //Load custom config file if it is available:
            LoadCustomConfigXMLFile();
    
            GetSetting("Server", ref m_name);
            if ( !GetSetting("LogWarning", ref m_logWarnings) )
                m_logWarnings = false;
    
            // Log4Net initialization:
            FileInfo log4netFile = new FileInfo(string.Format("{0}\\log4net.config", rootPath));
            if (log4netFile.Exists)
                XmlConfigurator.Configure(log4netFile);
            else
                XmlConfigurator.Configure();
            ILog log = log4net.LogManager.GetLogger(this.GetType());
    
            log.Info("Log4net correctly started");
    
            return true;
        }
    
        #endregion
    
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
        #region Public API
    
        public string GetSetting(string propName)
        {
            try
            {
                if (ConfigurationManager.AppSettings.Get(propName) != null)
                    return ConfigurationManager.AppSettings.Get(propName).ToString();
                else if (m_customConfig != null)
                {
                    string res = string.Empty;
                    m_customConfig.Root.ParseNode(propName, ref res);
                    return res;
                }
                else
                    return string.Empty;
            }
            catch { }
    
            return string.Empty;
        }
    
        protected bool GetSetting(string propName, ref string property)
        {
            try
            {
                if (ConfigurationManager.AppSettings.Get(propName) != null)
                    property = ConfigurationManager.AppSettings.Get(propName).ToString();
                else if (m_customConfig != null)
                    m_customConfig.Root.ParseNode(propName, ref property);
                else
                    return false;
                return true;
            }
            catch 
            {
                return false;
            }
        }
    
        protected bool GetSetting(string propName, ref bool property)
        {
            string prop = string.Empty;
            if ( GetSetting(propName, ref prop) )
                return bool.TryParse(prop, out property);
            else
                return false;
        }
    
        protected bool GetSetting(string propName, ref int property)
        {
            string prop = string.Empty;
            if (GetSetting(propName, ref prop))
                return int.TryParse(prop, out property);
            else
                return false;
        }
    
        protected bool GetSetting<T>(string propName, ref T property)
        {
            string prop = string.Empty;
            if (GetSetting(propName, ref prop))
            {
                try
                {
                    property = (T)Enum.Parse(typeof(T), prop, true);
                }
                catch
                {
                    return false;
                }
                return true;
            }
            else
                return false;
        }
        #endregion
    
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
        #region Protected internal utility functions
    
        /// <summary>
        /// Load in memory the xml describing the configuration, if any
        /// </summary>
        /// ------------------------------------------------------------------------------------------
        protected bool LoadCustomConfigXMLFile()
        {
            string path = string.Format("{0}\\mycfg.config", m_rootLocalPath);
            try
            {
                m_customConfig = XDocument.Load(path);
            }
            catch
            {
                // error loading document: Not found
                m_customConfig = null;
                return false;
            }
    
            return true;
        }
    
        #endregion
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    }
    

    public by Tech_JA  413  0  5  0

    web.config

    web.config for IIS 8.5 to work with SLIM framework
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="slim" patternSyntax="Wildcard">
                        <match url="*" />
                        <conditions>
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        </conditions>
                        <action type="Rewrite" url="index.php" />
                    </rule>
                </rules>
            </rewrite>
    		<httpProtocol>
    			<customHeaders>
    				<add name="Access-Control-Allow-Origin" value="*" />
    			</customHeaders>
    		</httpProtocol>
        </system.webServer>
    </configuration>           

    public by afelicioni  3689  0  3  0

    IIS woff2 mime fix

    IIS woff2 mime fix: web.config
    <staticContent>
    <remove fileExtension=".woff" />
    <remove fileExtension=".woff2" />
    <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
    <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
    </staticContent>
    
    

    public by Kevin Ross  255  0  3  0

    Development webpack config - http://stackoverflow.com/questions/41420329/consuming-pure-es2015-libraries-with-webpack-2

    Development webpack config - http://stackoverflow.com/questions/41420329/consuming-pure-es2015-libraries-with-webpack-2: webpack.config.js
    const config = {
      devtool: 'source-map',
      devServer: {
        port: 3808,
        headers: {
          'Access-Control-Allow-Origin': '*'
        }
      },
      context: '/Users/kross/projects/af/spec/dummy',
      entry: {
        application: [
          'react-hot-loader/patch',
          'webpack-dev-server/client?http://localhost:3808',
          'webpack/hot/only-dev-server',
          './ui/src/index.js'
        ],
        vendor: [
          '@alienfast/material-ui',
          'classnames',
          'cookie',
          'core-js',
          'dom-helpers',
          'dompurify',
          'es-collections',
          'fbemitter',
          'graphql',
          'graphql-relay',
          'i18next',
          'i18next-browser-languagedetector',
          'i18next-localstorage-cache',
          'i18next-sprintf-postprocessor',
          'jwt-decode',
          'jss',
          'jss-camel-case',
          'jss-compose',
          'jss-default-unit',
          'jss-expand',
          'jss-global',
          'jss-nested',
          'jss-preset-default',
          'jss-props-sort',
          'jss-theme-reactor',
          'key.js',
          'lodash',
          'material-ui',
          'md5',
          'query-string',
          'react',
          'react-dom',
          'react-formal',
          'react-helmet',
          'react-i18next',
          'react-relay',
          'react-relay-network-layer',
          'react-router',
          'react-router-relay',
          'react-sizeme',
          'react-tap-event-plugin',
          'recompose',
          'ua-parser-js',
          'whatwg-fetch',
          'yup'
        ]
      },
      output: {
        path: '/Users/kross/projects/af/spec/dummy/public/webpack',
        publicPath: '//localhost:3808/webpack/',
        filename: '[name].js'
      },
      resolve: {
        extensions: [
          '.js',
          '.jsx',
          '.json'
        ],
        alias: {
          react: '/Users/kross/projects/af/spec/dummy/node_modules/react',
          'react-relay': '/Users/kross/projects/af/spec/dummy/node_modules/react-relay'
        }
      },
      module: {
        loaders: [
          {
            test: /\.jsx?$/,
            include: [
              '/Users/kross/projects/af/spec/dummy/ui/src',
              '/Users/kross/projects/af/spec/dummy/ui/tests',
              '/Users/kross/projects/af/spec/dummy/node_modules/react',
              '/Users/kross/projects/af/spec/dummy/node_modules/react-relay'
            ],
            exclude: /node_modules\/(?!(react|react-relay)\/).*/,
            loaders: [
              'happypack/loader'
            ]
          },
          {
            test: /\.json$/,
            loader: 'json-loader'
          },
          {
            test: /\.svg(\?.*)?$/,
            loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml'
          },
          {
            test: /\.(png|jpg)$/,
            loader: 'url-loader?limit=8192'
          }
        ]
      },
      plugins: [
        new HappyPack({ loaders: [ 'babel-loader' ] }),
        new webpack.DefinePlugin({
          NODE_ENV: 'development',
          __DEV__: true,
          __PROD__: false,
          __TEST__: false,
          ENV: 'development',
          'process.env': {
            NODE_ENV: '"development"'
          }
        }),
        new StatsPlugin('manifest.json', {
          // We only need assetsByChunkName
          chunkModules: false,
          source: false,
          chunks: false,
          modules: false,
          assets: true
        }),
        new webpack.NoErrorsPlugin(),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 15 }),
        new webpack.optimize.MinChunkSizePlugin({ minChunkSize: 10000 }),
        new webpack.optimize.CommonsChunkPlugin({
          names: [ 'vendor', 'manifest' ] // Specify the common bundle's name.
        })
      ]
    }
    
    

    public by msdn  133156  1  6  0

    GetS2SClientContextWithWindowsIdentity: Retrieves an S2S client context with an access token signed by the application's private certificate on behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri...

    Retrieves an S2S client context with an access token signed by the application's private certificate on behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.IO;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Text;
    using System.Web.Configuration;
    using System.Web.Script.Serialization;
    using Microsoft.IdentityModel;
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.S2S.Tokens;
    using Microsoft.SharePoint.Client;
    using Microsoft.SharePoint.Client.EventReceivers;
    
    private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
    
    /// <summary>
    /// Retrieves an S2S client context with an access token signed by the application's private certificate on 
    /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the 
    /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the 
    /// targetApplicationUri to discover it.
    /// </summary>
    /// <param name="targetApplicationUri">Url of the target SharePoint site</param>
    /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
    /// <returns>A ClientContext using an access token with an audience of the target application</returns>
    public static ClientContext GetS2SClientContextWithWindowsIdentity(
        Uri targetApplicationUri,
        WindowsIdentity identity)
    {
        string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
    
        JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
    
        string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
    
        return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
    }

    public by msdn  3852  10  7  0

    ReadAndValidateContextToken: Validate that a specified context token string is intended for this application based on the parameters specified in web.config. Parameters used from web.config used for validation include ClientId, Hos...

    Validate that a specified context token string is intended for this application based on the parameters specified in web.config. Parameters used from web.config used for validation include ClientId, HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, it will be used
    using Microsoft.IdentityModel;
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.S2S.Tokens;
    using Microsoft.SharePoint.Client;
    using Microsoft.SharePoint.Client.EventReceivers;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.Text;
    using System.Web;
    using System.Web.Configuration;
    using System.Web.Script.Serialization;
    using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
    using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
    using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
    using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
    
    //
    // Environment Constants
    //
    private static string GlobalEndPointPrefix = "accounts";
    private static string AcsHostUrl = "accesscontrol.windows.net";
    private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
    private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
    private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
    //
    // Hosted app configuration
    //
    private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
    
    /// <summary>
    /// Validate that a specified context token string is intended for this application based on the parameters 
    /// specified in web.config. Parameters used from web.config used for validation include ClientId, 
    /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
    /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not 
    /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an 
    /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
    /// and a JsonWebSecurityToken based on the context token is returned.
    /// </summary>
    /// <param name="contextTokenString">The context token to validate</param>
    /// <param name="appHostName">The URL authority, consisting of  Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
    /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used 
    /// for validation instead of <paramref name="appHostName"/> .</param>
    /// <returns>A JsonWebSecurityToken based on the context token.</returns>
    public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
    {
        JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
        SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
        JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
        SharePointContextToken token = SharePointContextToken.Create(jsonToken);
    
        string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
        int firstDot = stsAuthority.IndexOf('.');
    
        GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
        AcsHostUrl = stsAuthority.Substring(firstDot + 1);
    
        tokenHandler.ValidateToken(jsonToken);
    
        string[] acceptableAudiences;
        if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
        {
            acceptableAudiences = HostedAppHostNameOverride.Split(';');
        }
        else if (appHostName == null)
        {
            acceptableAudiences = new[] { HostedAppHostName };
        }
        else
        {
            acceptableAudiences = new[] { appHostName };
        }
    
        bool validationSuccessful = false;
        string realm = Realm ?? token.Realm;
        foreach (var audience in acceptableAudiences)
        {
            string principal = GetFormattedPrincipal(ClientId, audience, realm);
            if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
            {
                validationSuccessful = true;
                break;
            }
        }
    
        if (!validationSuccessful)
        {
            throw new AudienceUriValidationFailedException(
                String.Format(CultureInfo.CurrentCulture,
                "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
        }
    
        return token;
    }

    public by msdn  3760  0  7  0

    ReadAndValidateContextToken: Validate that a specified context token string is intended for this application based on the parameters specified in web.config. Parameters used from web.config used for validation include ClientId, H...

    Validate that a specified context token string is intended for this application based on the parameters specified in web.config. Parameters used from web.config used for validation include ClientId, HostedAppHostName, ClientSecret, and Realm (if it is specified). If the is not null, it is used for validation instead of the web.config's Hos
    using Microsoft.IdentityModel;
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.S2S.Tokens;
    using Microsoft.SharePoint.Client;
    using Microsoft.SharePoint.Client.EventReceivers;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.Text;
    using System.Web;
    using System.Web.Configuration;
    using System.Web.Script.Serialization;
    using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
    using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
    using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
    using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
    
    //
    // Environment Constants
    //
    private static string GlobalEndPointPrefix = "accounts";
    private static string AcsHostUrl = "accesscontrol.windows.net";
    private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
    private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
    //
    // Hosted app configuration
    //
    private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
    
    /// <summary>
    /// Validate that a specified context token string is intended for this application based on the parameters 
    /// specified in web.config. Parameters used from web.config used for validation include ClientId, 
    /// HostedAppHostName, ClientSecret, and Realm (if it is specified). If the <paramref name="appHostName"/> is not 
    /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an 
    /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
    /// and a JsonWebSecurityToken based on the context token is returned.
    /// </summary>
    /// <param name="contextTokenString">The context token to validate</param>
    /// <param name="appHostName">The URL authority, consisting of  Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
    /// If null, HostedAppHostName web.config setting is used instead.</param>
    /// <returns>A JsonWebSecurityToken based on the context token.</returns>
    public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
    {
        JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
        SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
        JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
        SharePointContextToken token = SharePointContextToken.Create(jsonToken);
    
        string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
        int firstDot = stsAuthority.IndexOf('.');
    
        GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
        AcsHostUrl = stsAuthority.Substring(firstDot + 1);
    
        tokenHandler.ValidateToken(jsonToken);
    
        if (appHostName == null)
        {
            appHostName = HostedAppHostName;
        }
    
        string realm = Realm ?? token.Realm;
        string principal = GetFormattedPrincipal(ClientId, appHostName, realm);
        if (!StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
        {
            throw new AudienceUriValidationFailedException(
                String.Format(CultureInfo.CurrentCulture,
                "\"{0}\" is not the intended audience \"{1}\"", principal, token.Audience));
        }
    
        return token;
    }

    public by msdn  1687  1  6  0

    GetConfigurationSetting: Gets a configuration setting from application settings in the Web.config or App.config file. When running in a hosted environment, configuration settings are read from the settings specified in .cscfg fil...

    Gets a configuration setting from application settings in the Web.config or App.config file. When running in a hosted environment, configuration settings are read from the settings specified in .cscfg files (i.e., the settings are read from the fabrics configuration system).
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Globalization;
    using System.Configuration;
    using System.Collections.Specialized;
    using System.Runtime.InteropServices;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure;
    
    internal const string CSConfigStringPrefix = "CSConfigName";
    
    /// <summary>
    /// Gets a configuration setting from application settings in the Web.config or App.config file. 
    /// When running in a hosted environment, configuration settings are read from the settings specified in 
    /// .cscfg files (i.e., the settings are read from the fabrics configuration system).
    /// </summary>
    internal static string GetConfigurationSetting(string configurationString, string defaultValue, bool throwIfNull)
    {
        if (string.IsNullOrEmpty(configurationString)) {
            throw new ArgumentException("The parameter configurationString cannot be null or empty.");
        }
    
        string ret = null;
    
        // first, try to read from appsettings
        ret = TryGetAppSetting(configurationString);
    
        // settings in the csc file overload settings in Web.config
        if (RoleEnvironment.IsAvailable)
        {
            string cscRet = TryGetConfigurationSetting(configurationString);
            if (!string.IsNullOrEmpty(cscRet))
            {
                ret = cscRet;
            }
    
            // if there is a csc config name in the app settings, this config name even overloads the 
            // setting we have right now
            string refWebRet = TryGetAppSetting(CSConfigStringPrefix + configurationString);
            if (!string.IsNullOrEmpty(refWebRet))
            {
                cscRet = TryGetConfigurationSetting(refWebRet);
                if (!string.IsNullOrEmpty(cscRet))
                {
                    ret = cscRet;
                }
            }
        }
    
        // if we could not retrieve any configuration string set return value to the default value
        if (string.IsNullOrEmpty(ret) && defaultValue != null)
        {
            ret = defaultValue;
        }
    
        if (string.IsNullOrEmpty(ret) && throwIfNull)
        {
            throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "Cannot find configuration string {0}.", configurationString));
        }
        return ret;
    }

    public by msdn  5713  14  7  0

    GetS2SAccessTokenWithWindowsIdentity: Retrieves an S2S access token signed by the application's private certificate on behalf of the specified WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is speci...

    Retrieves an S2S access token signed by the application's private certificate on behalf of the specified WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in web.config, an auth challenge will be issued to the targetApplicationUri to discover it. Url of the target SharePoint site Windows
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.IO;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Text;
    using System.Web.Configuration;
    using System.Web.Script.Serialization;
    using Microsoft.IdentityModel;
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.S2S.Tokens;
    using Microsoft.SharePoint.Client;
    using Microsoft.SharePoint.Client.EventReceivers;
    
    private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
    
    /// <summary>
    /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified 
    /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in 
    /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
    /// </summary>
    /// <param name="targetApplicationUri">Url of the target SharePoint site</param>
    /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
    /// <returns>An access token with an audience of the target principal</returns>
    public static string GetS2SAccessTokenWithWindowsIdentity(
        Uri targetApplicationUri,
        WindowsIdentity identity)
    {
        string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
    
        JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
    
        return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
    }

    public by msdn  5058  14  8  0

    GetS2SClientContextWithWindowsIdentity: Retrieves an S2S client context with an access token signed by the application's private certificate on behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri ...

    Retrieves an S2S client context with an access token signed by the application's private certificate on behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the targetApplicationUri to discover it. Url
    using Microsoft.IdentityModel;
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.S2S.Tokens;
    using Microsoft.SharePoint.Client;
    using Microsoft.SharePoint.Client.EventReceivers;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.Text;
    using System.Web;
    using System.Web.Configuration;
    using System.Web.Script.Serialization;
    using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
    using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
    using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
    using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
    
    private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
    
    /// <summary>
    /// Retrieves an S2S client context with an access token signed by the application's private certificate on 
    /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the 
    /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the 
    /// targetApplicationUri to discover it.
    /// </summary>
    /// <param name="targetApplicationUri">Url of the target SharePoint site</param>
    /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
    /// <returns>A ClientContext using an access token with an audience of the target application</returns>
    public static ClientContext GetS2SClientContextWithWindowsIdentity(
        Uri targetApplicationUri,
        WindowsIdentity identity)
    {
        string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
    
        JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
    
        string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
    
        return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
    }
    • Public Snippets
    • Channels Snippets