本文整理汇总了C#中Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenByAuthorizationCodeAsync方法的典型用法代码示例。如果您正苦于以下问题:C# AuthenticationContext.AcquireTokenByAuthorizationCodeAsync方法的具体用法?C# AuthenticationContext.AcquireTokenByAuthorizationCodeAsync怎么用?C# AuthenticationContext.AcquireTokenByAuthorizationCodeAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext
的用法示例。
在下文中一共展示了AuthenticationContext.AcquireTokenByAuthorizationCodeAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Authorize
public async Task<ActionResult> Authorize()
{
var authContext = new AuthenticationContext(Settings.AzureADAuthority);
var authStateString = Request.QueryString["state"];
var authState = JsonConvert.DeserializeObject<AuthState>(authStateString);
try
{
// Get the token.
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
Request.Params["code"], // the auth 'code' parameter from the Azure redirect.
loginRedirectUri, // same redirectUri as used before in Login method.
new ClientCredential(Settings.AzureADClientId, Settings.AzureADClientSecret), // use the client ID and secret to establish app identity.
Settings.GraphApiResource); // provide the identifier of the resource we want to access
await SaveAuthToken(authState, authResult);
authState.authStatus = "success";
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
authState.authStatus = "failure";
}
return RedirectToAction(nameof(AuthorizeComplete), new { authState = JsonConvert.SerializeObject(authState) });
}
示例2: ConfigureAuth
public void ConfigureAuth(IAppBuilder app)
{
ApplicationDbContext db = new ApplicationDbContext();
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions {
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
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(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, resourceAzureGraphAPI).Result;
return Task.FromResult(0);
}
}
});
}
示例3: CompleteAuth
public async Task<HttpResponseMessage> CompleteAuth(string code)
{
AuthenticationContext AC = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
ClientCredential cc = new ClientCredential(clientId, clientSecret);
AuthenticationResult ar = await AC.AcquireTokenByAuthorizationCodeAsync(code, new Uri(redirectUrl), cc);
PowerBIController.authorization = new AuthResult { Expires = ar.ExpiresOn.UtcDateTime, AccessToken = ar.AccessToken, RefreshToken = ar.RefreshToken };
await WriteTokenToStorage(PowerBIController.authorization);
return Request.CreateResponse(HttpStatusCode.OK, "Successfully Authenticated");
}
示例4: ConfigureAuth
internal static void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieManager = new SystemWebCookieManager()
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
Authority = OfficeSettings.Authority,
ClientId = OfficeSettings.ClientId,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthorizationCodeReceived = async (context) =>
{
string code = context.Code;
ClientCredential credential = new ClientCredential(OfficeSettings.ClientId,
OfficeSettings.ClientSecret);
string signInUserId = context.AuthenticationTicket
.Identity
.FindFirst(ClaimTypes.NameIdentifier)
.Value;
AuthenticationContext ctx = new AuthenticationContext(OfficeSettings.Authority,
new ADALTokenCache(signInUserId));
var result = await ctx.AcquireTokenByAuthorizationCodeAsync(code,
new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
credential,
OfficeSettings.GraphResourceId);
return;
},
RedirectToIdentityProvider = (context) =>
{
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) =>
{
if (context.Exception.Message.StartsWith("OICE_20004") || context.Exception.Message.Contains("IDX10311"))
{
context.SkipToNextMiddleware();
return Task.FromResult(0);
}
context.HandleResponse();
context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
示例5: OnAuthorizationCodeReceived
public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
// Acquire a Token for the Graph API and cache it. In the TodoListController, we'll use the cache to acquire a token to the Todo List API
string userObjectId = notification.AuthenticationTicket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
ClientCredential clientCred = new ClientCredential(ClientId, AppKey);
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, notification.HttpContext.Session));
AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
notification.Code, new Uri(notification.RedirectUri), clientCred, Startup.GraphResourceId);
}
开发者ID:vansonvinhuni,项目名称:active-directory-dotnet-webapp-webapi-openidconnect-aspnet5,代码行数:9,代码来源:Startup.Auth.cs
示例6: OnAuthorizationCodeReceived
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
string userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
string tenantID = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenantID, string.Empty);
ClientCredential cred = new ClientCredential(clientId, clientSecret);
// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false, new NaiveSessionCache(userObjectId));
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(redirectUri), cred, new string[] { clientId });
}
示例7: ConfigureAuth
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions { });
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
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()
{
SecurityTokenValidated = (context) =>
{
return Task.FromResult(0);
},
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
// 2016-10-02 Commenting out because the ADALTokenCache threw an exception about empty DB connection string.
// AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID);
return
authContext.AcquireTokenByAuthorizationCodeAsync(
code,
new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
credential,
graphResourceID);
//return Task.FromResult(0);
},
AuthenticationFailed = (context) =>
{
telemetry.TrackException(context.Exception);
context.OwinContext.Response.Redirect("/Home/Error");
context.HandleResponse(); // Suppress the exception
return Task.FromResult(0);
}
}
});
}
示例8: ProcessCode
// GET: /TOnboarding/ProcessCode
public ActionResult ProcessCode(string code, string error, string error_description, string resource, string state)
{
// Is this a response to a request we generated? Let's see if the state is carrying an ID we previously saved
// ---if we don't, return an error
if (db.Tenants.FirstOrDefault(a => a.IssValue == state) == null)
{
// TODO: prettify
return View("Error");
}
else
{
// ---if the response is indeed from a request we generated
// ------get a token for the Graph, that will provide us with information abut the caller
ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
ConfigurationManager.AppSettings["ida:Password"]);
AuthenticationContext authContext = new AuthenticationContext("https://login.chinacloudapi.cn/common/");
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(
code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential).Result;
var myTenant = db.Tenants.FirstOrDefault(a => a.IssValue == state);
// if this was an admin consent, save the tenant
if (myTenant.AdminConsented)
{
// ------read the tenantID out of the Graph token and use it to create the issuer string
string issuer = String.Format("https://sts.chinacloudapi.cn/{0}/", result.TenantId);
myTenant.IssValue = issuer;
}
else
//otherwise, remove the temporary entry and save just the user
{
if (db.Users.FirstOrDefault(a => (a.UPN == result.UserInfo.DisplayableId) && (a.TenantID == result.TenantId)) == null)
{
db.Users.Add(new User { UPN = result.UserInfo.DisplayableId, TenantID = result.TenantId });
}
db.Tenants.Remove(myTenant);
}
// remove older, unclaimed entries
DateTime tenMinsAgo = DateTime.Now.Subtract(new TimeSpan(0, 10, 0)); // workaround for Linq to entities
var garbage = db.Tenants.Where(a => (!a.IssValue.StartsWith("https") && (a.Created < tenMinsAgo)));
foreach (Tenant t in garbage)
db.Tenants.Remove(t);
db.SaveChanges();
// ------return a view claiming success, inviting the user to sign in
return View();
}
}
示例9: Authorize
public async Task<ActionResult> Authorize()
{
// Create new authentication context
var authContext = new AuthenticationContext(Settings.Authority);
// The URL where Azure redirects to after successful login
Uri loginRedirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
// Get the access token
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(Request.Params["code"], loginRedirectUri, new ClientCredential(Settings.ClientId, Settings.ClientSecret), Settings.GraphUri);
// Save the token in the session.
Session["access_token"] = authResult.AccessToken;
return RedirectToAction("Index");
}
示例10: Authorize
public async Task<ActionResult> Authorize()
{
var authContext = new AuthenticationContext(Settings.AzureADAuthority);
// Get the token.
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
Request.Params["code"], // the auth 'code' parameter from the Azure redirect.
loginRedirectUri, // same redirectUri as used before in Login method.
new ClientCredential(Settings.ClientId, Settings.ClientSecret), // use the client ID and secret to establish app identity.
Settings.O365UnifiedAPIResource);
// Save the token in the session.
Session[SessionKeys.Login.AccessToken] = authResult.AccessToken;
// Get info about the current logged in user.
Session[SessionKeys.Login.UserInfo] = await GraphHelper.GetUserInfoAsync(authResult.AccessToken);
return RedirectToAction(nameof(Index), "PersonalData");
}
示例11: Authorize
public async System.Threading.Tasks.Task<ActionResult> Authorize(string code)
{
try
{
string powerBISchema = "Unable to retrieve schema";
using (var client = new HttpClient())
{
var schemaResult = await client.GetAsync("https://raw.githubusercontent.com/jeffhollan/MSHealthAPI/master/Power%20BI%20Dataset%20Schema.json");
powerBISchema = await schemaResult.Content.ReadAsStringAsync();
AuthenticationContext AC = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
ClientCredential cc = new ClientCredential(ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]);
AuthenticationResult ar = await AC.AcquireTokenByAuthorizationCodeAsync(code, new Uri(ConfigurationManager.AppSettings["redirect"].ToLower()), cc);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ar.AccessToken);
var createResult = await client.PostAsync("https://api.powerbi.com/v1.0/myorg/datasets?defaultRetentionPolicy=None", new StringContent(powerBISchema, Encoding.UTF8, "application/json"));
var resultString = await createResult.Content.ReadAsStringAsync();
ViewBag.datasetid = (string)JObject.Parse(resultString)["id"];
}
return View();
}
catch (Exception ex)
{
return View("Error");
}
}
示例12: Index
public async Task<ActionResult> Index(string code)
{
List<MyEvent> eventList = new List<MyEvent>();
AuthenticationContext authContext = new AuthenticationContext(
ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
true);
ClientCredential creds = new ClientCredential(
ConfigurationManager.AppSettings["ida:ClientID"],
ConfigurationManager.AppSettings["ida:Password"]);
DiscoveryClient disco = GetFromCache("DiscoveryClient") as DiscoveryClient;
CapabilityDiscoveryResult eventsDisco =GetFromCache("EventsDiscovery") as CapabilityDiscoveryResult;
//Redirect to login page if we do not have an
//authorization code for the Discovery service
if (disco == null && code == null)
{
Uri redirectUri = authContext.GetAuthorizationRequestURL(
discoResource,
creds.ClientId,
new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
UserIdentifier.AnyUser,
string.Empty);
return Redirect(redirectUri.ToString());
}
//Create a DiscoveryClient using the authorization code
if (disco == null && code != null)
{
disco = new DiscoveryClient(new Uri(discoEndpoint), async () =>
{
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
code,
new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
creds);
return authResult.AccessToken;
});
}
if (disco != null && code != null & eventsDisco == null)
{
//Discover required capabilities
eventsDisco = await disco.DiscoverCapabilityAsync("Calendar");
SaveInCache("EventsDiscovery", eventsDisco);
code = null;
//Get authorization code for the calendar
Uri redirectUri = authContext.GetAuthorizationRequestURL(
eventsDisco.ServiceResourceId,
creds.ClientId,
new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
UserIdentifier.AnyUser,
string.Empty);
return Redirect(redirectUri.ToString());
}
//Get the calendar events
if (disco != null && code != null & eventsDisco != null)
{
OutlookServicesClient outlookClient = new OutlookServicesClient(eventsDisco.ServiceEndpointUri, async () =>
{
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
code,
new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
creds);
return authResult.AccessToken;
});
//Get the events for the next 8 hours
var eventResults = await (from i in outlookClient.Me.Events
where i.End >= DateTimeOffset.UtcNow && i.End <= DateTimeOffset.UtcNow.AddHours(8)
select i).Take(5).ExecuteAsync();
var events = eventResults.CurrentPage.OrderBy(e => e.Start);
foreach (var e in events)
{
eventList.Add(new MyEvent
{
Id = e.Id,
Body = e.Body == null ? string.Empty : e.Body.Content,
End = e.End,
Location = e.Location == null ? string.Empty : e.Location.DisplayName,
Start = e.Start,
Subject = e.Subject == null ? string.Empty : e.Subject
});
}
//.........这里部分代码省略.........
示例13: Configure
public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
{
loggerfactory.AddConsole(Microsoft.Extensions.Logging.LogLevel.Information);
// Simple error page
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
if (!context.Response.HasStarted)
{
context.Response.Clear();
context.Response.StatusCode = 500;
await context.Response.WriteAsync(ex.ToString());
}
else
{
throw;
}
}
});
app.UseCookieAuthentication(new CookieAuthenticationOptions());
var clientId = Configuration["oidc:clientid"];
var clientSecret = Configuration["oidc:clientsecret"];
var authority = Configuration["oidc:authority"];
var resource = "https://graph.windows.net";
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = clientId,
ClientSecret = clientSecret, // for code flow
Authority = authority,
ResponseType = OpenIdConnectResponseType.CodeIdToken,
// GetClaimsFromUserInfoEndpoint = true,
Events = new OpenIdConnectEvents()
{
OnAuthorizationCodeReceived = async context =>
{
var request = context.HttpContext.Request;
var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
var credential = new ClientCredential(clientId, clientSecret);
var authContext = new AuthenticationContext(authority, AuthPropertiesTokenCache.ForCodeRedemption(context.Properties));
var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
context.ProtocolMessage.Code, new Uri(currentUri), credential, resource);
context.HandleCodeRedemption();
}
}
});
app.Run(async context =>
{
if (context.Request.Path.Equals("/signout"))
{
await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
context.Response.ContentType = "text/html";
await context.Response.WriteAsync($"<html><body>Signing out {context.User.Identity.Name}<br>{Environment.NewLine}");
await context.Response.WriteAsync("<a href=\"/\">Sign In</a>");
await context.Response.WriteAsync($"</body></html>");
return;
}
if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
{
await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" });
return;
}
context.Response.ContentType = "text/html";
await context.Response.WriteAsync($"<html><body>Hello Authenticated User {context.User.Identity.Name}<br>{Environment.NewLine}");
await context.Response.WriteAsync("Claims:<br>" + Environment.NewLine);
foreach (var claim in context.User.Claims)
{
await context.Response.WriteAsync($"{claim.Type}: {claim.Value}<br>{Environment.NewLine}");
}
await context.Response.WriteAsync("Tokens:<br>" + Environment.NewLine);
try
{
// Use ADAL to get the right token
var authContext = new AuthenticationContext(authority, AuthPropertiesTokenCache.ForApiCalls(context, CookieAuthenticationDefaults.AuthenticationScheme));
var credential = new ClientCredential(clientId, clientSecret);
string userObjectID = context.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
var result = await authContext.AcquireTokenSilentAsync(resource, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
await context.Response.WriteAsync($"access_token: {result.AccessToken}<br>{Environment.NewLine}");
}
catch (Exception ex)
{
await context.Response.WriteAsync($"AquireToken error: {ex.Message}<br>{Environment.NewLine}");
}
await context.Response.WriteAsync("<a href=\"/signout\">Sign Out</a>");
await context.Response.WriteAsync($"</body></html>");
//.........这里部分代码省略.........
示例14: ConfigureAuth
public void ConfigureAuth(IAppBuilder app)
{
Certificate = LoadCertificate();
if (Certificate == null)
{
throw new Exception("Certificate == null");
}
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
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 = async (context) =>
{
// This code gets the AccessToken for the AAD graph. This will be needed for some scenarios. However, it might
// be that we should ask for the services resource id at this stage. The AuthenticationResult includes a RefreshToken.
var code = context.Code;
var signedInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
string tenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string authority = string.Format(aadInstance, tenantId);
AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserId));
ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Certificate);
AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), clientAssertionCertificate, graphResourceId);
},
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);
},
SecurityTokenReceived = (context) =>
{
return Task.FromResult(0);
},
AuthenticationFailed = (context) =>
{
//context.OwinContext.Response.Redirect("/Home/Error");
//context.HandleResponse(); // Suppress the exception
return Task.FromResult(0);
}
}
});
}
示例15: Index
/// <summary>
/// Use the DiscoveryClient to get the Contacts and Files endpoints
/// </summary>
/// <param name="code">The authorization code to use when getting an access token</param>
/// <returns></returns>
public async Task<ActionResult> Index(string code)
{
AuthenticationContext authContext = new AuthenticationContext(
ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
true);
ClientCredential creds = new ClientCredential(
ConfigurationManager.AppSettings["ida:ClientID"],
ConfigurationManager.AppSettings["ida:Password"]);
DiscoveryClient disco = Helpers.GetFromCache("DiscoveryClient") as DiscoveryClient;
//Redirect to login page if we do not have an
//authorization code for the Discovery service
if (disco == null && code == null)
{
Uri redirectUri = authContext.GetAuthorizationRequestURL(
discoResource,
creds.ClientId,
new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
UserIdentifier.AnyUser,
string.Empty);
return Redirect(redirectUri.ToString());
}
//Create a DiscoveryClient using the authorization code
if (disco == null && code != null)
{
disco = new DiscoveryClient(new Uri(discoEndpoint), async () =>
{
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
code,
new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
creds);
return authResult.AccessToken;
});
}
//Discover required capabilities
CapabilityDiscoveryResult contactsDisco = await disco.DiscoverCapabilityAsync("Contacts");
CapabilityDiscoveryResult filesDisco = await disco.DiscoverCapabilityAsync("MyFiles");
Helpers.SaveInCache("ContactsDiscoveryResult", contactsDisco);
Helpers.SaveInCache("FilesDiscoveryResult", filesDisco);
List<MyDiscovery> discoveries = new List<MyDiscovery>(){
new MyDiscovery(){
Capability = "Contacts",
EndpointUri = contactsDisco.ServiceEndpointUri.OriginalString,
ResourceId = contactsDisco.ServiceResourceId,
Version = contactsDisco.ServiceApiVersion
},
new MyDiscovery(){
Capability = "My Files",
EndpointUri = filesDisco.ServiceEndpointUri.OriginalString,
ResourceId = filesDisco.ServiceResourceId,
Version = filesDisco.ServiceApiVersion
}
};
return View(discoveries);
}