예제 #1
0
        public static async Task <string> GetAccessToken(
            AadAppSettings settings,
            KeyVaultSettings vaultSettings = null,
            IKeyVaultClient kvClient       = null)
        {
            if (!string.IsNullOrEmpty(settings.ClientCertName))
            {
                if (kvClient == null)
                {
                    throw new ArgumentNullException(nameof(kvClient));
                }

                if (vaultSettings == null)
                {
                    throw new ArgumentNullException(nameof(vaultSettings));
                }
            }

            IConfidentialClientApplication app;

            if (!string.IsNullOrEmpty(settings.ClientCertName) && vaultSettings != null)
            {
                var cert = await kvClient.GetCertificateAsync(vaultSettings.VaultUrl, settings.ClientCertName);

                var pfx = new X509Certificate2(cert.Cer);
                app = ConfidentialClientApplicationBuilder.Create(settings.ClientId)
                      .WithCertificate(pfx)
                      .WithAuthority(settings.Authority)
                      .Build();
            }
            else
            {
                throw new ArgumentException("Either client secret or cert must be specified", nameof(settings));
            }

            try
            {
                var result = await app.AcquireTokenForClient(settings.Scopes).ExecuteAsync();

                return(result.AccessToken);
            }
            catch (MsalServiceException ex) 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
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Scope provided is not supported");
                Console.ResetColor();
            }

            return(null);
        }
예제 #2
0
        public static IServiceCollection AddAadAuth(this IServiceCollection services,
                                                    IConfiguration configuration)
        {
            var aadAppSettings = new AadAppSettings();

            configuration.Bind("aad", aadAppSettings);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => configuration.Bind("AzureAd", options));

            services.Configure <OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority = options.Authority + "/v2.0/";         // Microsoft identity platform
                options.TokenValidationParameters.ValidateIssuer = false; // accept several tenants (here simplified)
            });

//            services.AddProtectWebApiWithMicrosoftIdentityPlatformV2(Configuration)
//                .AddProtectedApiCallsWebApis(Configuration, new string[] { "user.read", "offline_access" })
//                .AddInMemoryTokenCaches();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddMvc(options =>
            {
                var policyBuilder = new AuthorizationPolicyBuilder();
                if (aadAppSettings.TokenType != AuthTokenType.None)
                {
                    policyBuilder.RequireAuthenticatedUser();
                }
                var policy = policyBuilder.Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            return(services);
        }