• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Headers.AuthenticationHeaderValue类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Net.Http.Headers.AuthenticationHeaderValue的典型用法代码示例。如果您正苦于以下问题:C# AuthenticationHeaderValue类的具体用法?C# AuthenticationHeaderValue怎么用?C# AuthenticationHeaderValue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



AuthenticationHeaderValue类属于System.Net.Http.Headers命名空间,在下文中一共展示了AuthenticationHeaderValue类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Call

        public static async Task<string> Call(string url, string user,string password, string parameters="")
        {
            string returnValue = "";

            try
            {
                using (var client = new HttpClient())
                {
                    //generate url

                    client.BaseAddress = new Uri(url);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //[email protected]:WSTest
                    var byteArray = Encoding.ASCII.GetBytes(user+":"+password);

                    // "basic "+ Convert.ToBase64String(byteArray)
                    AuthenticationHeaderValue ahv = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    client.DefaultRequestHeaders.Authorization = ahv;

                    string requesturl = url + parameters;
                    HttpResponseMessage response = await client.GetAsync(requesturl);
                    response.EnsureSuccessStatusCode();
                    returnValue = ((HttpResponseMessage)response).Content.ReadAsStringAsync().Result;
                }
                return returnValue;
            }
            catch (Exception e)
            {
                throw (e);
            }
        }
开发者ID:BEXIS2,项目名称:Core,代码行数:33,代码来源:BasicWebService.cs


示例2: GetTokenExplained

        /// <summary>
        /// Illustrates how to get token without OAuth2Client helper
        /// </summary>
        /// <returns></returns>
        public static string GetTokenExplained()
        {
            //data to post to the token endpoint
            var fields = new Dictionary<string, string>
            {
                { "scope", "bimtoolkitapi" },
                { "grant_type", "client_credentials" }
            };

            //setup basic authentication
            string creds = String.Format("{0}:{1}", _clientId, _clientSecret);
            byte[] bytes = Encoding.ASCII.GetBytes(creds);
            var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));

            //configure client
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = header;
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["Authority"] + "/connect/token");

            //get response and parse as json
            var response = client.PostAsync(string.Empty, new FormUrlEncodedContent(fields)).Result;
            string raw = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(raw);

            //try to get the access token from the json response
            JToken token;
            if (json.TryGetValue("access_token", out token))
            {
                return token.ToString();
            }

            return "";
        }
开发者ID:theNBS,项目名称:BimtoolkitApiClient,代码行数:37,代码来源:ApiAccess.cs


示例3: Main

    static public void Main ()
    {
        Console.WriteLine ("Trying to send");
        var username = "<API Username>";
        var password = "<API Password>";
        var postData = new List<KeyValuePair<string, string>>()
            {
            new KeyValuePair<string, string>("from", "+4676865201"),
            new KeyValuePair<string, string>("to", "+46723175800"),
            new KeyValuePair<string, string>("voice_start", '{"connect":"+461890510"}')
            };
                                
        string creds = string.Format("{0}:{1}", username, password);
        byte[] bytes = Encoding.ASCII.GetBytes(creds);
        var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
        var content = new FormUrlEncodedContent(postData);
        
        HttpClient Client = new HttpClient();
        Client.DefaultRequestHeaders.Authorization = header;
            
        var responseMessage =  Client.Post("https://api.46elks.com/a1/Calls", content);
        var response = esponseMessage.Content.ReadAsString();
        Console.WriteLine (response);
    }
}
开发者ID:46elks,项目名称:46elks-getting-started,代码行数:25,代码来源:csharp.cs


示例4: ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly

        public void ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly()
        {
            using (HttpResponseMessage response = new HttpResponseMessage())
            {
                string input = string.Empty;

                AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Digest",
                    "qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"");

                Assert.Equal(
                    "Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"",
                    auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += auth.ToString();

                auth = new AuthenticationHeaderValue("Negotiate");
                Assert.Equal("Negotiate", auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += ", " + auth.ToString();

                auth = new AuthenticationHeaderValue("Custom", ""); // empty string should be treated like 'null'.
                Assert.Equal("Custom", auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += ", " + auth.ToString();

                string result = response.Headers.ProxyAuthenticate.ToString();
                Assert.Equal(input, result);
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:29,代码来源:AuthenticationHeaderValueTest.cs


示例5: ValidateClientAsync

        public async Task<Client> ValidateClientAsync(NameValueCollection parameters, AuthenticationHeaderValue header)
        {
            Logger.Info("Start client validation");

            // validate client credentials on the wire
            var credential = ValidateHttpRequest(header, parameters);

            if (credential.IsMalformed || !credential.IsPresent)
            {
                LogError("No or malformed client credential found.");
                return null;
            }

            _log.ClientId = credential.ClientId;
            _log.ClientCredentialType = credential.Type;

            // validate client against configuration store
            var client = await ValidateClientCredentialsAsync(credential);
            if (client == null)
            {
                return null;
            }

            _log.ClientName = client.ClientName;

            LogSuccess();
            return client;
        }
开发者ID:ridopark,项目名称:IdentityServer3,代码行数:28,代码来源:ClientValidator.cs


示例6: GetContacts

        public IEnumerable<Models.Contact> GetContacts()
        {
            try
            {
                var header = Request.Headers;
                IEnumerable<string> email;
                IEnumerable<string> pass;
                header.TryGetValues("e", out email);
                header.TryGetValues("p", out pass);
                var credentials = header.Authorization;

                var e = email.FirstOrDefault();
                var p = pass.FirstOrDefault();
                var base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", e, p)));
                var temp = new AuthenticationHeaderValue("Basic", base64);
                if(temp.Parameter != credentials.Parameter)
                {
                    return null;
                }
                e = RSAUtil.RsaDecryptWithPrivate(e);
                p = RSAUtil.RsaDecryptWithPrivate(p);
                if (e != null && p != null)
                {
                    return Office365Data.Instance().GetContacts(e, p);
                }
            }
            catch
            {
                return null;
            }
            return null;
        }
开发者ID:thongvo,项目名称:myfiles,代码行数:32,代码来源:Office365Controller.cs


示例7: AzureMLAuthenticatedHttpClient

 public AzureMLAuthenticatedHttpClient(IAzureMLFrequentlyBoughtTogetherConfig config)
 {
     //Basic Auth requires a user name, even though it's not used. We use the key as user name.
     var accountKey = Encoding.ASCII.GetBytes($"{config.AccountKey}:{config.AccountKey}");
     var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(accountKey));
     DefaultRequestHeaders.Authorization = header;
 }
开发者ID:joergjo,项目名称:PartsUnlimited,代码行数:7,代码来源:AzureMLAuthenticatedHttpClient.cs


示例8: AzureMLAuthenticatedHttpClient

 public AzureMLAuthenticatedHttpClient(IAzureMLFrequentlyBoughtTogetherConfig config)
 {
     //HACK: Should prefix key with 'AccountKey:'
     var accountKey = Encoding.ASCII.GetBytes(config.AccountKey);
     var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(accountKey));
     DefaultRequestHeaders.Authorization = header;
 }
开发者ID:dpiessens,项目名称:PartsUnlimited,代码行数:7,代码来源:AzureMLAuthenticatedHttpClient.cs


示例9: ExtractCredentials

        private Credentials ExtractCredentials(AuthenticationHeaderValue authHeader)
        {
            try
            {
                if (authHeader == null)
                {
                    return null;
                }

                var encodedUserPass = authHeader.Parameter.Trim();

                Credentials credentials;

                if (!Credentials.TryParse(Crypto.DecryptStringAES(encodedUserPass, "authentication"), out credentials))
                {
                    return null;
                }

                return credentials;
            }
            catch
            {
                return null;
            }
        }
开发者ID:TryingToImprove,项目名称:BackboneCRM-TryingToImproveMe,代码行数:25,代码来源:BasicAuthenticationHandler.cs


示例10: GetCredentials

 private string[] GetCredentials(AuthenticationHeaderValue authHeader)
 {
     var raw = authHeader.Parameter;
     var encoding = Encoding.ASCII;
     var credentials = encoding.GetString(Convert.FromBase64String(raw));
     return credentials.Split(':');
 }
开发者ID:GrzesiekK126,项目名称:Wrocasion,代码行数:7,代码来源:BasicAuthorizeAttribute.cs


示例11: ExtractCredential

        private string ExtractCredential(AuthenticationHeaderValue authorizationHeaderValue)
        {
            if (authorizationHeaderValue.IsNull())
                return string.Empty;

            return authorizationHeaderValue.GetBearerToken();
        }
开发者ID:c4rm4x,项目名称:C4rm4x.WebApi,代码行数:7,代码来源:JwtBasedSecurityMessageHandler.cs


示例12: Get

        public static AuthenticationHeaderValue Get( String collectionIdentifier )
        {
            // Create authentication headers dictionary if not present
            if ( authenticationHeaders == null )
            {
                authenticationHeaders = new Dictionary<String, AuthenticationHeaderValue>();
            }

            // Try to get authentication header from dictionary
            if ( authenticationHeaders.ContainsKey( collectionIdentifier ) )
            {
                return authenticationHeaders[collectionIdentifier];
            }

            // Try to get authentication header from app storage
            String scheme = StorageUtils.GetValue<String>( collectionIdentifier + "_scheme" );
            String parameter = StorageUtils.GetValue<String>( collectionIdentifier + "_parameter" );

            if ( scheme == null || parameter == null )
            {
                return null;
            }

            AuthenticationHeaderValue authenticationHeader = new AuthenticationHeaderValue( scheme, parameter );

            // Add authentication header to dictionary
            authenticationHeaders[collectionIdentifier] = authenticationHeader;

            return authenticationHeader;
        }
开发者ID:anfema,项目名称:ion-client-windows,代码行数:30,代码来源:CollectionAuthStore.cs


示例13: TrottlingAuthenticate

        public void TrottlingAuthenticate()
        {
            Database.SetInitializer(new ManahostManagerInitializer());
            using (ManahostManagerDAL prectx = new ManahostManagerDAL())
            {
                prectx.Database.Delete();
            }
            using (var server = TestServer.Create<WebApiApplicationThrottle>())
            {
                HttpResponseMessage response = null;
                response = server.CreateRequest("/token").And((x) => x.Content = new StringContent(string.Format("grant_type=password&username={0}&password={1}&client_id=UNITTEST&client_secret=BLAHBLAHCAR", ControllerUtils.username, ControllerUtils.password), Encoding.UTF8, "application/x-www-form-urlencoded")).PostAsync().Result;
                Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "STATUS AUTHENTIFICATIOn");

                TokenAuth token = response.Content.ReadAsAsync<TokenAuth>().Result;
                AuthenticationHeaderValue headerValueAuthentication = new AuthenticationHeaderValue("Bearer", token.access_token);

                for (int i = 0; i < 4000; i++)
                {
                    response = server.CreateRequest("/api/Account").AddHeader("Authorization", headerValueAuthentication.ToString()).GetAsync().Result;
                    Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, string.Format("STATUS Account GET I : {0}", i));
                }
                response = server.CreateRequest("/api/Account").AddHeader("Authorization", headerValueAuthentication.ToString()).GetAsync().Result;
                Assert.AreEqual((int)response.StatusCode, 429, "STATUS 429");
            }
        }
开发者ID:charla-n,项目名称:ManahostManager,代码行数:25,代码来源:ThrottlingTest.cs


示例14: TryRequestAsync

        static async Task TryRequestAsync(HttpClient client, AuthenticationHeaderValue authorization)
        {
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, ServerAddress))
            {
                request.Headers.Authorization = authorization;
                using (HttpResponseMessage response = await client.SendAsync(request))
                {
                    Console.WriteLine("{0} {1}", (int)response.StatusCode, response.ReasonPhrase);

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        return;
                    }

                    Console.WriteLine();

                    HomeModel model = await response.Content.ReadAsAsync<HomeModel>();
                    Console.WriteLine("UserName: {0}", model.UserName);
                    Console.WriteLine("Claims:");

                    foreach (ClaimModel claim in model.Claims)
                    {
                        Console.WriteLine("{0} => {1}", claim.Type, claim.Value);
                    }
                }
            }
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:27,代码来源:Program.cs


示例15: OnAuthorization

 public override void OnAuthorization(HttpActionContext actionContext)
 {
     AuthenticationHeaderValue headerValue = actionContext.Request.Headers.Authorization;
     if (null != headerValue && headerValue.Scheme == "Basic")
     {
         string credential = Encoding.Default.GetString(Convert.FromBase64String(headerValue.Parameter));
         string[] split = credential.Split(':');
         if (split.Length == 2)
         {
             string userName = split[0];
             string password;
             if (userAccounters.TryGetValue(userName, out password))
             {
                 if (password == split[1])
                 {
                     GenericIdentity identity = new GenericIdentity(userName);
                     actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(identity, new string[0]);
                     return;
                 }
             }
         }
     }
     HttpResponseMessage response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
     string parameter = string.Format("realm=\"{0}\"", actionContext.Request.RequestUri.DnsSafeHost);
     AuthenticationHeaderValue challenge = new AuthenticationHeaderValue("Basic", parameter);
     response.Headers.WwwAuthenticate.Add(challenge);
     actionContext.Response = response;
 }
开发者ID:chenboyi081,项目名称:asp-net-web-api-2-samples,代码行数:28,代码来源:AuthenticateAttribute.cs


示例16: Create

 public static AuthenticationHeaderValue Create(Guid userProviderKey)
 {
     string authInfo = userProviderKey + ":" + string.Empty;
     authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
     var authenticationHeaderValue = new AuthenticationHeaderValue("Basic", authInfo);
     return authenticationHeaderValue;
 }
开发者ID:swharr,项目名称:API-Examples,代码行数:7,代码来源:AuthenticationHeaderValueFactory.cs


示例17: GitHubSoapBrokerImpl

 private GitHubSoapBrokerImpl()
 {
     _httpClient = new HttpClient();
     var bytes = Encoding.ASCII.GetBytes("spf-uc06:spf1234");
     var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
     _httpClient.DefaultRequestHeaders.Authorization = authHeader;
 }
开发者ID:sandrapatfer,项目名称:PROMPT11-06-Services.sandrapatfer,代码行数:7,代码来源:GitHubSoapBrokerImpl.cs


示例18: ParseAuthHeader

        public static IDictionary<string, string> ParseAuthHeader(AuthenticationHeaderValue header)
        {
            if(header == null) {
                return null;
            }

            var retVal = new Dictionary<string, string>();
            var raw = header.Parameter;
            var regex = new Regex("(\\w+)=((\\w+)|\"([^\"]+))");
            var matches = regex.Matches(raw);
            if(matches.Count > 0) { 
                var groups = matches[0].Groups;
                var key = groups[1].Value;
                var k = groups[3];
                if(!k.Success) {
                    k = groups[4];
                }

                retVal[key] = k.Value;
                retVal["Scheme"] = header.Scheme;
            }

            retVal["WWW-Authenticate"] = header.ToString();
            return retVal;
        }
开发者ID:jonfunkhouser,项目名称:couchbase-lite-net,代码行数:25,代码来源:AuthUtils.cs


示例19: ExtractCredential

 private static NetworkCredential ExtractCredential(AuthenticationHeaderValue authorizationHeader)
 {
     string parameter = authorizationHeader.Parameter.Trim();
     string userNameAndPassword = Encoding.ASCII.GetString(Convert.FromBase64String(parameter));
     string[] credentials = userNameAndPassword.Split(':');
     return new NetworkCredential(credentials[0], credentials[1], "DOMAIN");
 }
开发者ID:ChrisMissal,项目名称:WcfWebApiContrib,代码行数:7,代码来源:BasicAuthenticator.cs


示例20: Ctor_SetSchemeOnly_MatchExpectation

 public void Ctor_SetSchemeOnly_MatchExpectation()
 {
     // Just verify that this ctor forwards the call to the overload taking 2 parameters.
     AuthenticationHeaderValue auth = new AuthenticationHeaderValue("NTLM");
     Assert.Equal("NTLM", auth.Scheme);
     Assert.Null(auth.Parameter);
 }
开发者ID:dotnet,项目名称:corefx,代码行数:7,代码来源:AuthenticationHeaderValueTest.cs



注:本文中的System.Net.Http.Headers.AuthenticationHeaderValue类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Headers.CacheControlHeaderValue类代码示例发布时间:2022-05-26
下一篇:
C# Formatting.MediaTypeFormatter类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap