本文整理汇总了C#中Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenAsync方法的典型用法代码示例。如果您正苦于以下问题:C# AuthenticationContext.AcquireTokenAsync方法的具体用法?C# AuthenticationContext.AcquireTokenAsync怎么用?C# AuthenticationContext.AcquireTokenAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext
的用法示例。
在下文中一共展示了AuthenticationContext.AcquireTokenAsync方法的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: Authenticate
private async void Authenticate()
{
var authConfig = App.AuthenticationConfiguration;
var authContext = new AuthenticationContext("https://login.windows.net/" + authConfig.DirectoryDomain);
//Use this during development if you don't want your credentials cached
//authContext.TokenCacheStore.Clear();
var result = await authContext.AcquireTokenAsync(authConfig.AppRedirectUri, authConfig.AppClientId, new Uri(authConfig.ApiAppSignOnUrl));
if (result.Status == AuthenticationStatus.Success)
{
App.BearerToken = result.AccessToken;
App.CurrentUser = result.UserInfo;
//Here is how to make a secure HTTP call with SecureHttpClient
//var secureHttpClient = new SecureHttpClient(result.AccessToken);
//var resp = await secureHttpClient.GetAsync("http://localhost:3184/api/echo?whoami=true");
var rootFrame = (Frame)Window.Current.Content;
rootFrame.Navigate(typeof(Views.Menu.MenuPage));
}
else
{
Authenticate();
}
}
示例3: MainAsync
static async Task MainAsync(string[] args)
{
var keyClient = new KeyVaultClient(async (authority, resource, scope) =>
{
var adCredential = new ClientCredential(applicationId, applicationSecret);
var authenticationContext = new AuthenticationContext(authority, null);
return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
});
// Get the key details
var keyIdentifier = "https://rahulkeyvault.vault.azure.net:443/keys/NewKey";
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.DecryptAsync(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);
}
}
示例4: GetAccessToken
/// <summary>
/// Gets the access token
/// </summary>
/// <param name="authority"> Authority </param>
/// <param name="resource"> Resource </param>
/// <param name="scope"> scope </param>
/// <returns> token </returns>
public async Task<string> GetAccessToken(string authority, string resource, string scope)
{
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, _credential);
return result.AccessToken;
}
示例5: 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;
}
示例6: GetAccessToken
private static async Task<string> GetAccessToken(X509Certificate2 certificate)
{
var authenticationContext = new AuthenticationContext(Authority, false);
var cac = new ClientAssertionCertificate(ClientId, certificate);
var authenticationResult = await authenticationContext.AcquireTokenAsync(GraphUrl, cac);
return authenticationResult.AccessToken;
}
示例7: Main
static void Main(string[] args)
{
/// Azure AD WebApi's APP ID URL
string resource = "";
/// Azure AD WebApi's Client ID
string clientId = "";
/// Azure AD User's credentials
string userName = "";
string userPassword = "";
/// Web API's URL
string apiUrl = "http://localhost:3672/api/Test";
var user = new UserCredential(userName, userPassword);
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/common");
/// Get an Access Token to Access the Web API on behalf of the user
AuthenticationResult authResult = authContext.AcquireTokenAsync(resource, clientId, user).Result;
/// Call WebAPI passing Access token on header
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
/// Get the result
HttpResponseMessage response = client.GetAsync(apiUrl).Result;
string text = response.Content.ReadAsStringAsync().Result;
}
示例8: GetAccessToken
/// <summary>
/// Authentication callback that gets a token using the X509 certificate
/// </summary>
/// <param name="authority">Address of the authority</param>
/// <param name="resource">Identifier of the target resource that is the recipient of the requested token</param>
/// <param name="scope">Scope</param>
/// <param name="assertionCert">The assertion certificate</param>
/// <returns> The access token </returns>
public static async Task<string> GetAccessToken(string authority, string resource, string scope, ClientAssertionCertificate assertionCert)
{
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, assertionCert);
return result.AccessToken;
}
示例9: GetAzureAdToken
public static AuthenticationResult GetAzureAdToken(AuthenticationContext authContext, String resourceHostUri,
string clientId, string redirectUri, UserCredential uc)
{
AuthenticationResult authenticationResult = null;
Console.WriteLine("Performing GetAzureAdToken");
try
{
Console.WriteLine("Passed resource host URI is " + resourceHostUri);
if (resourceHostUri.StartsWith("http"))
{
resourceHostUri = Helpers.ReduceUriToProtoAndHost(resourceHostUri);
Console.WriteLine("Normalized the resourceHostUri to just the protocol and hostname " + resourceHostUri);
}
// check if there's a user credential - i.e. a username and password
if(uc != null)
{
authenticationResult = authContext.AcquireTokenAsync(resourceHostUri, clientId, uc).Result;
}
else {
PlatformParameters platformParams = new PlatformParameters(PromptBehavior.Auto);
authenticationResult = authContext.AcquireTokenAsync(resourceHostUri, clientId, new Uri(redirectUri), platformParams).Result;
}
//Console.WriteLine("Bearer token from Azure AD is " + authenticationResult.AccessToken);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("An unexpected error occurred.");
string message = ex.Message;
if (ex.InnerException != null)
{
message += Environment.NewLine + "Inner Exception : " + ex.InnerException.Message;
}
Console.WriteLine("Message: {0}", message);
Console.ForegroundColor = ConsoleColor.White;
}
return authenticationResult;
}
示例10: GetTokenForApplication
/// <summary>
/// Get Token for Application.
/// </summary>
/// <returns>Token for application.</returns>
public static string GetTokenForApplication(string tenantName, string clientId, string clientSecret)
{
AuthenticationContext authenticationContext = new AuthenticationContext(String.Format(Constants.AuthString, tenantName), false);
// Config for OAuth client credentials
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
Task<AuthenticationResult> authenticationResult = authenticationContext.AcquireTokenAsync(Constants.ResourceUrl, clientCred);
string token = authenticationResult.Result.AccessToken;
return token;
}
示例11: GetAccessToken
/// <summary>
/// Gets an access token for the client ID and client key specified in the configuration.
/// </summary>
/// <param name="authority">The authority granting access.</param>
/// <param name="resource">The resource to access.</param>
/// <param name="scope">The scope of the authentication request.</param>
/// <returns>An access token.</returns>
public static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
ClientCredential credential = new ClientCredential(CloudConfigurationManager.GetSetting("KVClientId"), CloudConfigurationManager.GetSetting("KVClientKey"));
AuthenticationContext ctx = new AuthenticationContext(new Uri(authority).AbsoluteUri, false);
AuthenticationResult result = await ctx.AcquireTokenAsync(resource, credential);
return result.AccessToken;
}
示例12: GetToken
public async Task<AuthenticationResult> GetToken(string resource)
{
ClientAssertionCertificate cac = GetClientAssertionCertificate();
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority);
AuthenticationResult authResult = await authContext.AcquireTokenAsync(resource, cac);
return authResult;
}
示例13: AuthenticateAsync
/// <summary>
/// Authenticate using the credentials stored for the given client id
/// </summary>
/// <param name="clientId">The Application ID for this service principal</param>
/// <param name="audience">The intended audicne for authentication</param>
/// <param name="context">The AD AuthenticationContext to use</param>
/// <returns></returns>
public async Task<AuthenticationResult> AuthenticateAsync(string clientId, string audience, AuthenticationContext context)
{
if (_credentials.ContainsKey(clientId))
{
var creds = _credentials[clientId];
return await context.AcquireTokenAsync(audience, creds);
}
throw new AuthenticationException("Matching credentials for client id '{0}' could not be found.");
}
示例14: GetAccessToken
public static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
var clientId = _configuration["KeyVault:AuthClientId"];
var clientSecret = _configuration["KeyVault:AuthClientSecret"];
var clientCredential = new ClientCredential(clientId, clientSecret);
var context = new AuthenticationContext(authority, null);
var result = await context.AcquireTokenAsync(resource, clientCredential);
return result.AccessToken;
}
示例15: KeyVaultClientAuthenticationCallback
internal async Task<string> KeyVaultClientAuthenticationCallback(string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(_clientId, _clientSecret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return result.AccessToken;
}
开发者ID:MattCotterellNZ,项目名称:IdentityServer.Contrib.AzureKeyVaultTokenSigningService,代码行数:11,代码来源:AzureKeyVaultAuthentication.cs