Ejemplo n.º 1
0
 public AzureAdClient(IOptionsMonitor <AzureAdGraphApiOptions> azureAdGraphApiOptionsMonitor, IOptionsMonitor <AzureAdB2COptions> azureAdB2COptionsMonitor)
 {
     _azureAdGraphApiOptions = azureAdGraphApiOptionsMonitor?.CurrentValue ??
                               throw new ArgumentNullException(nameof(azureAdGraphApiOptionsMonitor));
     _azureAdB2COptions = azureAdB2COptionsMonitor?.CurrentValue ??
                          throw new ArgumentNullException(nameof(azureAdB2COptionsMonitor));
 }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            var b2cConfig = Configuration.GetSection("AzureAdB2C");
            AzureAdB2COptions azureAdB2COptions = new AzureAdB2COptions();

            Configuration.Bind("AzureAdB2C", azureAdB2COptions);
            services.Configure <AzureAdB2COptions>(b2cConfig);


            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = Constants.SignInSignUpPolicy;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.LoginPath          = new PathString("/Auth/Login");
                options.LogoutPath         = new PathString("/Auth/Logout");
                options.ReturnUrlParameter = "returnUrl";
            })
            .AddOpenIdConnect(Constants.SignInSignUpPolicy, GetOpenIdConnectOptions(azureAdB2COptions, Constants.SignInSignUpPolicy))
            .AddOpenIdConnect(Constants.EditProfilePolicy, GetOpenIdConnectOptions(azureAdB2COptions, Constants.EditProfilePolicy));
            services.AddDistributedMemoryCache();
            services.AddControllersWithViews();
        }
Ejemplo n.º 3
0
        public APIController(IOptions <AzureAdB2COptions> azureAdB2COptions)
        {
            AzureAdB2COptions = azureAdB2COptions.Value;

            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
Ejemplo n.º 4
0
        public Startup(IConfiguration configuration, AzureAdB2COptions azureAdB2COptions)
        {
            Configuration = configuration;

            _azureAdB2COptions = azureAdB2COptions;

            Configuration.Bind("Authentication:AzureAdB2C", _azureAdB2COptions);
        }
 public HelloApiController(IConfiguration configuration,
                           IOptions <AzureAdB2COptions> options,
                           IDistributedCache cache)
 {
     _configuration  = configuration;
     _baseApiAddress = _configuration["ApiEndpoint"];
     _options        = options.Value;
     _cache          = cache;
 }
        public AzureAdB2CSecuredApiConnector(IOptions <AzureAdB2COptions> options, IHttpContextAccessor httpContextAccessor)
        {
            _azureAdB2COptions = options.Value;
            ValidateOptions(options);
            _requiredScopes = _azureAdB2COptions.ApiScopes.Split(' ').ToList();
            var signedInUserId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userTokenCache = new MsalSessionCache(signedInUserId, httpContextAccessor.HttpContext).GetMsalCacheInstance();

            _confidentialClientApplication = new ConfidentialClientApplication(_azureAdB2COptions.ClientId, _azureAdB2COptions.Authority, _azureAdB2COptions.RedirectUri, new ClientCredential(_azureAdB2COptions.ClientSecret), userTokenCache, null);
        }
Ejemplo n.º 7
0
 public APIController(IOptions <AzureAdB2COptions> azureAdB2COptions,
                      IUserService <ApplicationUser> uService,
                      IOfferService <JobOffer> oService,
                      IOptions <MyConfig> options,
                      HR_ProjectContext context)
 {
     AzureAdB2COptions = azureAdB2COptions.Value;
     userService       = uService;
     _context          = context;
     this.options      = options;
 }
        private async Task <AuthenticationResult> AcquireTokenSilentAsync(AzureAdB2COptions azureAdB2COptions)
        {
            // Retrieve the token with the specified scopes
            var scope          = azureAdB2COptions.ApiScopes.Split(' ');
            var signedInUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userTokenCache = new MsalSessionCache(signedInUserId, HttpContext).GetMsalCacheInstance();
            var cca            = new ConfidentialClientApplication(
                azureAdB2COptions.ApplicationId,
                azureAdB2COptions.Authority,
                azureAdB2COptions.RedirectUri,
                new ClientCredential(azureAdB2COptions.ClientSecret), userTokenCache, null);

            var result = await cca.AcquireTokenSilentAsync(scope, cca.Users.FirstOrDefault(), azureAdB2COptions.Authority, false);

            return(result);
        }
Ejemplo n.º 9
0
        public static async Task <string> GetAccessToken(HttpContext context, AzureAdB2COptions options)
        {
            var    scope          = options.ApiScopes.Split(' ');
            string signedInUserID = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            var cca = ConfidentialClientApplicationBuilder.Create(options.ClientId)
                      .WithRedirectUri(options.RedirectUri)
                      .WithClientSecret(options.ClientSecret)
                      .WithB2CAuthority(options.Authority)
                      .Build();

            new MSALStaticCache(signedInUserID, context).EnablePersistence(cca.UserTokenCache);

            var accounts = await cca.GetAccountsAsync();

            var result = await cca.AcquireTokenSilent(scope, accounts.FirstOrDefault())
                         .ExecuteAsync();

            return(result.AccessToken);
        }
Ejemplo n.º 10
0
        private Action <OpenIdConnectOptions> GetOpenIdConnectOptions(AzureAdB2COptions azureAdB2COptions, string policyName) =>
        (options) =>
        {
            options.Authority             = azureAdB2COptions.GetB2CAuthority(policyName);
            options.ClientId              = azureAdB2COptions.ClientId;
            options.ClientSecret          = azureAdB2COptions.ClientSecret;
            options.ResponseType          = OidcConstants.ResponseTypes.CodeIdToken;
            options.SignInScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
            options.CallbackPath          = $"/signin/{policyName}";
            options.SignedOutCallbackPath = $"/signout/{policyName}";
            options.SaveTokens            = true;
            options.UseTokenLifetime      = true;
            foreach (string scope in azureAdB2COptions.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries))
            {
                options.Scope.Add(scope);
            }
            options.TokenValidationParameters.NameClaimType = "name";
            options.TokenValidationParameters.RoleClaimType = "role";

            options.Events.OnAuthorizationCodeReceived += OnAuthorizationCodeReceived;
            options.Events.OnRemoteFailure             += OnRemoteFailureHandler;
        };
        public DomainResolver(HttpContext httpContext, AzureAdOptions azureAdOptions, AzureAdB2COptions azureAdB2COptions)
        {
            _azureAdOptions    = azureAdOptions;
            _azureAdB2COptions = azureAdB2COptions;

            _httpContext = httpContext;
            userObjectID = (httpContext.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;

            if (httpContext.User.FindFirst("emails") != null)
            {
                signedInUseremail = httpContext.User.FindFirst("emails").Value;
            }
            else
            {
                //"preferred_username"
                signedInUseremail = httpContext.User.FindFirst("preferred_username") != null?httpContext.User.FindFirst("preferred_username").Value : null;
            }
            if (!signedInUseremail.ToLower().EndsWith("domain.com"))
            {
                isB2cUser = true;
            }
        }
 public HomeController(IOptions <AzureAdB2COptions> options)
 {
     _azureOptions = options.Value;
 }
Ejemplo n.º 13
0
 public SignOutModel(IOptions <AzureAdB2COptions> b2cOptions)
 {
     AzureAdB2COptions = b2cOptions.Value;
 }
Ejemplo n.º 14
0
 public AccountController(
     IOptions <AzureAdB2COptions> azureAdB2COptions)
 {
     _azureAdB2COptions = azureAdB2COptions.Value;
 }
Ejemplo n.º 15
0
        public void SetOptionsForOpenIdConnectPolicy(string policy, OpenIdConnectOptions options, AzureAdB2COptions azureAdB2COptions)
        {
            options.ClientId                  = azureAdB2COptions.ApplicationId; // Azure AD B2C application ID."### ADD APPLICATION ID HERE ###";
            options.Authority                 = azureAdB2COptions.Authority;
            options.UseTokenLifetime          = true;
            options.TokenValidationParameters = new TokenValidationParameters {
                NameClaimType = "name"
            };

            options.Events = new OpenIdConnectEvents
            {
                OnRedirectToIdentityProvider = context => OnRedirectToIdentityProvider(context, azureAdB2COptions.DefaultPolicy, azureAdB2COptions.ApiUrl, azureAdB2COptions.ApiScopes),
                OnRemoteFailure = OnRemoteFailure,
                //OnAuthorizationCodeReceived = OnAuthorizationCodeReceived
                OnAuthorizationCodeReceived = async context => await OnAuthorizationCodeReceived(context,
                                                                                                 azureAdB2COptions.ApplicationId,
                                                                                                 azureAdB2COptions.Authority,
                                                                                                 azureAdB2COptions.ClientSecret,
                                                                                                 azureAdB2COptions.RedirectUri,
                                                                                                 azureAdB2COptions.ApiScopes)
            };

            // https://login.microsoftonline.com/bqadb2c.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_sign_up_in&client_id=50b51705-27f1-4cf3-b9a1-1ee8be89bc8c&nonce=defaultNonce&redirect_uri=msal50b51705-27f1-4cf3-b9a1-1ee8be89bc8c%3A%2F%2Fauth&scope=openid&response_type=id_token&prompt=login
            options.MetadataAddress = $"https://login.microsoftonline.com/{azureAdB2COptions.Tenant}/v2.0/.well-known/openid-configuration?p={policy}";
        }
Ejemplo n.º 16
0
 public AccountController(IOptions <AzureAdB2COptions> b2COptionsAccessor)
 {
     _b2COptions = b2COptionsAccessor.Value;
 }
 public TodoController(IOptions <AzureAdB2COptions> azureAdB2COptions, IOptions <AzureAdOptions> azureAdOptions)
 {
     _azureAdB2COptions = azureAdB2COptions.Value;
     _azureAdOptions    = azureAdOptions.Value;
 }
Ejemplo n.º 18
0
 public HomeController(IOptions <AzureAdB2COptions> azureAdB2COptions)
 {
     AzureAdB2COptions = azureAdB2COptions.Value;
 }
Ejemplo n.º 19
0
 public HomeController(IOptions <AzureAdB2COptions> azureAdB2COptions, ILogger <HomeController> logger)
 {
     _logger           = logger;
     AzureAdB2COptions = azureAdB2COptions.Value;
 }
 public ExampleController(IAzureAdSecuredApiConnector azureAdSecuredApiConnector, IOptions <AzureAdOptions> azureSettingsAccessor, IOptions <AzureAdB2COptions> azureB2CSettingsAccessor)
 {
     _azureAdSecuredApiConnector = azureAdSecuredApiConnector;
     _azureAdOptions             = azureSettingsAccessor.Value;
     _azureAdB2COptions          = azureB2CSettingsAccessor.Value;
 }
Ejemplo n.º 21
0
 public SessionController(IOptions <AzureAdB2COptions> b2cOptions)
 {
     _azureAdB2COptions = b2cOptions.Value;
 }
        public static void AddAzureAdAndB2CJwtBearerAuthentication(this IServiceCollection services, AzureAdOptions azureAdOptions, AzureAdB2COptions azureB2COptions, Assembly controllerAssembly, string policyIdentifier = "")
        {
            // Setup Authentication
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = AzureJwtSchemes.AZURE_AD_AUTHENTICATION_SCHEME;
            })
            .AddAzureB2CJwtBearer(azureB2COptions)
            .AddAzureAdJwtBearer(azureAdOptions);

            // Setup Authorization
            var customPolicyBuilder = new AuthorizationPolicyBuilder(AzureJwtSchemes.AZURE_AD_B2_C_AUTHENTICATION_SCHEME, AzureJwtSchemes.AZURE_AD_AUTHENTICATION_SCHEME);
            var defaultPolicy       = customPolicyBuilder.RequireAuthenticatedUser().Build();

            // scan custom defined policies in Authorization attribute to add as custom policies
            var customDefinedPolicies = FindAuthorizationPolicies(controllerAssembly, policyIdentifier);

            // add these custom policies to the authorization process
            services.AddAuthorization(o =>
            {
                o.DefaultPolicy = defaultPolicy;
                customDefinedPolicies.ForEach(customDefinedPolicy => o.AddPolicy(customDefinedPolicy,
                                                                                 policy =>
                {
                    policy.Requirements.Add(new AzurePolicyRequirement(customDefinedPolicy));
                    policy.AuthenticationSchemes.Add(AzureJwtSchemes.AZURE_AD_B2_C_AUTHENTICATION_SCHEME);
                    policy.AuthenticationSchemes.Add(AzureJwtSchemes.AZURE_AD_AUTHENTICATION_SCHEME);
                }));
            });
        }
        public static AuthenticationBuilder AddAzureB2CCookieAuthentication(this IServiceCollection services, AzureAdB2COptions azureAdB2CSettings, string resetPasswordUrl, bool requestAccessToken, bool loadMemberGroupsAsRoles = false)
        {
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(20);
                // no javascript calls to cookie
                options.Cookie.HttpOnly = true;
            });
            return(services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
                   .AddCookie()
                   .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.ClientId = azureAdB2CSettings.ClientId;
                // Set the authority to your Azure domain
                options.Authority = azureAdB2CSettings.Authority;

                options.UseTokenLifetime = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType = "name"
                };

                options.Events = new OpenIdConnectEvents
                {
                    OnRedirectToIdentityProvider = (context) =>
                    {
                        // pass language (adds ui_locales to query string)
                        var requestCulture = context.HttpContext.Features.Get <IRequestCultureFeature>();
                        var lang = requestCulture?.RequestCulture.Culture.TextInfo.ToTitleCase(
                            requestCulture.RequestCulture.Culture.TwoLetterISOLanguageName);
                        if (lang != null)
                        {
                            context.ProtocolMessage.UiLocales = lang;
                        }

                        // no explict policy or default policy passed - just continue
                        var defaultPolicy = azureAdB2CSettings.DefaultPolicy;
                        if (!context.Properties.Items.TryGetValue(AzureAdB2COptions.POLICY_AUTHENTICATION_PROPERTY, out var policy) || policy.Equals(defaultPolicy))
                        {
                            if (requestAccessToken)
                            {
                                context.ProtocolMessage.Scope += $" offline_access {String.Join(" ", azureAdB2CSettings.Scopes)}";
                                context.ProtocolMessage.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                            }
                        }
                        else
                        {
                            // explict policy set in context => see AuthenticationProperties.Items.Add("Policy", desired policy_name)
                            // example --> custom policy has been set to reset password
                            context.ProtocolMessage.Scope = OpenIdConnectScope.OpenIdProfile;
                            context.ProtocolMessage.ResponseType = OpenIdConnectResponseType.IdToken;
                            context.ProtocolMessage.IssuerAddress = context.ProtocolMessage.IssuerAddress.ToLower().Replace($"/{defaultPolicy.ToLower()}/", $"/{policy.ToLower()}/");
                            context.Properties.Items.Remove(AzureAdB2COptions.POLICY_AUTHENTICATION_PROPERTY);
                        }
                        return Task.CompletedTask;
                    },
                    OnRemoteFailure = (context) =>
                    {
                        context.HandleResponse();
                        // Handle the error code that Azure AD B2C throws when trying to reset a password from the login page
                        // because password reset is not supported by a "sign-up or sign-in policy"
                        if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("AADB2C90118"))
                        {
                            // If the user clicked the reset password link, redirect to the reset password route
                            context.Response.Redirect(resetPasswordUrl);
                        }
                        else if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("access_denied"))
                        {
                            context.Response.Redirect("/");
                        }
                        else
                        {
                            throw context.Failure;
                        }
                        return Task.FromResult(0);
                    },
                    OnAuthorizationCodeReceived = async(context) =>
                    {
                        // Use MSAL to swap the code for an access token
                        // Extract the code from the response notification
                        var auhtorizationCode = context.ProtocolMessage.Code;

                        string signedInUserId = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                        var userTokenCache = new MsalSessionCache(signedInUserId, context.HttpContext).GetMsalCacheInstance();
                        var clientApplication = new ConfidentialClientApplication(azureAdB2CSettings.ClientId, azureAdB2CSettings.Authority, azureAdB2CSettings.RedirectUri, new ClientCredential(azureAdB2CSettings.ClientSecret), userTokenCache, null);

                        try
                        {
                            if (requestAccessToken)
                            {
                                var result = await clientApplication.AcquireTokenByAuthorizationCodeAsync(auhtorizationCode, azureAdB2CSettings.Scopes);
                                context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                            }
                        }
                        catch (Exception e)
                        {
                            throw new Exception("AcquireTokenByAuthorizationCodeAsync failed", e);
                        }
                    },
                    // handle the logout redirection
                    OnRedirectToIdentityProviderForSignOut = (context) =>
                    {
                        var logoutUri = $"{azureAdB2CSettings.Domain}/v2/logout?client_id={azureAdB2CSettings.ClientId}";

                        var postLogoutUri = context.Properties.RedirectUri;
                        if (!string.IsNullOrEmpty(postLogoutUri))
                        {
                            if (postLogoutUri.StartsWith("/"))
                            {
                                // transform to absolute
                                var request = context.Request;
                                postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase +
                                                postLogoutUri;
                            }
                            logoutUri += $"&post_logout_redirect_uri={Uri.EscapeDataString(postLogoutUri)}";
                        }
                        // set the audience parameter to get also an access token back after login to be able to call APIs of this application
                        context.ProtocolMessage.SetParameter("audience", azureAdB2CSettings.ClientId);
                        context.Response.Redirect(logoutUri);
                        context.HandleResponse();

                        return Task.CompletedTask;
                    }
                };
                if (loadMemberGroupsAsRoles)
                {
                    //Check via Azure Graph API if user is in correct group
                    options.Events.OnTokenValidated = context =>
                    {
                        var serviceProvider = services.BuildServiceProvider();
                        // resolve GraphApiConnector
                        var graphApiConnector = serviceProvider.GetService <IGraphApiConnector>();
                        if (graphApiConnector == null)
                        {
                            throw new Exception("No implementation has been registered for IGraphApiConnector");
                        }
                        // Get membergroups for user from AzureAd
                        var signedInUserId = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                        var memberGroups = graphApiConnector.GetMemberGroupsForUser(signedInUserId).GetAwaiter()
                                           .GetResult();
                        // create roleclaim
                        var roleClaims = memberGroups.Select(x => new Claim(ClaimTypes.Role, x));
                        // Add RoleClaim to useridentity
                        ((ClaimsIdentity)context.Principal.Identity).AddClaims(roleClaims);

                        return Task.FromResult(0);
                    };
                }
            }));
Ejemplo n.º 24
0
 public HomeController(IOptions <AzureAdB2COptions> azureAdB2COptions, IMemoryCache cache)
 {
     _azureOptions = azureAdB2COptions.Value;
     _cache        = cache;
 }
Ejemplo n.º 25
0
 public AccountController(IOptions <AzureAdB2COptions> b2cOptions, IUserService userService)
 {
     _options     = b2cOptions.Value;
     _userService = userService;
 }
Ejemplo n.º 26
0
 public HomeController(IOptions <AzureAdB2COptions> azureAdB2COptions, IHttpClientFactory clientFactory)
 {
     _azureAdB2COptions = azureAdB2COptions.Value;
     _clientFactory     = clientFactory;
 }
Ejemplo n.º 27
0
 public ApiController(IOptions <AzureAdB2COptions> b2cOptions)
 {
     AzureAdB2COptions = b2cOptions.Value;
 }
Ejemplo n.º 28
0
 public Credentials(IOptions <AzureAdB2COptions> b2cOptions)
 {
     AzureAdB2COptions = b2cOptions.Value;
 }
Ejemplo n.º 29
0
 public AccountController(IOptions <AzureAdB2COptions> b2cOptions)
 {
     _options = b2cOptions.Value;
 }
 public ConfigureAzureOptions(IOptions <AzureAdB2COptions> azureOptions)
 {
     this.azureOptions = azureOptions.Value;
 }