本文整理汇总了C#中System.Net.Http.Headers.AuthenticationHeaderValue类的典型用法代码示例。如果您正苦于以下问题:C# AuthenticationHeaderValue类的具体用法?C# AuthenticationHeaderValue怎么用?C# AuthenticationHeaderValue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AuthenticationHeaderValue类属于System.Net.Http.Headers命名空间,在下文中一共展示了AuthenticationHeaderValue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
}
示例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 "";
}
示例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);
}
}
示例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);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
}
示例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(':');
}
示例11: ExtractCredential
private string ExtractCredential(AuthenticationHeaderValue authorizationHeaderValue)
{
if (authorizationHeaderValue.IsNull())
return string.Empty;
return authorizationHeaderValue.GetBearerToken();
}
示例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;
}
示例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");
}
}
示例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);
}
}
}
}
示例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;
}