本文整理汇总了C#中Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential类的典型用法代码示例。如果您正苦于以下问题:C# ClientCredential类的具体用法?C# ClientCredential怎么用?C# ClientCredential使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ClientCredential类属于Microsoft.IdentityModel.Clients.ActiveDirectory命名空间,在下文中一共展示了ClientCredential类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RetrieveTokenAsync
/// <summary>
/// Retrieves a new auth token from AAD.
/// </summary>
/// <param name="authUrl">The root of the authority url.</param>
/// <param name="tenantDomain">The domain name of the Azure tenant as the second part of the authority url.</param>
/// <param name="targetServiceUrl">The url of the service that should be accessed. Be sure to check trailing slashes!</param>
/// <param name="clientId">The unique client id as it is configured in Azure Portal.</param>
/// <param name="appKey">This value is optional and contains the App-Key-Secret if it is configured in azure portal.</param>
/// <param name="redirectUrl">The redirect url as it is configured in Azure Portal.</param>
/// <returns>The authentication token.</returns>
public static async Task<string> RetrieveTokenAsync(string authUrl, string tenantDomain, string targetServiceUrl, string clientId, Uri redirectUrl, string appKey = null)
{
var authenticationContext = new AuthenticationContext($"{authUrl}/{tenantDomain}");
try
{
AuthenticationResult result = null;
if (appKey.IsNullOrEmpty())
{
// use user auth
var parameters = new PlatformParameters(PromptBehavior.Auto);
result = await authenticationContext.AcquireTokenAsync(targetServiceUrl, clientId, redirectUrl, parameters).ConfigureAwait(false);
}
else
{
// use key auth
var clientCredential = new ClientCredential(clientId, appKey);
result = await authenticationContext.AcquireTokenAsync(targetServiceUrl, clientCredential).ConfigureAwait(false);
}
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
// store token for reuse
return result.AccessToken;
}
catch (Exception ex)
{
throw new InvalidOperationException("Could not retrieve token.", ex);
}
}
示例2: ConfigureAuth
public void ConfigureAuth(IAppBuilder app) {
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
ClientId = SettingsHelper.ClientId,
Authority = SettingsHelper.AzureADAuthority,
Notifications = new OpenIdConnectAuthenticationNotifications() {
AuthorizationCodeReceived = (context) => {
string code = context.Code;
ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
EFADALTokenCache cache = new EFADALTokenCache(userObjectId);
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, cache);
Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);
return Task.FromResult(0);
},
AuthenticationFailed = (context) => {
context.HandleResponse();
return Task.FromResult(0);
}
},
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters {
ValidateIssuer = false
}
});
}
示例3: AcquireToken
public static string AcquireToken(string userObjectId)
{
ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
AuthenticationResult result = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
return result.AccessToken;
}
示例4: MainAsync
static async Task MainAsync(string[] args)
{
var keyClient = new KeyVaultClient((authority, resource, scope) =>
{
var adCredential = new ClientCredential(applicationId, applicationSecret);
var authenticationContext = new AuthenticationContext(authority, null);
return authenticationContext.AcquireToken(resource, adCredential).AccessToken;
});
// Get the key details
var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784";
var key = await keyClient.GetKeyAsync(keyIdentifier);
var publicKey = Convert.ToBase64String(key.Key.N);
using (var rsa = new RSACryptoServiceProvider())
{
var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E };
rsa.ImportParameters(p);
var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
// Encrypt and Decrypt
var encryptedText = rsa.Encrypt(byteData, true);
var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText);
var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);
// Sign and Verify
var hasher = new SHA256CryptoServiceProvider();
var digest = hasher.ComputeHash(byteData);
var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result);
}
}
示例5: ConfigureAuth
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = _appConfig.ClientID,
Authority = Constants.Authentication.CommonAuthority,
PostLogoutRedirectUri = _appConfig.PostLogoutRedirectURI,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
// instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
// we inject our own multitenant validation logic
ValidateIssuer = false,
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(_appConfig.ClientID,_appConfig.ClientSecret);
string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenantID), new ADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code,
new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
credential,
Constants.Authentication.GraphServiceUrl);
return Task.FromResult(0);
},
RedirectToIdentityProvider = (context) =>
{
// This ensures that the address used for sign in and sign out is picked up dynamically from the request
// this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
// Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
return Task.FromResult(0);
},
AuthenticationFailed = (context) =>
{
System.Diagnostics.Trace.TraceError(context.Exception.ToString());
string redirectPath = string.Format("/Error/?errorMessage={0}", context.Exception.Message);
context.OwinContext.Response.Redirect(redirectPath);
// context.OwinContext.Response.Redirect("/Error/Index");
context.HandleResponse(); // Suppress the exception
return Task.FromResult(0);
}
}
});
}
示例6: GetCredential
//Get the Service Principle credential for getting the access token
private static ClientCredential GetCredential()
{
string filePath = "c:\\Users\\vmuser\\azure\\profiles\\default.profile";
ClientCredential creds;
//obtain credential from default location - dev machine
if (File.Exists(filePath))
{
string[] secrets = GetCredentialFromProfile(filePath);
creds = new ClientCredential(secrets[0], secrets[1]);
}
else if (true) //todo: change to check the Azure environment this app is running in
{
//obtain credential from custom data settings - App Services, Cloud Services
var clientID = CloudConfigurationManager.GetSetting("ClientID");
var clientSecret = CloudConfigurationManager.GetSetting("ClientSecret");
creds = new ClientCredential(clientID, clientSecret);
}
else if (false)
{
//TODO: obtain credential from instance metadata -VM, VMSS
}
else
creds = null;
return creds;
}
示例7: Index
// GET: Discovery
public async Task<ActionResult> Index()
{
// get instance of the authentication context using the token cache we created previously
var signedInUser = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signedInUser));
// create credentials for the application
var appCred = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
// get user identifier
var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
var userId = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
// create instance of DiscoveryClient
var discoveryClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
async () =>
{
var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, appCred, userId);
return authResult.AccessToken;
});
// query discovery service for endpoints
var capabilitiesResults = await discoveryClient.DiscoverCapabilitiesAsync();
return View(capabilitiesResults);
}
示例8: GetAccessToken
private async Task<AuthenticationResult> GetAccessToken()
{
AuthenticationContext context = new AuthenticationContext(SettingsHelper.AzureADAuthority);
var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
AuthenticationResult result = (AuthenticationResult)this.Session[SettingsHelper.UserTokenCacheKey];
return await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientCredential, SettingsHelper.UnifiedApiResource);
}
示例9: AdalCredential
/// <summary>
/// Creates a new instance of the <see cref="Tailspin.Surveys.Security.AdalCredential"/>
/// </summary>
/// <param name="clientCredential">A <see cref="Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential"/> instance to store in this credential.</param>
public AdalCredential(ClientCredential clientCredential)
{
Guard.ArgumentNotNull(clientCredential, nameof(clientCredential));
ClientCredential = clientCredential;
CredentialType = AdalCredentialType.ClientCredential;
}
示例10: GetApplicationAccountToken
public string GetApplicationAccountToken(string resourceUrl)
{
AuthenticationResult result = null;
var authority = string.Format("https://login.microsoftonline.com/{0}/oauth2/token/",
ConfigurationManager.AppSettings["TenantId"]);
var context = new AuthenticationContext(authority);
var credential = new ClientCredential(ConfigurationManager.AppSettings["ClientId"],
ConfigurationManager.AppSettings["ClientSecret"]);
var thread = new Thread(() => { result = context.AcquireToken(resourceUrl, credential); });
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
var token = result.AccessToken;
return token;
}
示例11: AddCredential
/// <summary>
/// Add the given credential to the in-memory store.
/// </summary>
/// <param name="credential">The credential to add.</param>
public void AddCredential(ClientCredential credential)
{
if (!_credentials.ContainsKey(credential.ClientId))
{
_credentials[credential.ClientId] = credential;
}
}
示例12: AcquireToken
public IAuthenticationResult AcquireToken(string resource, ClientCredential clientCredential)
{
this._authenticationContext.CorrelationId = this.CorrelationId;
var _result = this._authenticationContext.AcquireToken(resource, clientCredential);
return _result == null ? null : new AuthenticationResultWrapper(_result);
}
示例13: GetAccessToken
/// <summary>
/// Get the access token
/// </summary>
/// <param name="clientId">Client ID of the Web API app</param>
/// <param name="appKey">Client secret for the Web API app</param>
/// <param name="aadInstance">The login URL for AAD</param>
/// <param name="tenant">Your tenant (eg kirke.onmicrosoft.com)</param>
/// <param name="resource">The resource being accessed
///(eg., https://rbinrais.sharepoint.com)
/// </param>
/// <returns>string containing the access token</returns>
public static async Task<string> GetAccessToken(
string clientId,
string appKey,
string aadInstance,
string tenant,
string resource)
{
string accessToken = null;
AuthenticationResult result = null;
ClientCredential clientCred = new ClientCredential(clientId, appKey);
string authHeader = HttpContext.Current.Request.Headers["Authorization"];
string userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim();
UserAssertion userAssertion = new UserAssertion(userAccessToken);
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
AuthenticationContext authContext = new AuthenticationContext(authority);
result = await authContext.AcquireTokenAsync(resource, clientCred, userAssertion);
accessToken = result.AccessToken;
return accessToken;
}
示例14: Index
public ActionResult Index(string code) {
CustomAuthenticationManager.CacheAuthenticationCode(code);
ClientCredential credential =
new ClientCredential(DemoConstants.ClientId, DemoConstants.ClientSecret);
string resource = DemoConstants.TargetResource;
Uri uriReplyUrl = new Uri(DemoConstants.ClientReplyUrl);
AuthenticationContext authenticationContext = new AuthenticationContext(DemoConstants.urlAuthorizationEndpoint);
AuthenticationResult authenticationResult =
authenticationContext.AcquireTokenByAuthorizationCode(
code,
uriReplyUrl,
credential,
resource);
CustomAuthenticationManager.CacheAuthenticationResult(authenticationResult);
ViewBag.AuthenticationCode = code;
return View(authenticationResult);
}
示例15: GetAccessToken
public static string GetAccessToken(string resource)
{
// get ClaimsPrincipal for current user
ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current;
string signedInUserID = currentUserClaims.FindFirst(ClaimTypes.NameIdentifier).Value;
string tenantID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
ApplicationDbContext db = new ApplicationDbContext();
ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID);
string urlAuthorityRoot = ConfigurationManager.AppSettings["ida:AADInstance"];
string urlAuthorityTenant = urlAuthorityRoot + tenantID;
AuthenticationContext authenticationContext =
new AuthenticationContext(urlAuthorityTenant, userTokenCache);
Uri uriReplyUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
UserIdentifier userIdentifier = new UserIdentifier(userObjectID, UserIdentifierType.UniqueId);
AuthenticationResult authenticationResult =
authenticationContext.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier).Result;
return authenticationResult.AccessToken;
}