public static string GetAccessToken(string[] scopes) { // create new public client application var appPublic = PublicClientApplicationBuilder.Create(applicationId) .WithAuthority(tenantCommonAuthority) .WithRedirectUri(redirectUri) .Build(); // connect application to token cache TokenCacheHelper.EnableSerialization(appPublic.UserTokenCache); AuthenticationResult authResult; try { // try to acquire token from token cache var user = appPublic.GetAccountsAsync().Result.FirstOrDefault(); authResult = appPublic.AcquireTokenSilent(scopes, user).ExecuteAsync().Result; } catch { authResult = appPublic.AcquireTokenInteractive(scopes).ExecuteAsync().Result; } // return access token to caller return(authResult.AccessToken); }
static App() { _clientApp = PublicClientApplicationBuilder.Create(ClientId) .WithAuthority(AzureCloudInstance.AzurePublic, Tenant) .Build(); TokenCacheHelper.EnableSerialization(_clientApp.UserTokenCache); }
/* * Callback function when an authorization code is received */ private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) { // Extract the code from the response notification string code = notification.Code; // Extract signed in user id string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; // MSAL v3 confidential application creation IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(ClientId) .WithB2CAuthority(Authority) .WithClientSecret(ClientSecret) .WithRedirectUri(RedirectUri) .Build(); // Enable encrypted persistence to local file for tokens TokenCacheHelper.EnableSerialization(cca.UserTokenCache); try { // MSAL v3 get accesstoken by authorization code AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(Scopes, code).ExecuteAsync(); } catch (Exception ex) { //TODO: Handle throw; } }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { var scopes = new string[] { "https://admin.services.crm.dynamics.com/user_impersonation", "offline_access" }; if (req.Method == "POST" && req.Form.ContainsKey("code")) { var code = req.Form["code"].FirstOrDefault(); var app = ConfidentialClientApplicationBuilder.Create(_settings.ClientId) .WithClientSecret(_settings.ClientSecret) .WithTenantId(_settings.Tenant) .WithRedirectUri(req.GetDisplayUrl()) .Build(); var cache = new TokenCacheHelper(AzureApp.CacheFileDir); cache.EnableSerialization(app.UserTokenCache); _ = await app.AcquireTokenByAuthorizationCode(new string[] { $"{_settings.DynamicsUrl}/user_impersonation" }, code).ExecuteAsync(); return(new OkObjectResult("The app is authorized to perform operations on behalf of your account.")); } var url = new StringBuilder(); url.Append($"https://login.microsoftonline.com/{_settings.Tenant}/oauth2/v2.0/authorize?"); url.Append($"client_id={_settings.ClientId}&"); url.Append($"response_type=code&"); url.Append($"redirect_uri={req.GetEncodedUrl()}&"); url.Append($"response_mode=form_post&"); url.Append($"scope={WebUtility.UrlEncode(string.Join(" ", scopes))}&"); return(new RedirectResult(url.ToString(), false)); }
/// <summary> /// Retrieves an access token for the specified scopes. /// </summary> private async Task <string> GetAccessTokenAsync(params string[] scopes) { string signedInUserID = User.GetId(); // MSAL v3 confidential application creation IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(Startup.ClientId) .WithB2CAuthority(Startup.Authority) .WithClientSecret(Startup.ClientSecret) .WithRedirectUri(Startup.RedirectUri) .Build(); // Enable encrypted persistence to local file for tokens TokenCacheHelper.EnableSerialization(cca.UserTokenCache); IEnumerable <IAccount> accounts = await cca.GetAccountsAsync(); IAccount account = accounts.FirstOrDefault(acc => acc.HomeAccountId.Identifier.StartsWith(signedInUserID)); if (account == null) { throw new Exception("The account is NULL. Please clear your cookies and try again. Specifically delete cookies for 'login.microsoftonline.com'. See this GitHub issue for more details: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/9"); } AuthenticationResult result = await cca.AcquireTokenSilent(Startup.Scopes, account) .WithB2CAuthority(Startup.Authority) .ExecuteAsync(); return(result.AccessToken); }
public DriveAccountService(SiteContext siteContext) { if (Configuration.Type == Configuration.OfficeType.China) { app = ConfidentialClientApplicationBuilder .Create(Configuration.ClientId) .WithClientSecret(Configuration.ClientSecret) .WithRedirectUri(Configuration.BaseUri + "/api/admin/bind/new") .WithAuthority(AzureCloudInstance.AzureChina, "common") .Build(); } else { app = ConfidentialClientApplicationBuilder .Create(Configuration.ClientId) .WithClientSecret(Configuration.ClientSecret) .WithRedirectUri(Configuration.BaseUri + "/api/admin/bind/new") .WithAuthority(AzureCloudInstance.AzurePublic, "common") .Build(); } //缓存Token TokenCacheHelper.EnableSerialization(app.UserTokenCache); //这里要传入一个 Scope 否则默认使用 https://graph.microsoft.com/.default //而导致无法使用世纪互联版本 authProvider = new AuthorizationCodeProvider(app, Configuration.Scopes); //获取Token if (File.Exists(TokenCacheHelper.CacheFilePath)) { authorizeResult = authProvider.ClientApplication.AcquireTokenSilent(Configuration.Scopes, Configuration.AccountName).ExecuteAsync().Result; //Debug.WriteLine(authorizeResult.AccessToken); } //启用代理 if (!string.IsNullOrEmpty(Configuration.Proxy)) { // Configure your proxy var httpClientHandler = new HttpClientHandler { Proxy = new WebProxy(Configuration.Proxy), UseDefaultCredentials = true }; var httpProvider = new Microsoft.Graph.HttpProvider(httpClientHandler, false) { OverallTimeout = TimeSpan.FromSeconds(10) }; Graph = new Microsoft.Graph.GraphServiceClient($"{Configuration.GraphApi}/v1.0", authProvider, httpProvider); } else { Graph = new Microsoft.Graph.GraphServiceClient($"{Configuration.GraphApi}/v1.0", authProvider); } this.SiteContext = siteContext; //定时更新Token Timer timer = new Timer(o => { if (File.Exists(TokenCacheHelper.CacheFilePath)) { authorizeResult = authProvider.ClientApplication.AcquireTokenSilent(Configuration.Scopes, Configuration.AccountName).ExecuteAsync().Result; } }, null, TimeSpan.FromSeconds(0), TimeSpan.FromHours(1)); }
public AuthService(string clientId) { _publicClientApp = PublicClientApplicationBuilder.Create(clientId) .WithAuthority(CloudInstance, Tenant) .WithDefaultRedirectUri() // MAKE SURE YOU SET http://localhost AS REDIRECT URI IN THE AZURE PORTAL .Build(); TokenCacheHelper.EnableSerialization(_publicClientApp.UserTokenCache); }
private static IAuthenticationProvider CreateAuthorizationProvider() { var clientApplication = PublicClientApplicationBuilder .Create(clientId) .WithAuthority(authority) .Build(); TokenCacheHelper.EnableSerialization(clientApplication.UserTokenCache); return(new MsalAuthenticationProvider(clientApplication, scopes.ToArray())); }
public DeviceCodeAuthProvider(string appId, string[] scopes) { _scopes = scopes; _msalClient = PublicClientApplicationBuilder .Create(appId) .WithAuthority(AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount, true) .WithRedirectUri("http://localhost:8383") .Build(); TokenCacheHelper.EnableSerialization(_msalClient.UserTokenCache); }
public static string GetAppOnlyAccessToken() { var appConfidential = ConfidentialClientApplicationBuilder.Create(confidentialApplicationId) .WithClientSecret(confidentialApplicationSecret) .WithAuthority(tenantSpecificAuthority) .Build(); TokenCacheHelper.EnableSerialization(appConfidential.UserTokenCache); string[] scopesDefault = new string[] { "https://analysis.windows.net/powerbi/api/.default" }; var authResult = appConfidential.AcquireTokenForClient(scopesDefault).ExecuteAsync().Result; return(authResult.AccessToken); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var app = ConfidentialClientApplicationBuilder.Create(_azureAppSettings.ClientId) .WithClientSecret(_azureAppSettings.ClientSecret) .WithTenantId(_azureAppSettings.Tenant) .Build(); var cache = new TokenCacheHelper(AzureApp.CacheFileDir); cache.EnableSerialization(app.UserTokenCache); var accounts = await app.GetAccountsAsync(); var result = await app.AcquireTokenSilent(new string[] { $"{_azureAppSettings.DynamicsUrl}/user_impersonation" }, accounts.FirstOrDefault()).ExecuteAsync(); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); return(await base.SendAsync(request, cancellationToken)); }
public GraphServiceClient GetGraphClient(ILogger logger) { if (_PublicClientApplication == null) { _PublicClientApplication = PublicClientApplicationBuilder .Create(_Options.ClientId) .WithAuthority(new Uri($"{_Options.Instance}/{_Options.TenantId}")) .Build(); TokenCacheHelper.EnableSerialization(_PublicClientApplication.UserTokenCache); Func <DeviceCodeResult, Task> deviceCodeReadyCallback = async dcr => await Console.Out.WriteLineAsync(dcr.Message); DeviceCodeProvider authProvider = new DeviceCodeProvider(_PublicClientApplication, _Options.Scope, deviceCodeReadyCallback); _GraphClient = new GraphServiceClient(authProvider); } return(_GraphClient); }
public Auth(string Authority, AppPlatform platform, string clientId, string[] scopes, object parentActivity) { this.appPlatform = platform; this.clientId = clientId; this.parentActivity = parentActivity; this.scopes = scopes; string userDir = MyDocumentsRoot() + @"\"; this.RedirectUri = $@"msal{this.clientId}://auth"; this.pca = PublicClientApplicationBuilder.Create(this.clientId) .WithB2CAuthority(Authority) .WithRedirectUri(RedirectUri) .Build(); Debug.WriteLine($@"Creating auth context with: B2C authority: {Authority} Client id: {this.clientId} Redirect uri: {RedirectUri}"); if (this.scopes is null) { System.Diagnostics.Debug.WriteLine("** Scopes are NULL **"); } else { foreach (var s in scopes) { System.Diagnostics.Debug.WriteLine(s); } } switch (platform) { case AppPlatform.DesktopClient: TokenCacheHelper.CacheFilePath = userDir + "msalcache.bin3"; TokenCacheHelper.EnableSerialization(this.pca.UserTokenCache); break; default: break; } }
public static string GetAccessToken(string[] scopes) { // create new public client application var appPublic = PublicClientApplicationBuilder.Create(applicationId) .WithAuthority(tenantCommonAuthority) .WithRedirectUri(redirectUri) .Build(); // connect application to token cache TokenCacheHelper.EnableSerialization(appPublic.UserTokenCache); AuthenticationResult authResult; try { // try to acquire token from token cache var user = appPublic.GetAccountsAsync().Result.FirstOrDefault(); authResult = appPublic.AcquireTokenSilent(scopes, user).ExecuteAsync().Result; } catch { try { // try to acquire token with non-interactive User Password Credential Flow SecureString userPasswordSecure = new System.Security.SecureString(); foreach (char c in userPassword) { userPasswordSecure.AppendChar(c); } authResult = appPublic.AcquireTokenByUsernamePassword(scopes, userName, userPasswordSecure).ExecuteAsync().Result; } catch { // try to acquire token with interactive flow authResult = appPublic.AcquireTokenInteractive(scopes).ExecuteAsync().Result; } } // return access token to caller return(authResult.AccessToken); }
/// <summary> /// Acquires the security token from the authority. /// </summary> /// <param name="context">Context to be used when requesting a security token.</param> /// <param name="debugAction">The action to write debug statements.</param> /// <returns>The result from the authentication request.</returns> public AuthenticationToken Authenticate(PartnerContext context, Action <string> debugAction) { AuthenticationResult authResult; System.Security.Claims.Claim claim; DateTimeOffset expiration; JwtSecurityToken token; JwtSecurityTokenHandler tokenHandler; PartnerEnvironment environment; environment = PartnerEnvironment.PublicEnvironments[context.Environment]; if (context.Account.Type == AccountType.AccessToken) { tokenHandler = new JwtSecurityTokenHandler(); token = tokenHandler.ReadJwtToken(context.Account.Properties[AzureAccountPropertyType.AccessToken]); claim = token.Claims.SingleOrDefault(c => c.Type.Equals("oid", StringComparison.InvariantCultureIgnoreCase)); context.Account.Properties[AzureAccountPropertyType.UserIdentifier] = claim?.Value; claim = token.Claims.SingleOrDefault(c => c.Type.Equals("tid", StringComparison.InvariantCultureIgnoreCase)); context.Account.Properties[AzureAccountPropertyType.Tenant] = claim?.Value; claim = token.Claims.SingleOrDefault(c => c.Type.Equals("exp", StringComparison.InvariantCultureIgnoreCase)); expiration = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(claim.Value, CultureInfo.InvariantCulture)); claim = token.Claims.SingleOrDefault(c => c.Type.Equals("unique_name", StringComparison.InvariantCultureIgnoreCase)); context.AuthenticationType = claim == null ? AuthenticationTypes.AppOnly : AuthenticationTypes.AppPlusUser; debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateAccessTokenTrace, expiration.ToString(CultureInfo.CurrentCulture), context.Account.Properties[AzureAccountPropertyType.Tenant], context.Account.Properties[AzureAccountPropertyType.UserIdentifier], claim?.Value)); return(new AuthenticationToken( context.Account.Properties[AzureAccountPropertyType.AccessToken], expiration)); } else if (context.Account.Type == AccountType.ServicePrincipal) { debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateServicePrincipalTrace, environment.ActiveDirectoryAuthority, context.Account.Id, environment.AzureAdGraphEndpoint, context.Account.Properties[AzureAccountPropertyType.Tenant])); IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(context.ApplicationId) .WithClientSecret(context.Account.Properties[AzureAccountPropertyType.ServicePrincipalSecret]) .WithTenantId(context.Account.Properties[AzureAccountPropertyType.Tenant]) .Build(); authResult = app.AcquireTokenForClient(new string[] { $"{environment.AzureAdGraphEndpoint}/.default" }) .ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); context.AuthenticationType = AuthenticationTypes.AppOnly; } else if (!context.Account.Properties.ContainsKey(AzureAccountPropertyType.UserIdentifier)) { #if NETSTANDARD debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateDeviceCodeTrace, context.ApplicationId, environment.PartnerCenterEndpoint)); IPublicClientApplication app = PublicClientApplicationBuilder.Create(context.ApplicationId) .WithTenantId(context.Account.Properties[AzureAccountPropertyType.Tenant]) .Build(); authResult = app.AcquireTokenWithDeviceCode(new[] { $"{environment.PartnerCenterEndpoint}/user_impersonation" }, deviceCodeResult => { Console.WriteLine(deviceCodeResult?.Message); return(Task.CompletedTask); }).ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); #else debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateAuthorizationCodeTrace, context.ApplicationId, environment.ActiveDirectoryAuthority, AuthenticationConstants.RedirectUriValue, environment.PartnerCenterEndpoint)); IPublicClientApplication app = PublicClientApplicationBuilder.Create(context.ApplicationId) .WithTenantId(context.Account.Properties[AzureAccountPropertyType.Tenant]) .Build(); TokenCacheHelper.EnableSerialization(app.UserTokenCache); authResult = app.AcquireTokenInteractive(new[] { $"{environment.PartnerCenterEndpoint}/user_impersonation" }) .WithPrompt(Prompt.ForceLogin) .ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); #endif context.Account.Id = authResult.Account.Username; context.Account.Properties[AzureAccountPropertyType.Tenant] = authResult.TenantId; context.Account.Properties[AzureAccountPropertyType.UserIdentifier] = authResult.Account.HomeAccountId.ObjectId; context.AuthenticationType = AuthenticationTypes.AppPlusUser; } else { debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateSilentTrace, context.ApplicationId, environment.ActiveDirectoryAuthority, environment.PartnerCenterEndpoint, context.Account.Id)); IPublicClientApplication app = PublicClientApplicationBuilder.Create(context.ApplicationId) .WithTenantId(context.Account.Properties[AzureAccountPropertyType.Tenant]) .Build(); TokenCacheHelper.EnableSerialization(app.UserTokenCache); IEnumerable <IAccount> accounts = app.GetAccountsAsync().ConfigureAwait(false).GetAwaiter().GetResult(); authResult = app.AcquireTokenSilent(new[] { $"{environment.PartnerCenterEndpoint}/user_impersonation" }, accounts.FirstOrDefault()) .ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); context.Account.Id = authResult.Account.Username; context.Account.Properties[AzureAccountPropertyType.Tenant] = authResult.TenantId; context.Account.Properties[AzureAccountPropertyType.UserIdentifier] = authResult.Account.HomeAccountId.ObjectId; context.AuthenticationType = AuthenticationTypes.AppPlusUser; } return(new AuthenticationToken(authResult.AccessToken, authResult.ExpiresOn)); }