本文整理汇总了C#中Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenByAuthorizationCode方法的典型用法代码示例。如果您正苦于以下问题:C# AuthenticationContext.AcquireTokenByAuthorizationCode方法的具体用法?C# AuthenticationContext.AcquireTokenByAuthorizationCode怎么用?C# AuthenticationContext.AcquireTokenByAuthorizationCode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext
的用法示例。
在下文中一共展示了AuthenticationContext.AcquireTokenByAuthorizationCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
//Redirect uri must match the redirect_uri used when requesting Authorization code.
string redirectUri = Properties.Settings.Default.RedirectUrl;
string authorityUri = "https://login.windows.net/common/oauth2/authorize/";
// Get the auth code
string code = Request.Params.GetValues(0)[0];
// Get auth token from auth code
TokenCache TC = new TokenCache();
AuthenticationContext AC = new AuthenticationContext(authorityUri, TC);
ClientCredential cc = new ClientCredential
(Properties.Settings.Default.ClientID,
Properties.Settings.Default.ClientSecretKey);
AuthenticationResult AR = AC.AcquireTokenByAuthorizationCode(code, new Uri(redirectUri), cc);
//Set Session "authResult" index string to the AuthenticationResult
Session["authResult"] = AR;
//Redirect back to Default.aspx
Response.Redirect("/Default.aspx");
}
示例2: ConfigureAuth
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
//Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ConfigHelper.ClientId,
Authority = ConfigHelper.Authority,
PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = context =>
{
ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId);
return Task.FromResult(0);
},
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
示例3: GetAuthenticatedUserIDentity
/// <summary>
/// Acquires an IUserIdentity from Azure Active Directory using the argument authorizationCode.
/// </summary>
/// <param name="authorizationCode">An authorization code provided by Azure Active Directory used to retrieve an IUserIdentity</param>
/// <returns>Returns an IUserIdentity representing a successfully authenticated Azure Active Directory user who has privileges for this configured application</returns>
public static IUserIdentity GetAuthenticatedUserIDentity(string authorizationCode)
{
var authenticationContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", AAD.TENANT_ID));
var clientCredential = new ClientCredential(AAD.CLIENT_ID, AAD.CLIENT_KEY);
var authenticationResult = authenticationContext.AcquireTokenByAuthorizationCode(authorizationCode, new Uri(AAD.REPLY_URL), clientCredential);
return new UserIdentity(authenticationResult.UserInfo);
}
示例4: Token
public ActionResult Token(string code)
{
var authenticationContext = new AuthenticationContext(authority);
var tokenResult = authenticationContext.AcquireTokenByAuthorizationCode(code, new Uri(redirectUrl), new ClientCredential(clientId, clientSecret), resource);
var accessToken = tokenResult.AccessToken;
using (ClientContext ctx = new ClientContext(resource))
{
ctx.ExecutingWebRequest += (object sender, WebRequestEventArgs e) =>
{
e.WebRequestExecutor.RequestHeaders.Add("Authorization", "Bearer " + accessToken);
};
var web = ctx.Web;
ctx.Load(web, a => a.Title, a=>a.CurrentUser);
ctx.ExecuteQuery();
var title = web.Title;
ViewBag.SiteTitle = title;
ViewBag.LoggedUser = web.CurrentUser.Title;
ViewBag.LoggedUserEmail = web.CurrentUser.Email;
}
return View("Index");
}
示例5: 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
}
});
}
示例6: 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.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
return Task.FromResult(0);
}
}
});
}
示例7: 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);
}
示例8: Associate
public AssociationStatusEnum Associate(string state, string code, Uri requestUri)
{
ClientCredential clientCredential = new ClientCredential(Constants.ClientId, Constants.ClientKey);
AuthenticationContext context = new AuthenticationContext("https://login.windows.net/common/");
AuthenticationResult result = context.AcquireTokenByAuthorizationCode(code, requestUri, clientCredential);
return ConvertTemporaryTenantToPermanentTenant(state, result.TenantId);
}
开发者ID:JamesRandall,项目名称:AzureAdOffice365MultiTenantedAuthentication,代码行数:8,代码来源:AzureTenantService.cs
示例9: ConfigureAuth
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
//app.UseCookieAuthentication(new CookieAuthenticationOptions {
// CookieManager = new Components.SystemWebCookieManager()
//});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = MSGraphAPISettings.ClientId,
Authority = MSGraphAPISettings.AADInstance + "common",
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(
MSGraphAPISettings.ClientId,
MSGraphAPISettings.ClientSecret);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(
ClaimTypes.NameIdentifier).Value;
string tenantId = context.AuthenticationTicket.Identity.FindFirst(
"http://schemas.microsoft.com/identity/claims/tenantid").Value;
AuthenticationContext authContext = new AuthenticationContext(
MSGraphAPISettings.AADInstance + tenantId,
new SessionADALCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
credential, MSGraphAPISettings.MicrosoftGraphResourceId);
return Task.FromResult(0);
},
AuthenticationFailed = (context) =>
{
context.OwinContext.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
context.HandleResponse(); // Suppress the exception
return Task.FromResult(0);
}
}
});
}
示例10: ConfigureAuth
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
//app.UseWindowsAzureActiveDirectoryBearerAuthentication(
// new WindowsAzureActiveDirectoryBearerAuthenticationOptions
// {
// Audience = ConfigurationManager.AppSettings["ida:Audience"],
// Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
// });
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 userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
//AuthenticationContext authContext = new AuthenticationContext(Authority);
//AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
//AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential);
//string todoListBaseAddress = ConfigurationManager.AppSettings["todo:TodoListBaseAddress"];
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, serviceResourceId);
return Task.FromResult(0);
},
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
示例11: ConfigureAuth
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
//Implement our own cookie manager to work around the infinite
//redirect loop issue
CookieManager = new SystemWebCookieManager()
});
string clientID = ConfigurationManager.AppSettings["ida:ClientID"];
string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
string clientSecret = ConfigurationManager.AppSettings["ida:AppKey"];
string graphResourceID = ConfigurationManager.AppSettings["ida:GraphResourceID"];
string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientID,
Authority = authority,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// when an auth code is received...
AuthorizationCodeReceived = (context) =>
{
// get the OpenID Connect code passed from Azure AD on successful auth
string code = context.Code;
// create the app credentials & get reference to the user
ClientCredential creds = new ClientCredential(clientID, clientSecret);
string signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
// use the OpenID Connect code to obtain access token & refresh token...
// save those in a persistent store...
AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCache(signInUserId));
// obtain access token for the AzureAD graph
Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, graphResourceID);
// successful auth
return Task.FromResult(0);
},
AuthenticationFailed = (context) =>
{
context.HandleResponse();
return Task.FromResult(0);
}
}
});
}
示例12: OnAuthorizationCodeReceived
private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
string userObjectId = notification.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
string tenantId = notification.AuthenticationTicket.Identity.FindFirst(Globals.TenantIdClaimType).Value;
AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId), new TokenDbCache(userObjectId));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
notification.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)), credential, ConfigHelper.GraphResourceId);
return Task.FromResult(0);
}
示例13: 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.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
// added by [email protected] to the original template
// Getting KeyDelivery Access Token
AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, kdResourceId);
string kdAccessToken = kdAPiresult.AccessToken;
System.IdentityModel.Tokens.JwtSecurityToken kdAccessJwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(kdAccessToken);
//context.AuthenticationTicket.Identity.AddClaim(
// new System.Security.Claims.Claim("KdAccessJwtSecurityTokenClaim", kdAccessJwtToken.RawData));
// added by [email protected] to the original template
return Task.FromResult(0);
}
}
});
}
示例14: ConfigureAuth
//
// The Client ID is used by the application to uniquely identify itself to Azure AD.
// The App Key is a credential used to authenticate the application to Azure AD. Azure AD supports password and certificate credentials.
// The Metadata Address is used by the application to retrieve the signing keys used by Azure AD.
// The AAD Instance is the instance of Azure, for example public Azure or Azure China.
// The Authority is the sign-in URL of the tenant.
// The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
//
// This is the resource ID of the AAD Graph API. We'll need this to request a token to call the Graph API.
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = MediaLibraryWebApp.Configuration.ClientId,
Authority = MediaLibraryWebApp.Configuration.Authority,
PostLogoutRedirectUri = MediaLibraryWebApp.Configuration.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;
System.IdentityModel.Tokens.JwtSecurityToken jwtToken = context.JwtSecurityToken;
string userObjectID = context.AuthenticationTicket.Identity.FindFirst(MediaLibraryWebApp.Configuration.ClaimsObjectidentifier).Value;
Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(MediaLibraryWebApp.Configuration.ClientId, MediaLibraryWebApp.Configuration.AppKey);
NaiveSessionCache cache = new NaiveSessionCache(userObjectID);
AuthenticationContext authContext = new AuthenticationContext(MediaLibraryWebApp.Configuration.Authority, cache);
//Getting a token to connect with GraphApi later on userProfile page
AuthenticationResult graphAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.GraphResourceId);
//Getting a access token which can be used to configure auth restrictions for multiple tentants since audience will be same for each web app requesting this token
//AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.KdResourceId);
//string kdAccessToken = kdAPiresult.AccessToken;
//Initializing MediaServicesCredentials in order to obtain access token to be used to connect
var amsCredentials = new MediaServicesCredentials(MediaLibraryWebApp.Configuration.MediaAccount, MediaLibraryWebApp.Configuration.MediaKey);
//Forces to get access token
amsCredentials.RefreshToken();
//Adding token to a claim so it can be accessible within controller
context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsSignInJwtToken, jwtToken.RawData));
//Adding media services access token as claim so it can be accessible within controller
context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsAmsAcessToken, amsCredentials.AccessToken));
return Task.FromResult(0);
}
}
});
}
示例15: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
String code = Request["code"];
String error = Request["error"];
String error_description = Request["error_description"];
String resource = Request["resource"];
String state = Request["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)
{
failedOnBoarding.Visible = true;
errorMessage.Text = error_description;
errorDescription.Text = error_description;
}
else
{
successedOnBoarding.Visible = true;
// ---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(AuthenticationHelper.ClientId, AuthenticationHelper.SharedSecret);
AuthenticationContext authContext = new AuthenticationContext(AuthenticationHelper.AuthorityMultitenant);
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential);
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.windows.net/{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();
}
}