public static void InitAzureOauth(this IServiceCollection services, IConfiguration configuration) { AzureADOptions azOptions = new AzureADOptions(); configuration.Bind("AzureAd", azOptions); // Add JWT Authentication services.AddAuthentication(sharedoptions => { sharedoptions.DefaultScheme = JWT_SCHEME; }) .AddJwtBearer(options => { options.Authority = azOptions.Instance + azOptions.TenantId; options.Audience = azOptions.ClientId; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidAudiences = new string[] { $"api://{azOptions.ClientId}", azOptions.ClientId }, ValidIssuers = new string[] { $"https://sts.windows.net/{azOptions.TenantId}/", $"https://login.microsoftonline.com/${azOptions.TenantId}/v2.0" } }; }); // Add cookie based authentication services.AddAuthentication(COOKIE_SCHEME) .AddAzureAD(options => { options.TenantId = azOptions.TenantId; options.ClientId = azOptions.ClientId; options.Domain = azOptions.Domain; options.Instance = azOptions.Instance; options.CallbackPath = azOptions.CallbackPath; }); // Add Policies services.AddAuthorization(options => { // Default policy allows JWT and Cookie Auth options.DefaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .AddAuthenticationSchemes(JWT_SCHEME, COOKIE_SCHEME) .Build(); // Create a policy based on a claim to identify Service Principal accounts options.AddPolicy(SP_POLICY, policy => { // Indicates how the client was authenticated. // For a public client, the value is "0". // If client ID and client secret are used, the value is "1". // If a client certificate was used for authentication, the value is "2". policy.RequireClaim("appidacr", new[] { "1", "2" }); }); // Fallback to require an authenticated user options.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { AzureADOptions azureAdOptions = Configuration.GetSection(AzureAdConfigSection).Get <AzureADOptions>(); services.AddSingleton <AzureADOptions>(azureAdOptions); services.Configure <CookiePolicyOptions>(options => { options.MinimumSameSitePolicy = SameSiteMode.None; }); //services.AddHttpContextAccessor(); services.AddAuthentication() // allow Bearer tokens for non-interactive applications .AddAzureADBearer(options => Configuration.Bind(AzureAdConfigSection, options)) // web applications .AddAzureAD(options => Configuration.Bind(AzureAdConfigSection, options)); //configure bearer options services.Configure <JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, (configureOptions) => { configureOptions.Authority += "/v2.0"; }); //configure OIDC options services.Configure <OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, (configureOptions) => { configureOptions.Authority += "/v2.0"; configureOptions.ResponseType = "code"; }); //add authz policies to distinguish between application types services.AddAuthorization(options => { options.AddPolicy("api", policy => { policy.AuthenticationSchemes.Add(AzureADDefaults.JwtBearerAuthenticationScheme); policy.RequireAuthenticatedUser(); }); options.AddPolicy("web", policy => { policy.AuthenticationSchemes.Add(AzureADDefaults.OpenIdScheme); policy.RequireAuthenticatedUser(); }); }); //required to ensure consistency across multiple nodes services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Configuration["DataProtectionFileLocation"])); services.AddMvc(options => options.EnableEndpointRouting = false) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.ForwardLimit = 2; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); }); }
private static void RegisterAuthenticationServicesWithCertificate( IServiceCollection services, IConfiguration configuration, AuthenticationOptions authenticationOptions, AzureADOptions azureADOptions) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi( options => { options.Authority = $"{azureADOptions.Instance}{azureADOptions.TenantId}/v2.0"; options.SaveToken = true; options.TokenValidationParameters.ValidAudiences = AuthenticationServiceCollectionExtensions.GetValidAudiences(authenticationOptions); options.TokenValidationParameters.AudienceValidator = AuthenticationServiceCollectionExtensions.AudienceValidator; options.TokenValidationParameters.ValidIssuers = AuthenticationServiceCollectionExtensions.GetValidIssuers(authenticationOptions); }, microsoftIdentityOptions => { configuration.Bind("AzureAd", microsoftIdentityOptions); microsoftIdentityOptions.ClientCertificates = new CertificateDescription[] { CertificateDescription.FromKeyVault(configuration.GetValue <string>("KeyVault:Url"), configuration.GetValue <string>("GraphAppCertName")), }; }) .EnableTokenAcquisitionToCallDownstreamApi( confidentialClientApplicationOptions => { configuration.Bind("AzureAd", confidentialClientApplicationOptions); }) .AddInMemoryTokenCaches(); }
public KeyVaultAdminService(IOptionsSnapshot <AzureADOptions> azureAdOptions, IOptionsSnapshot <AdminConfig> adminConfig, IOptionsSnapshot <ResourceIds> resources, IGraphHttpService graphHttpService, IApplicationConfiguration applicationConfiguration, IUser user, IHttpContextAccessor contextAccessor) { userId = user.ObjectId; tenantId = Guid.Parse(user.TenantId); this.azureAdOptions = azureAdOptions.Get(AzureADDefaults.AuthenticationScheme); clientId = Guid.Parse(this.azureAdOptions.ClientId); adalContext = new AuthenticationContext($"{this.azureAdOptions.Instance}{this.azureAdOptions.TenantId}", new ADALSessionCache(userId, contextAccessor)); resourceGroup = adminConfig.Value.ResourceGroup; kvManagmentClient = new KeyVaultManagementClient(new AutoRestCredential <KeyVaultManagementClient>(GetAppToken)) { SubscriptionId = adminConfig.Value.SubscriptionId, BaseUri = new Uri(adminConfig.Value.ArmInstance) }; kvClient = new KeyVaultClient(new AutoRestCredential <KeyVaultClient>(GetAppTokenForKv)); this.adminConfig = adminConfig.Value; this.graphHttpService = graphHttpService; this.applicationConfiguration = applicationConfiguration; this.resources = resources.Value; }
public void AzureADConfig(AzureADOptions opts) { opts.Instance = Config.Get("AAD_Instance"); opts.Domain = Config.Get("AAD_Domain").ToLower(); opts.TenantId = Config.Get("AAD_TenantId"); opts.ClientId = Config.Get("AAD_ClientId"); opts.CallbackPath = Config.Get("AAD_CallbackPath"); bool ok = opts.Instance.HasValue() && opts.Domain.HasValue() && opts.TenantId.HasValue(); ok = ok && opts.ClientId.HasValue() && opts.CallbackPath.HasValue(); if (!ok) { Log.Me.DebugOn = true; } Log.Me.Debug("----------------------------------------------------------------------------------------------"); Log.Me.Debug("Azure Active Directory (aka authentication) Configuration:"); Log.Me.Debug(""); Log.Me.Debug("AAD_Instance : " + (opts.Instance ?? "")); Log.Me.Debug("AAD_Domain : " + (opts.Domain ?? "")); Log.Me.Debug("AAD_TenantId : " + (opts.TenantId ?? "")); Log.Me.Debug("AAD_ClientId : " + (opts.ClientId ?? "")); Log.Me.Debug("AAD_CallbackPath: " + (opts.CallbackPath ?? "")); if (!ok) { Log.Me.Fatal("Missing AzureAD Configuration. Check debug (above) to see what is wrong."); System.Environment.Exit(8); } }
/// <summary> /// Extension method to register the authentication services. /// </summary> /// <param name="services">IServiceCollection instance.</param> /// <param name="configuration">IConfiguration instance.</param> public static void AddLearnNowAuthentication(this IServiceCollection services, IConfiguration configuration) { configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); // This works specifically for single tenant application. AuthenticationServiceCollectionExtensions.ValidateAuthenticationConfigurationSettings(configuration); services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { var botOptions = new BotSettings(); var azureADOptions = new AzureADOptions(); configuration.Bind("Bot", botOptions); configuration.Bind("AzureAd", azureADOptions); options.Authority = $"{azureADOptions.Instance}/{botOptions.TenantId}/v2.0"; options.TokenValidationParameters = new TokenValidationParameters { ValidAudiences = AuthenticationServiceCollectionExtensions.GetValidAudiences(configuration), ValidIssuers = AuthenticationServiceCollectionExtensions.GetValidIssuers(configuration), AudienceValidator = AuthenticationServiceCollectionExtensions.AudienceValidator, }; }); RegisterAuthorizationPolicy(services); }
public ApplicationConfiguration(IOptionsMonitor <AzureADOptions> azureAdOptions, IOptions <ResourceIds> resourceIds, IOptions <AdminConfig> adminConfig, ILogger <ApplicationConfiguration> logger) { this.azureAdOptions = azureAdOptions.Get(AzureADDefaults.AuthenticationScheme); this.resourceIds = resourceIds; this.adminConfig = adminConfig; this.logger = logger; }
// This method works specifically for single tenant application. private static void RegisterAuthenticationServices( IServiceCollection services, IConfiguration configuration, AuthenticationOptions authenticationOptions) { AuthenticationServiceCollectionExtensions.ValidateAuthenticationOptions(authenticationOptions); services.AddProtectedWebApi(configuration) .AddProtectedWebApiCallsProtectedWebApi(configuration) .AddInMemoryTokenCaches(); services.Configure <JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options => { var azureADOptions = new AzureADOptions { Instance = authenticationOptions.AzureAdInstance, TenantId = authenticationOptions.AzureAdTenantId, ClientId = authenticationOptions.AzureAdClientId, }; options.Authority = $"{azureADOptions.Instance}{azureADOptions.TenantId}/v2.0"; options.SaveToken = true; options.TokenValidationParameters.ValidAudiences = AuthenticationServiceCollectionExtensions.GetValidAudiences(authenticationOptions); options.TokenValidationParameters.AudienceValidator = AuthenticationServiceCollectionExtensions.AudienceValidator; options.TokenValidationParameters.ValidIssuers = AuthenticationServiceCollectionExtensions.GetValidIssuers(authenticationOptions); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => Configuration.Bind("AzureAd", options)); var appSettings = new AzureADOptions(); Configuration.Bind("AzureAd", appSettings); var application = ConfidentialClientApplicationBuilder.Create(appSettings.ClientId) .WithAuthority(appSettings.Instance + appSettings.TenantId + "/v2.0/") .WithRedirectUri("https://localhost:5001" + appSettings.CallbackPath) .WithClientSecret(appSettings.ClientSecret) .Build(); services.AddSingleton(application); services.Configure <OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => { // configure authority to use v2 endpoint options.Authority = options.Authority + "/v2.0/"; // asking Azure AD for id_token (to establish identity) and // authorization code (to get access/refresh tokens for calling services) options.ResponseType = OpenIdConnectResponseType.CodeIdToken; // add the permission scopes you want the application to use options.Scope.Add("offline_access"); Constants.ProductCatalogAPI.SCOPES.ForEach(s => options.Scope.Add(s)); options.TokenValidationParameters.NameClaimType = "preferred_username"; // wire up event to do second part of code authorization flow (exchanging authorization code for token) var handler = options.Events.OnAuthorizationCodeReceived; options.Events.OnAuthorizationCodeReceived = async context => { // handle the auth code returned post signin context.HandleCodeRedemption(); if (!context.HttpContext.User.Claims.Any()) { (context.HttpContext.User.Identity as ClaimsIdentity).AddClaims(context.Principal.Claims); } // get token var token = await application.AcquireTokenByAuthorizationCode(options.Scope, context.ProtocolMessage.Code).ExecuteAsync(); context.HandleCodeRedemption(null, token.IdToken); await handler(context).ConfigureAwait(false); }; }); services.AddControllersWithViews(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); services.AddRazorPages(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddHttpContextAccessor(); services.AddSingleton <IGraph, GraphHelper>(); services.AddHttpClient("AzureWebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services.AddHttpClient("GraphWebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services .AddSingleton(observer) .AddSingleton <IGraphLogger>(logger) .AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { var azureAdOptions = new AzureADOptions(); Configuration.Bind("AzureAd", azureAdOptions); options.Authority = $"{azureAdOptions.Instance}{azureAdOptions.TenantId}/v2.0"; options.TokenValidationParameters = new TokenValidationParameters { ValidAudiences = AuthenticationHelper.GetValidAudiences(Configuration), ValidIssuers = AuthenticationHelper.GetValidIssuers(Configuration), AudienceValidator = AuthenticationHelper.AudienceValidator }; }); services .AddBot(options => Configuration.Bind("Bot", options)) .AddMvc(); IdentityModelEventSource.ShowPII = true; services.AddHostedService <SchedulerHelper>(); services.AddHostedService <ParticipantsScheduler>(); }
// This method works specifically for single tenant application. private static void RegisterAuthenticationServices( IServiceCollection services, IConfiguration configuration) { AuthenticationServiceCollectionExtensions.ValidateAuthenticationConfigurationSettings(configuration); services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { var azureADOptions = new AzureADOptions(); configuration.Bind("AzureAd", azureADOptions); options.Authority = $"{azureADOptions.Instance}{azureADOptions.TenantId}/v2.0"; options.TokenValidationParameters = new TokenValidationParameters { ValidAudiences = AuthenticationServiceCollectionExtensions.GetValidAudiences(configuration), ValidIssuers = AuthenticationServiceCollectionExtensions.GetValidIssuers(configuration), AudienceValidator = AuthenticationServiceCollectionExtensions.AudienceValidator, }; options.Events = new JwtBearerEvents { OnTokenValidated = async context => { var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService <TokenAcquisitionHelper>(); context.Success(); // Adds the token to the cache, and also handles the incremental consent and claim challenges var jwtToken = AuthenticationHeaderValue.Parse(context.Request.Headers["Authorization"].ToString()).Parameter; await tokenAcquisition.AddTokenToCacheFromJwtAsync(configuration[AuthenticationServiceCollectionExtensions.GraphScopeConfigurationSettingsKey], jwtToken); await Task.FromResult(0); }, }; }); }
public AccountController(IOptions <AppSettings> appSettingsAccessor, IConfiguration configuration) { appSettings = appSettingsAccessor.Value; azureAdOptions = new AzureADOptions(); configuration.Bind("AzureAd", azureAdOptions); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">IServiceCollection instance</param> public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore); services.Configure <TeamsConfiguration>(this.Configuration.GetSection("TeamsConfiguration")); services.AddApplicationInsightsTelemetry(); services.AddSingleton <ISharePoint, SharePointHelper>(); services.AddSingleton <IGraph, GraphHelper>(); services.AddSingleton <ITableStorage, TableStorageHelper>(); services.AddHttpClient("TableStorageWebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services.AddHttpClient("GraphWebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services.AddHttpClient("SharePointWebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { var azureADOptions = new AzureADOptions(); Configuration.Bind("AzureAd", azureADOptions); options.Authority = $"{azureADOptions.Instance}{azureADOptions.TenantId}/v2.0"; options.TokenValidationParameters = new TokenValidationParameters { ValidAudiences = AuthenticationHelper.GetValidAudiences(Configuration), ValidIssuers = AuthenticationHelper.GetValidIssuers(Configuration), AudienceValidator = AuthenticationHelper.AudienceValidator }; }); }
public CertificateRequestController( OpcVaultApiOptions opcVaultOptions, AzureADOptions azureADOptions, ITokenCacheService tokenCacheService) : base(opcVaultOptions, azureADOptions, tokenCacheService) { }
/// <summary> /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to /// configure the confidential client application and a token cache provider. /// This constructor is called by ASP.NET Core dependency injection /// </summary> /// <param name="options">Options to configure the application</param> public TokenAcquisition(ITokenCacheProvider tokenCacheProvider, IConfiguration configuration) { azureAdOptions = new AzureADOptions(); configuration.Bind("AzureAD", azureAdOptions); _applicationOptions = new ConfidentialClientApplicationOptions(); configuration.Bind("AzureAD", _applicationOptions); this.tokenCacheProvider = tokenCacheProvider; }
public Startup(IConfiguration configuration) { Configuration = configuration; OpcVaultOptions = new OpcVaultApiOptions(); Configuration.Bind("OpcVault", OpcVaultOptions); AzureADOptions = new AzureADOptions(); Configuration.Bind("AzureAD", AzureADOptions); }
/// <summary> /// Gets the COLID AzureAd Options from AppSettings. /// </summary> /// <exception cref="ArgumentNullException">If the options are not set.</exception> /// <param name="configuration">key/value application configuration properties</param> /// <returns>configuration for azure ad</returns> private static AzureADOptions ParseAzureADOptions(IConfiguration configuration) { Guard.ArgumentNotNull(configuration.GetSection("AzureAd"), "Configuration:AzureAd"); var azureADOptions = new AzureADOptions(); configuration.Bind("AzureAd", azureADOptions); return(azureADOptions); }
public CertificateGroupController( OpcVaultApiOptions opcVaultOptions, AzureADOptions azureADOptions, ITokenCacheService tokenCacheService) { this._opcVaultOptions = opcVaultOptions; this._azureADOptions = azureADOptions; this._tokenCacheService = tokenCacheService; }
public DownloadController( OpcVaultApiOptions opcVaultOptions, AzureADOptions azureADOptions, ITokenCacheService tokenCacheService) { _opcVaultOptions = opcVaultOptions; _azureADOptions = azureADOptions; _tokenCacheService = tokenCacheService; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.IsEssential = true; options.IdleTimeout = TimeSpan.FromMinutes(60);//You can set Time }); services.AddControllers().AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => false; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMemoryCache(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddMvc().AddSessionStateTempDataProvider(); // Create a global hashset for our Roster and notes information services.AddSingleton <ConcurrentDictionary <string, Token> >(); services.AddSingleton <ConcurrentDictionary <string, bool> >(); services.AddHttpClient().AddControllers().AddNewtonsoftJson(); services.AddRazorPages(); services.AddHttpClient("WebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services.AddHttpContextAccessor(); services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { var azureAdOptions = new AzureADOptions(); Configuration.Bind("AzureAd", azureAdOptions); options.Authority = $"{azureAdOptions.Instance}{azureAdOptions.TenantId}/v2.0"; options.TokenValidationParameters = new TokenValidationParameters { ValidAudiences = AuthHelper.GetValidAudiences(Configuration), ValidIssuers = AuthHelper.GetValidIssuers(Configuration), AudienceValidator = AuthHelper.AudienceValidator }; }); // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.) services.AddSingleton <IStorage, MemoryStorage>(); // Create the Conversation state. (Used by the Dialog system itself.) services.AddSingleton <ConversationState>(); // Dialog Manager handles initiating the Dialog Stack, saving state, etc. services.AddSingleton <DialogManager>(); // Create the Bot Framework Authentication to be used with the Bot Adapter. services.AddSingleton <BotFrameworkAuthentication, ConfigurationBotFrameworkAuthentication>(); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">Service collection with input</param> public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.AddCors(options => { options.AddPolicy("AllowAll", builder => builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod()); }); services.Configure <TeamsConfiguration>(Configuration.GetSection("TeamsConfiguration")); services.AddApplicationInsightsTelemetry(); services.AddSingleton <ISharePoint, SharePointHelper>(); services.AddSingleton <IGraph, GraphHelper>(); services.AddSingleton <ITableStorage, TableStorageHelper>(); services.AddHttpClient("TableStorageWebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services.AddHttpClient("GraphWebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services.AddHttpClient("SharePointWebClient", client => client.Timeout = TimeSpan.FromSeconds(600)); services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { AzureADOptions azureAdOptions = new AzureADOptions(); Configuration.Bind("AzureAd", azureAdOptions); options.Authority = $"{azureAdOptions.Instance}{azureAdOptions.TenantId}/v2.0"; options.TokenValidationParameters = new TokenValidationParameters { ValidAudiences = AuthenticationHelper.GetValidAudiences(Configuration), ValidIssuers = AuthenticationHelper.GetValidIssuers(Configuration), AudienceValidator = AuthenticationHelper.AudienceValidator }; }); services.AddControllers() .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddVersioning(); services.AddTransient <IConfigureOptions <SwaggerGenOptions>, ConfigureSwaggerOptions>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v3", new OpenApiInfo { Title = "My API", Version = "v3" }); c.AddSecurityDefinition( "Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); }); }
public GraphHttpService(IOptionsSnapshot <AzureADOptions> azureAdOptions, IOptionsSnapshot <AdminConfig> adminConfig, IOptionsSnapshot <ResourceIds> resources, IUser user, IHttpContextAccessor contextAccessor) { this.azureAdOptions = azureAdOptions.Get(AzureADDefaults.AuthenticationScheme); this.adminConfig = adminConfig.Value; graphResourceId = resources.Value.GraphId; var userId = user.ObjectId; adalContext = new AuthenticationContext($"{this.azureAdOptions.Instance}{this.azureAdOptions.TenantId}", new ADALSessionCache(userId, contextAccessor)); }
public OpcVaultLoginCredentials( OpcVaultApiOptions opcVaultOptions, AzureADOptions azureADOptions, ITokenCacheService tokenCacheService, ClaimsPrincipal claimsPrincipal) { this.opcVaultOptions = opcVaultOptions; this.azureADOptions = azureADOptions; this.tokenCacheService = tokenCacheService; this.claimsPrincipal = claimsPrincipal; }
/// <summary> /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to /// configure the confidential client application and a token cache provider. /// This constructor is called by ASP.NET Core dependency injection /// </summary> /// <param name="configuration"></param> /// <param name="tokenCacheProvider">The App token cache provider</param> /// <param name="userTokenCacheProvider">The User token cache provider</param> public TokenAcquisition( IMsalTokenCacheProvider tokenCacheProvider, IHttpContextAccessor httpContextAccessor, IOptions <AzureADOptions> azureAdOptions, IOptions <ConfidentialClientApplicationOptions> applicationOptions) { _httpContextAccessor = httpContextAccessor; _azureAdOptions = azureAdOptions.Value; _applicationOptions = applicationOptions.Value; _tokenCacheProvider = tokenCacheProvider; }
/// <summary> /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to /// configure the confidential client application and a token cache provider. /// This constructor is called by ASP.NET Core dependency injection /// </summary> /// <param name="appTokenCacheProvider">The App token cache provider</param> /// <param name="userTokenCacheProvider">The User token cache provider</param> /// <param name="configuration"></param> public TokenAcquisition(IConfiguration configuration, IMSALAppTokenCacheProvider appTokenCacheProvider, IMSALUserTokenCacheProvider userTokenCacheProvider) { azureAdOptions = new AzureADOptions(); configuration.Bind("AzureAD", azureAdOptions); _applicationOptions = new ConfidentialClientApplicationOptions(); configuration.Bind("AzureAD", _applicationOptions); this.AppTokenCacheProvider = appTokenCacheProvider; this.UserTokenCacheProvider = userTokenCacheProvider; }
public KeyVaultService(IOptionsSnapshot <ResourceIds> settings, IOptionsSnapshot <AzureADOptions> aadOptions, ILogger <KeyVaultService> logger) { Task <string> Authenticate(string authority, string resource, string scope) { return(Task.FromResult(AccessToken)); } client = new KeyVaultClient(new AutoRestCredential <KeyVaultClient>(Authenticate)); this.settings = settings; this.aadOptions = aadOptions.Get(AzureADDefaults.AuthenticationScheme); }
private static async Task <string> getAdTokenAsync(IConfiguration configuration, string azureAdSectionName = null) { azureAdSectionName = azureAdSectionName ?? AzureADDefaults.AuthenticationScheme; var adSection = configuration.GetSection(azureAdSectionName) ?? configuration.GetSection("AzureAD") ?? configuration.GetSection("AzureAd"); var adOptions = new AzureADOptions(); adSection.Bind(adOptions); var clientId = adSection["ClientId"]; if (string.IsNullOrWhiteSpace(clientId)) { throw new Exception($"require configuration for AzureAD.ClientId"); } var clientSecret = adSection["ClientSecret"]; if (string.IsNullOrWhiteSpace(clientSecret)) { throw new Exception($"require configuration for AzureAD.ClientSecret"); } //var instance = adSection["Instance"]; //if (string.IsNullOrWhiteSpace(instance)) { throw new Exception($"require configuration for AzureAD.Instance"); } string[] scopes = new string[] { "https://graph.microsoft.com/.default" }; var credential = new ClientCredential(secret: clientSecret); var authority = adSection["Instance"] ?? "https://graph.windows.net/"; var authContext = new ConfidentialClientApplication( clientId: clientId, authority: authority, redirectUri: "http://daemon", clientCredential: credential, userTokenCache: null, appTokenCache: new TokenCache() ); try { var authResult = await authContext.AcquireTokenForClientAsync(scopes); return(authResult.AccessToken); } catch (MsalServiceException ex) { // Case when ex.Message contains: // AADSTS70011 Invalid scope. The scope has to be of the form "https://resourceUrl/.default" // Mitigation: change the scope to be as expected //logger.LogError($"getAdTokenAsync: {ex.Message}"); throw; } }
private void OptionsFor(OpenIdConnectOptions options, string policy) { var aadOptions = new AzureADOptions(); Configuration.Bind("AzureAD", aadOptions); options.ClientId = aadOptions.ClientId; var aadTenant = aadOptions.Domain.Split('.')[0]; options.MetadataAddress = $"https://{aadTenant}.b2clogin.com/{aadOptions.TenantId}/b2c_1a_{policy}/v2.0/.well-known/openid-configuration"; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { NameClaimType = "name" }; options.CallbackPath = new PathString($"/signin-{policy}"); // otherwise getting 'correlation error' options.SignedOutCallbackPath = new PathString($"/signout-{policy}"); options.SignedOutRedirectUri = "/"; options.ResponseType = OpenIdConnectResponseType.CodeIdToken; //TODO: Improve, Concat could not be used foreach (var s in RESTService.Scopes) { options.Scope.Add(s); } options.Events.OnRedirectToIdentityProvider = async(ctx) => { if (ctx.Properties.Parameters.ContainsKey("tenant")) { var tenantName = (string)ctx.Properties.Parameters["tenant"]; ctx.ProtocolMessage.Parameters.Add("tenant", tenantName); } await Task.FromResult(0); }; options.Events.OnAuthorizationCodeReceived = async(ctx) => { ctx.HandleCodeRedemption(); // The cache will need the claims from the ID token. // If they are not yet in the HttpContext.User's claims, so adding them here. if (!ctx.HttpContext.User.Claims.Any()) { (ctx.HttpContext.User.Identity as ClaimsIdentity).AddClaims(ctx.Principal.Claims); } var ts = ctx.HttpContext.RequestServices.GetRequiredService <Extensions.TokenService>(); var auth = ts.AuthApp; var tokens = await auth.AcquireTokenByAuthorizationCode( RESTService.Scopes, ctx.ProtocolMessage.Code).ExecuteAsync().ConfigureAwait(false); ctx.HandleCodeRedemption(null, tokens.IdToken); }; }
public MageSignService(IOptionsMonitor <AzureADOptions> aadOptions, IHostingEnvironment hostingEnvironment, IKeyVaultService keyVaultService, IServiceProvider serviceProvider, ILogger <MageSignService> logger, ITelemetryLogger telemetryLogger) { this.aadOptions = aadOptions.Get(AzureADDefaults.AuthenticationScheme); this.keyVaultService = keyVaultService; this.logger = logger; this.telemetryLogger = telemetryLogger; magetoolPath = Path.Combine(hostingEnvironment.ContentRootPath, "tools\\SDK\\mage.exe"); signToolName = nameof(MageSignService); // Need to delay this as it'd create a dependency loop if directly in the ctor signToolAggregate = new Lazy <ISigningToolAggregate>(() => serviceProvider.GetService <ISigningToolAggregate>()); }
/// <summary> /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to /// configure the confidential client application and a token cache provider. /// This constructor is called by ASP.NET Core dependency injection /// </summary> /// <param name="appTokenCacheProvider">The App token cache provider</param> /// <param name="userTokenCacheProvider">The User token cache provider</param> /// <param name="configuration"></param> public TokenAcquisition(IConfiguration configuration, IMSALAppTokenCacheProvider appTokenCacheProvider, IMSALUserTokenCacheProvider userTokenCacheProvider) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } azureAdOptions = new AzureADOptions(); configuration.Bind("AzureAD", azureAdOptions); _applicationOptions = new ConfidentialClientApplicationOptions(); configuration.Bind("AzureAD", _applicationOptions); this.AppTokenCacheProvider = appTokenCacheProvider; this.UserTokenCacheProvider = userTokenCacheProvider; }