本文整理汇总了C#中Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenSilent方法的典型用法代码示例。如果您正苦于以下问题:C# AuthenticationContext.AcquireTokenSilent方法的具体用法?C# AuthenticationContext.AcquireTokenSilent怎么用?C# AuthenticationContext.AcquireTokenSilent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext
的用法示例。
在下文中一共展示了AuthenticationContext.AcquireTokenSilent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetToken
public static AuthenticationResult GetToken(string serviceName)
{
var ctx = new AuthenticationContext(IdentitySettings.IssuerAddress, new NativeTokenCache());
var resource = Resource(serviceName);
var appClientId = RuntimeFactory.Current.Context.GetServiceConfiguration().GetConfigParameter("OauthClientId");
var appClientSecret = RuntimeFactory.Current.Context.GetServiceConfiguration().GetSecureConfigParameter("OauthClientSecret");
try
{
AuthenticationResult token;
var userToken = GetUserToken();
var userId = GetUserObjectId();
var clientCredential = new ClientCredential(appClientId, appClientSecret);
if (userToken.ContainsCharacters())
{
try
{
token = ctx.AcquireToken(resource, clientCredential, new UserAssertion(userToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", RuntimeFactory.Current.GetCurrentClaimsIdentity().Name));
}
catch (Exception)
{
token = ctx.AcquireTokenSilent(resource, clientCredential, GetUserAssertion());
}
}
else if (userId.ContainsCharacters()) token = ctx.AcquireTokenSilent(resource, clientCredential, GetUserAssertion());
else
{
if (ConfigurationManagerHelper.GetValueOnKey("stardust.promptUserFOrCredentials", false)) token = ctx.AcquireToken(resource, appClientId, new Uri("http://" + Utilities.GetEnvironment() + "ters.dnvgl.com"), PromptBehavior.Auto);
else token = ctx.AcquireToken(resource, clientCredential);
}
return token;
}
catch (AdalSilentTokenAcquisitionException adalex)
{
if (adalex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
{
HttpContext.Current.GetOwinContext().Authentication.SignOut();
HttpContext.Current.GetOwinContext().Authentication.Challenge();
throw;
}
throw;
}
catch (System.Exception ex)
{
ex.Log();
throw;
}
}
示例2: GetAccessToken
public static string GetAccessToken(string resource) {
// get user ID in security cookie
var signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
// get token cache for signed in user
ApplicationDbContext db = new ApplicationDbContext();
ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID);
AuthenticationContext authContext = new AuthenticationContext(Authority, userTokenCache);
// Get credentials for user
var clientCredential = new ClientCredential(clientId, clientSecret);
// Create user identifier object using User ID for Azure Active Directory account
string objectIdentifierID = "http://schemas.microsoft.com/identity/claims/objectidentifier";
var userObjectId = ClaimsPrincipal.Current.FindFirst(objectIdentifierID).Value;
var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
// call to ADAL to get access token from cache of across network
var authResult = authContext.AcquireTokenSilent(resource, clientCredential, userIdentifier);
// obtain access token
return authResult.AccessToken;
}
示例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: GetUserOrganizations
public static List<Organization> GetUserOrganizations()
{
List<Organization> organizations = new List<Organization>();
string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];
try
{
// Aquire Access Token to call Azure Resource Manager
ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
ConfigurationManager.AppSettings["ida:Password"]);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
AuthenticationContext authContext = new AuthenticationContext(
string.Format(ConfigurationManager.AppSettings["ida:Authority"], tenantId), new ADALTokenCache(signedInUserUniqueName));
var items = authContext.TokenCache.ReadItems().ToList();
AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));
items = authContext.TokenCache.ReadItems().ToList();
// Get a list of Organizations of which the user is a member
string requestUrl = string.Format("{0}/tenants?api-version={1}", ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"],
ConfigurationManager.AppSettings["ida:AzureResourceManagerAPIVersion"]);
// Make the GET request
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = client.SendAsync(request).Result;
// Endpoint returns JSON with an array of Tenant Objects
// id tenantId
// -- --------
// /tenants/7fe877e6-a150-4992-bbfe-f517e304dfa0 7fe877e6-a150-4992-bbfe-f517e304dfa0
// /tenants/62e173e9-301e-423e-bcd4-29121ec1aa24 62e173e9-301e-423e-bcd4-29121ec1aa24
if (response.IsSuccessStatusCode)
{
string responseContent = response.Content.ReadAsStringAsync().Result;
var organizationsResult = (Json.Decode(responseContent)).value;
foreach (var organization in organizationsResult)
organizations.Add(new Organization()
{
Id = organization.tenantId,
//DisplayName = AzureADGraphAPIUtil.GetOrganizationDisplayName(organization.tenantId),
objectIdOfCloudSenseServicePrincipal =
AzureADGraphAPIUtil.GetObjectIdOfServicePrincipalInOrganization(organization.tenantId, ConfigurationManager.AppSettings["ida:ClientID"])
});
}
}
catch { }
return organizations;
}
示例5: AcquireToken
public static string AcquireToken(string userObjectId)
{
ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
string tenantId = ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value;
AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId), new TokenDbCache(userObjectId));
AuthenticationResult result = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
return result.AccessToken;
}
示例6: getTokenForGraph
private string getTokenForGraph(string tenantID, string signedInUserID, string userObjectID, string clientId, string appKey, string graphResourceID)
{
// get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
ClientCredential clientcred = new ClientCredential(clientId, appKey);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.chinacloudapi.cn/{0}", tenantID), new EFADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenSilent(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
return result.AccessToken;
}
示例7: GetAccessTokenForCurrentUser
/// <summary>
/// This helper method returns and OAuth Access Token for the current user
/// </summary>
/// <param name="resourceId">The resourceId for which we are requesting the token</param>
/// <returns>The OAuth Access Token value</returns>
public static String GetAccessTokenForCurrentUser(String resourceId = null)
{
String accessToken = null;
if (String.IsNullOrEmpty(resourceId))
{
resourceId = MicrosoftGraphResourceId;
}
try
{
ClientCredential credential = new ClientCredential(
ClientId,
ClientSecret);
String signedInUserID = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(
ClaimTypes.NameIdentifier).Value;
String tenantId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(
"http://schemas.microsoft.com/identity/claims/tenantid").Value;
AuthenticationContext authContext = new AuthenticationContext(
AADInstance + TenantId,
new SessionADALCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenSilent(
resourceId,
credential,
UserIdentifier.AnyUser);
if (result != null)
{
accessToken = result.AccessToken;
}
}
catch (AdalException ex)
{
if (ex.ErrorCode == "failed_to_acquire_token_silently")
{
// Refresh the access token from scratch
HttpContext.Current.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties
{
RedirectUri = HttpContext.Current.Request.Url.ToString(),
},
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
else
{
// Rethrow the exception
throw ex;
}
}
return (accessToken);
}
示例8: GetUserSubscriptions
public static List<Subscription> GetUserSubscriptions(string organizationId)
{
List<Subscription> subscriptions = null;
string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];
try
{
// Aquire Access Token to call Azure Resource Manager
X509Certificate2 keyCredential = new X509Certificate2(HttpContext.Current.Server.MapPath
(ConfigurationManager.AppSettings["KeyCredentialPath"]), "", X509KeyStorageFlags.MachineKeySet);
ClientAssertionCertificate clientAssertion = new ClientAssertionCertificate(ConfigurationManager.AppSettings["ClientId"], keyCredential);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
AuthenticationContext authContext = new AuthenticationContext(
string.Format(ConfigurationManager.AppSettings["Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["AzureResourceManagerIdentifier"], clientAssertion,
new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));
subscriptions = new List<Subscription>();
// Get subscriptions to which the user has some kind of access
string requestUrl = string.Format("{0}/subscriptions?api-version={1}", ConfigurationManager.AppSettings["AzureResourceManagerUrl"],
ConfigurationManager.AppSettings["AzureResourceManagerAPIVersion"]);
// Make the GET request
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = client.SendAsync(request).Result;
// Endpoint returns JSON with an array of Subscription Objects
// id subscriptionId displayName state
// -- -------------- ----------- -----
// /subscriptions/c276fc76-9cd4-44c9-99a7-4fd71546436e c276fc76-9cd4-44c9-99a7-4fd71546436e Production Enabled
// /subscriptions/e91d47c4-76f3-4271-a796-21b4ecfe3624 e91d47c4-76f3-4271-a796-21b4ecfe3624 Development Enabled
if (response.IsSuccessStatusCode)
{
string responseContent = response.Content.ReadAsStringAsync().Result;
var subscriptionsResult = (Json.Decode(responseContent)).value;
foreach (var subscription in subscriptionsResult)
subscriptions.Add(new Subscription()
{
Id = subscription.subscriptionId,
DisplayName = subscription.displayName,
});
}
}
catch { }
return subscriptions;
}
示例9: Index
public async Task<ActionResult> Index()
{
var clientId = "e0347f85-eb21-4ee1-b55c-d7d6f2b7db68";
var appKey = "3QEZFKVoEk9RHkSJcxWJvgqXkW8yO+sk2Jv7tc07UT4=";
var webApiResourceId = "http://AzureADOpenIdWebApi.JohnsonAzureAD.onmicrosoft.com";
var webApiBaseAddress = "http://localhost.fiddler:51734/";
var authority = "https://login.windows.net/JohnsonAzureAD.onmicrosoft.com";
/**
// To authenticate to the WebApi service, the client needs to know the service's App ID URI.
// To contact the To Do list service we need it's URL as well.
var authContext = new AuthenticationContext(authority);
var clientCredential = new ClientCredential(clientId, appKey);
// ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
var result = authContext.AcquireToken(webApiResourceId, clientCredential);
***/
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
var result = authContext.AcquireTokenSilent(webApiResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
//
// Retrieve the user's To Do List.
//
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, webApiBaseAddress + "/api/me");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await httpClient.SendAsync(request);
//
// Return the To Do List in the view.
//
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
ViewBag.Response = responseString;
}
return View();
}
示例10: GetGroupsFromGraphAPI
private static async Task<List<string>> GetGroupsFromGraphAPI(ClaimsIdentity claimsIdentity)
{
List<string> groupObjectIds = new List<string>();
// Acquire the Access Token
ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
// MULTITENANT - Since I've set Tenant=common, we can't use the regular Authority here, we need the user's tenant
// AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority,
// new TokenDbCache(claimsIdentity.FindFirst(Globals.ObjectIdClaimType).Value));
string userAuthority = String.Format(CultureInfo.InvariantCulture,
ConfigHelper.AadInstance,
ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value);
AuthenticationContext authContext = new AuthenticationContext(userAuthority,
new TokenDbCache(claimsIdentity.FindFirst(Globals.ObjectIdClaimType).Value));
AuthenticationResult result = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, credential,
new UserIdentifier(claimsIdentity.FindFirst(Globals.ObjectIdClaimType).Value, UserIdentifierType.UniqueId));
// Get the GraphAPI Group Endpoint for the specific user from the _claim_sources claim in token
string groupsClaimSourceIndex = (Json.Decode(claimsIdentity.FindFirst("_claim_names").Value)).groups;
var groupClaimsSource = (Json.Decode(claimsIdentity.FindFirst("_claim_sources").Value))[groupsClaimSourceIndex];
string requestUrl = groupClaimsSource.endpoint + "?api-version=" + ConfigHelper.GraphApiVersion;
// Prepare and Make the POST request
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
StringContent content = new StringContent("{\"securityEnabledOnly\": \"false\"}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
// Endpoint returns JSON with an array of Group ObjectIDs
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
var groupsResult = (Json.Decode(responseContent)).value;
foreach (string groupObjectID in groupsResult)
groupObjectIds.Add(groupObjectID);
}
else
{
throw new WebException();
}
return groupObjectIds;
}
示例11: GetGroupsFromGraphAPI
/// <summary>
/// In the case of Groups claim overage, we must query the GraphAPI to obtain the group membership.
/// Here we use the GraphAPI Client Library to do so.
/// </summary>
/// <param name="claimsIdentity">The <see cref="ClaimsIdenity" /> object that represents the
/// claims-based identity of the currently signed in user and contains thier claims.</param>
/// <returns>A list of ObjectIDs representing the groups that the user is member of.</returns>
private static async Task<List<string>> GetGroupsFromGraphAPI(ClaimsIdentity claimsIdentity)
{
List<string> groupObjectIds = new List<string>();
string tenantId = claimsIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string signedInUserID = claimsIdentity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
string userObjectID = claimsIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// Aquire Access Token to call Graph
ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
ConfigurationManager.AppSettings["ida:Password"]);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
AuthenticationContext authContext = new AuthenticationContext(
string.Format(ConfigurationManager.AppSettings["ida:Authority"], tenantId), new ADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenSilent(
ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"], credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
// Get the GraphAPI Group Endpoint for the specific user from the _claim_sources claim in token
string groupsClaimSourceIndex = (Json.Decode(claimsIdentity.FindFirst("_claim_names").Value)).groups;
var groupClaimsSource = (Json.Decode(claimsIdentity.FindFirst("_claim_sources").Value))[groupsClaimSourceIndex];
string requestUrl = groupClaimsSource.endpoint + "?api-version=" + ConfigurationManager.AppSettings["ida:GraphAPIVersion"];
// Prepare and Make the POST request
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
StringContent content = new StringContent("{\"securityEnabledOnly\": \"false\"}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
// Endpoint returns JSON with an array of Group ObjectIDs
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
var groupsResult = (Json.Decode(responseContent)).value;
foreach (string groupObjectID in groupsResult)
groupObjectIds.Add(groupObjectID);
}
else
{
throw new WebException();
}
return groupObjectIds;
}
示例12: GetOrganizationDisplayName
public static string GetOrganizationDisplayName(string organizationId)
{
string displayName = null;
string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];
try
{
// Aquire Access Token to call Azure AD Graph API
ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
ConfigurationManager.AppSettings["ida:Password"]);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
AuthenticationContext authContext = new AuthenticationContext(
string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"], credential,
new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));
// Get a list of Organizations of which the user is a member
string requestUrl = string.Format("{0}{1}/tenantDetails?api-version={2}", ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"],
organizationId, ConfigurationManager.AppSettings["ida:GraphAPIVersion"]);
// Make the GET request
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = client.SendAsync(request).Result;
// Endpoint returns JSON with an array of Tenant Objects
if (response.IsSuccessStatusCode)
{
string responseContent = response.Content.ReadAsStringAsync().Result;
var organizationPropertiesResult = (Json.Decode(responseContent)).value;
if (organizationPropertiesResult != null && organizationPropertiesResult.Length > 0)
{
displayName = organizationPropertiesResult[0].displayName;
if (organizationPropertiesResult[0].verifiedDomains != null)
foreach (var verifiedDomain in organizationPropertiesResult[0].verifiedDomains)
if (verifiedDomain["default"])
displayName += " (" + verifiedDomain.name + ")";
}
}
}
catch { }
return displayName;
}
示例13: CallService
public async Task<List<string>> CallService()
{
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
//AuthenticationContext authContext = new AuthenticationContext(Startup.Authority);
ClientCredential credential = new ClientCredential(clientId, appKey);
AuthenticationResult result = authContext.AcquireTokenSilent(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
//AuthenticationResult result = authContext.AcquireToken(todoListResourceId, credential,) new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
//AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential);
//
// Retrieve the user's To Do List.
//
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, todoListBaseAddress + "/ServiceTest");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
//
// Return the To Do List in the view.
//
if (response.IsSuccessStatusCode)
{
//List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
JsonSerializerSettings settings = new JsonSerializerSettings();
String responseString = await response.Content.ReadAsStringAsync();
//responseElements = JsonConvert.DeserializeObject<List<String, String>>(responseString, settings);
List<string> messages = JsonConvert.DeserializeObject<List<String>>(responseString, settings);
//foreach (Dictionary<String, String> responseElement in responseElements)
//{
// TodoItem newItem = new TodoItem();
// newItem.Title = responseElement["Title"];
// newItem.Owner = responseElement["Owner"];
// itemList.Add(newItem);
//}
return messages;
}
else
{
throw new UnauthorizedAccessException();
}
}
示例14: AcquireToken
public static string AcquireToken(string userObjectId)
{
ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
// MULTITENANT - Since I've set Tenant=common, we can't use the regular Authority here, we need the user's tenant
// AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
string userAuthority = String.Format(CultureInfo.InvariantCulture,
ConfigHelper.AadInstance,
ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value);
AuthenticationContext authContext = new AuthenticationContext(userAuthority, new TokenDbCache(userObjectId));
AuthenticationResult result = authContext.AcquireTokenSilent(
ConfigHelper.GraphResourceId,
cred,
new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)
);
return result.AccessToken;
}
示例15: GetAccessTokenForCurrentUser
/// <summary>
/// This helper method returns and OAuth Access Token for the current user
/// </summary>
/// <param name="resourceId">The resourceId for which we are requesting the token</param>
/// <returns>The OAuth Access Token value</returns>
public static String GetAccessTokenForCurrentUser(String resourceId = null)
{
String accessToken = null;
if (String.IsNullOrEmpty(resourceId))
{
resourceId = MicrosoftGraphConstants.MicrosoftGraphResourceId;
}
try
{
ClientCredential credential = new ClientCredential(
PnPPartnerPackSettings.ClientId,
PnPPartnerPackSettings.ClientSecret);
string signedInUserID = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(
ClaimTypes.NameIdentifier).Value;
string tenantId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(
"http://schemas.microsoft.com/identity/claims/tenantid").Value;
AuthenticationContext authContext = new AuthenticationContext(
PnPPartnerPackSettings.AADInstance + tenantId,
new SessionADALCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenSilent(
resourceId,
credential,
UserIdentifier.AnyUser);
accessToken = result.AccessToken;
}
catch (AdalException ex)
{
if (ex.ErrorCode == "failed_to_acquire_token_silently")
{
// Refresh the access token from scratch
ForceOAuthChallenge();
}
else
{
// Rethrow the exception
throw ex;
}
}
return (accessToken);
}