本文整理汇总了C#中ICredentials.GetCredential方法的典型用法代码示例。如果您正苦于以下问题:C# ICredentials.GetCredential方法的具体用法?C# ICredentials.GetCredential怎么用?C# ICredentials.GetCredential使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ICredentials
的用法示例。
在下文中一共展示了ICredentials.GetCredential方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Authenticate
public Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials)
{
int index = challenge.ToLower ().IndexOf (auth_type.ToLower ());
if (index == -1)
{
index = challenge.ToLower ().IndexOf (hackish_auth_type.ToLower ());
if (index == -1)
return null;
}
if (GoogleClient.auth_token != null)
{
return new Authorization(auth_type + " auth=" + GoogleClient.auth_token);
}
string username = credentials.GetCredential (request.RequestUri, auth_type).UserName;
string password = credentials.GetCredential (request.RequestUri, auth_type).Password;
byte[] login_data = Encoding.ASCII.GetBytes (String.Format (
"Email={0}&Passwd={1}&source=Tomboy-Blogposter-0.4.4&service=blogger",
HttpUtility.UrlEncode (username), HttpUtility.UrlEncode (password)));
HttpWebRequest login_request = (HttpWebRequest) WebRequest.Create("https://www.google.com/accounts/ClientLogin");
ServicePointManager.Expect100Continue = false;
login_request.Method = "POST";
login_request.ContentType = "application/x-www-form-urlencoded";
login_request.ContentLength = login_data.Length;
Stream login_request_stream = login_request.GetRequestStream ();
login_request_stream.Write (login_data, 0, login_data.Length);
try
{
HttpWebResponse login_response = (HttpWebResponse) login_request.GetResponse ();
Stream login_response_stream = login_response.GetResponseStream ();
StreamReader login_response_stream_reader = new StreamReader (login_response_stream);
string lines = login_response_stream_reader.ReadToEnd ();
login_response.Close ();
login_response_stream.Close ();
login_response_stream_reader.Close ();
foreach (string line in lines.Split ('\n'))
{
if (line.StartsWith ("Auth="))
{
GoogleClient.auth_token = line.Substring (5);
break;
}
}
}
catch (WebException exception)
{
Logger.Log(((HttpWebResponse) exception.Response).StatusCode.ToString());
GoogleClient.auth_token = null;
exception.Response.Close ();
}
login_request_stream.Close ();
if (GoogleClient.auth_token != null)
return new Authorization(auth_type + " auth=" + GoogleClient.auth_token);
else
return null;
}
示例2: InternalAuthenticate
static Authorization InternalAuthenticate (WebRequest webRequest, ICredentials credentials)
{
HttpWebRequest request = webRequest as HttpWebRequest;
if (request == null || credentials == null)
return null;
NetworkCredential cred = credentials.GetCredential (request.AuthUri, "basic");
if (cred == null)
return null;
string userName = cred.UserName;
if (userName == null || userName == "")
return null;
string password = cred.Password;
string domain = cred.Domain;
byte [] bytes;
// If domain is set, MS sends "domain\user:password".
if (domain == null || domain == "" || domain.Trim () == "")
bytes = GetBytes (userName + ":" + password);
else
bytes = GetBytes (domain + "\\" + userName + ":" + password);
string auth = "Basic " + Convert.ToBase64String (bytes);
return new Authorization (auth);
}
示例3: CreateClientHandler
public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials, bool useCookies = false)
{
if (serviceUrl == null)
{
throw new ArgumentNullException("serviceUrl");
}
// Set up our own HttpClientHandler and configure it
HttpClientHandler clientHandler = new HttpClientHandler();
if (credentials != null)
{
// Set up credentials cache which will handle basic authentication
CredentialCache credentialCache = new CredentialCache();
// Get base address without terminating slash
string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);
// Add credentials to cache and associate with handler
NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
clientHandler.Credentials = credentialCache;
clientHandler.PreAuthenticate = true;
}
// HttpClient's default UseCookies is true (meaning always roundtripping cookie back)
// However, our api will default to false to cover multiple instance scenarios
clientHandler.UseCookies = useCookies;
// Our handler is ready
return clientHandler;
}
示例4: CreateClientHandler
public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials)
{
if (serviceUrl == null)
{
throw new ArgumentNullException("serviceUrl");
}
// Set up our own HttpClientHandler and configure it
HttpClientHandler clientHandler = new HttpClientHandler();
if (credentials != null)
{
// Set up credentials cache which will handle basic authentication
CredentialCache credentialCache = new CredentialCache();
// Get base address without terminating slash
string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);
// Add credentials to cache and associate with handler
NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
clientHandler.Credentials = credentialCache;
clientHandler.PreAuthenticate = true;
}
// Our handler is ready
return clientHandler;
}
示例5: CanPreAuthenticate
/// <summary>
/// Does the authentication module supports pre-authentication?
/// </summary>
/// <param name="client">Client executing this request</param>
/// <param name="request">Request to authenticate</param>
/// <param name="credentials">The credentials to be used for the authentication</param>
/// <returns>true when the authentication module supports pre-authentication</returns>
public bool CanPreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
{
if (credentials == null)
return false;
var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);
if (cred == null)
return false;
return true;
}
示例6: Authenticate
public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials)
{
HttpWebRequest request = webRequest as HttpWebRequest;
if (request == null)
return null;
NetworkCredential cred = credentials.GetCredential (request.RequestUri, "NTLM");
if (cred == null)
return null;
string userName = cred.UserName;
string domain = cred.Domain;
string password = cred.Password;
if (userName == null || userName == "")
return null;
domain = domain != null && domain.Length > 0 ? domain : request.Headers ["Host"];
bool completed = false;
if (message == null) {
Type1Message type1 = new Type1Message ();
type1.Domain = domain;
message = type1;
} else if (message.Type == 1) {
// Should I check the credentials?
if (challenge == null) {
message = null;
return null;
}
Type2Message type2 = new Type2Message (Convert.FromBase64String (challenge));
if (password == null)
password = "";
Type3Message type3 = new Type3Message ();
type3.Domain = domain;
type3.Username = userName;
type3.Challenge = type2.Nonce;
type3.Password = password;
message = type3;
completed = true;
} else {
// Should I check the credentials?
// type must be 3 here
if (challenge == null || challenge == String.Empty) {
Type1Message type1 = new Type1Message ();
type1.Domain = domain;
message = type1;
} else {
completed = true;
}
}
string token = "NTLM " + Convert.ToBase64String (message.GetBytes ());
return new Authorization (token, completed);
}
示例7: PreAuthenticate
/// <summary>
/// Modifies the request to ensure that the authentication requirements are met.
/// </summary>
/// <param name="client">Client executing this request</param>
/// <param name="request">Request to authenticate</param>
/// <param name="credentials">The credentials used for the authentication</param>
/// <returns>The task the authentication is performed on</returns>
public Task PreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
{
return Task.Factory.StartNew(() =>
{
if (credentials == null)
throw new InvalidOperationException("The credentials must be set using the IRestClient.Credential property.");
var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);
if (cred == null)
throw new InvalidOperationException($"No credentials provided for the {AuthenticationMethod} authentication type.");
request.AddParameter(_usernameKey, cred.UserName, _parameterType);
request.AddParameter(_passwordKey, cred.Password, _parameterType);
});
}
示例8: Lookup
private Authorization Lookup(HttpWebRequest httpWebRequest, ICredentials credentials) {
//NetworkCredential credential = credentials.GetCredential(httpWebRequest.ChallengedUri, BasicClient.Signature);
var net_cred = credentials.GetCredential(httpWebRequest.RequestUri, "Basic");
if (net_cred == null) {
return null;
}
ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy;
if (credentialPolicy != null && !credentialPolicy.ShouldSendCredential(httpWebRequest.RequestUri, httpWebRequest, net_cred, this)) {
return null;
}
var user_pass = String.Join(":", net_cred.UserName, net_cred.Password).ToUtf8();
string authToken = "Basic " + user_pass.ToBase64();
return new Authorization(authToken, true);
}
示例9: GetCredentialsForUriFromICredentials
public static NetworkCredential GetCredentialsForUriFromICredentials (Uri uri, ICredentials credentials)
{
if (credentials == null)
return null;
NetworkCredential cred = null;
foreach (var scheme in AuthenticationSchemes) {
cred = credentials.GetCredential (uri, scheme);
if (cred != null)
break;
}
return cred;
}
示例10: AuthenticateInternal
private Authorization AuthenticateInternal(WebRequest request,
ICredentials credentials)
{
String user,password,domain;
NetworkCredential netcredentials=credentials.GetCredential(
request.RequestUri, "Basic");
user=netcredentials.UserName;
password=netcredentials.Password;
domain=netcredentials.Domain;
String response=((domain==null || domain=="") ? "" :
(domain + "\\"))
+ user + ":" + password;
byte[] buf=Encoding.Default.GetBytes(response);
return new Authorization("Basic "+ToBase64String(buf));
}
示例11: BuildHttpClient
private static HttpClient BuildHttpClient(Uri uri, ICredentials credentials = null)
{
var handler = new HttpClientHandler();
var client = new HttpClient(handler);
if (credentials != null)
{
handler.PreAuthenticate = true;
handler.Credentials = credentials;
var basicCredentials = credentials.GetCredential(uri, authType: "Basic");
if (basicCredentials != null)
SetBasicAuthHeader(client, basicCredentials);
}
return client;
}
示例12: PreAuthenticate
public Authorization PreAuthenticate(WebRequest request, ICredentials credentials)
{
NetworkCredential credential = credentials.GetCredential(request.RequestUri, AuthenticationType);
string username = credential.UserName;
string password = credential.Password;
string created, nonce;
string passwordDigest = GeneratePasswordDigest(password, out created, out nonce);
request.Headers.Add("X-WSSE", string.Format(
CultureInfo.InvariantCulture,
"UsernameToken Username=\"{0}\", PasswordDigest=\"{1}\", Created=\"{2}\", Nonce=\"{3}\"",
username,
passwordDigest,
created,
nonce));
return new Authorization("WSSE profile=\"UsernameToken\"", true);
}
示例13: Lookup
private Authorization Lookup(HttpWebRequest httpWebRequest, ICredentials credentials)
{
NetworkCredential credential = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature);
if (credential == null)
{
return null;
}
ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy;
if ((credentialPolicy != null) && !credentialPolicy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, credential, this))
{
return null;
}
string userName = credential.InternalGetUserName();
string domain = credential.InternalGetDomain();
if (ValidationHelper.IsBlankString(userName))
{
return null;
}
byte[] inArray = EncodingRightGetBytes((!ValidationHelper.IsBlankString(domain) ? (domain + @"\") : "") + userName + ":" + credential.InternalGetPassword());
return new Authorization("Basic " + Convert.ToBase64String(inArray), true);
}
示例14: Authenticate
/// <summary>
/// Authenticates the user with the specified AD FS endpoint and
/// yields the SAML response data for subsequent parsing.
/// </summary>
/// <param name="identityProvider">
/// The https endpoint of the federated identity provider.
/// </param>
/// <param name="credentials">
/// Credentials for the call. If null, the user's default network credentials
/// will be used in a temporary impersonation context.
/// </param>
/// <param name="authenticationType">
/// The authentication type to be used with the endpoint. Valid values are 'NTLM',
/// 'Digest', 'Kerberos' and 'Negotiate'.
/// </param>
/// <returns>The response data from a successful authentication request.</returns>
public string Authenticate(Uri identityProvider, ICredentials credentials, string authenticationType)
{
string responseStreamData = null;
ImpersonationState impersonationState = null;
try
{
if (credentials != null)
{
var networkCredentials = credentials.GetCredential(identityProvider, authenticationType);
impersonationState = ImpersonationState.Impersonate(networkCredentials);
}
using (var response = QueryProvider(identityProvider, authenticationType))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseStreamData = reader.ReadToEnd();
}
}
}
catch (Exception e)
{
var sb = new StringBuilder(e.Message);
if (e.InnerException != null)
sb.AppendFormat("(Inner exception '{0}')", e.InnerException.Message);
throw new AdfsAuthenticationControllerException(sb.ToString(), e);
}
finally
{
if (impersonationState != null)
impersonationState.Dispose();
}
return responseStreamData;
}
示例15: Authenticate
public Authorization Authenticate (WebRequest webRequest, ICredentials credentials)
{
if (parser == null)
throw new InvalidOperationException ();
HttpWebRequest request = webRequest as HttpWebRequest;
if (request == null)
return null;
lastUse = DateTime.Now;
NetworkCredential cred = credentials.GetCredential (request.RequestUri, "digest");
if (cred == null)
return null;
string userName = cred.UserName;
if (userName == null || userName == "")
return null;
string password = cred.Password;
StringBuilder auth = new StringBuilder ();
auth.AppendFormat ("Digest username=\"{0}\", ", userName);
auth.AppendFormat ("realm=\"{0}\", ", Realm);
auth.AppendFormat ("nonce=\"{0}\", ", Nonce);
auth.AppendFormat ("uri=\"{0}\", ", request.Address.PathAndQuery);
if (Algorithm != null) { // hash algorithm (only MD5 in RFC2617)
auth.AppendFormat ("algorithm=\"{0}\", ", Algorithm);
}
auth.AppendFormat ("response=\"{0}\", ", Response (userName, password, request));
if (QOP != null) { // quality of protection (server decision)
auth.AppendFormat ("qop=\"{0}\", ", QOP);
}
lock (this) {
// _nc MUST NOT change from here...
// number of request using this nonce
if (QOP != null) {
auth.AppendFormat ("nc={0:X8}, ", _nc);
_nc++;
}
// until here, now _nc can change
}
if (CNonce != null) // opaque value from the client
auth.AppendFormat ("cnonce=\"{0}\", ", CNonce);
if (Opaque != null) // exact same opaque value as received from server
auth.AppendFormat ("opaque=\"{0}\", ", Opaque);
auth.Length -= 2; // remove ", "
return new Authorization (auth.ToString ());
}