public AzureClient(int portalId, AuthMode mode)
            : base(portalId, mode, "AzureB2C")
        {
            Settings = new AzureConfig("AzureB2C", portalId);

            TokenMethod = HttpMethod.POST;

            if (!string.IsNullOrEmpty(Settings.TenantName) && !string.IsNullOrEmpty(Settings.TenantId))
            {
                TokenEndpoint         = new Uri(string.Format(Utils.GetAppSetting("AzureADB2C.TokenEndpointPattern", TokenEndpointPattern), Settings.TenantName, Settings.TenantId));
                LogoutEndpoint        = new Uri(string.Format(Utils.GetAppSetting("AzureADB2C.LogoutEndpointPattern", LogoutEndpointPattern), Settings.TenantName, Settings.TenantId, Settings.SignUpPolicy, UrlEncode(HttpContext.Current.Request.Url.ToString())));
                AuthorizationEndpoint = new Uri(string.Format(Utils.GetAppSetting("AzureADB2C.AuthorizationEndpointPattern", AuthorizationEndpointPattern), Settings.TenantName, Settings.TenantId));
                MeGraphEndpoint       = new Uri(string.Format(Utils.GetAppSetting("AzureADB2C.GraphEndpointPattern", GraphEndpointPattern), Settings.TenantId));
            }

            if (string.IsNullOrEmpty(Settings.APIResource) && string.IsNullOrEmpty(Settings.Scopes))
            {
                Scope       = Settings.APIKey;
                APIResource = Settings.APIKey;
            }
            else
            {
                Scope = string.Join(" ", Settings.Scopes
                                    .Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                                    .Select(x => $"{Settings.APIResource}{x.Trim()}"));
                APIResource = Settings.APIResource;
            }
            APIKey          = Settings.APIKey;
            AuthTokenName   = "AzureB2CUserToken";
            OAuthVersion    = "2.0";
            OAuthHeaderCode = "Basic";
            LoadTokenCookie(string.Empty);
            JwtIdToken = null;
            Policy     = PolicyEnum.SignUpPolicy;
        }
예제 #2
0
        private static UserInfo GetOrCreateCachedUserInfo(JwtSecurityToken jwt, PortalSettings portalSettings, System.Security.Claims.Claim userClaim)
        {
            var usernamePrefixEnabled = bool.Parse(AzureConfig.GetSetting(AzureConfig.ServiceName, "UsernamePrefixEnabled", portalSettings.PortalId, "true"));
            var usernameToFind        = usernamePrefixEnabled ? $"azureb2c-{userClaim.Value}" : userClaim.Value;
            var userInfo = UserController.GetUserByName(portalSettings.PortalId, usernameToFind);
            var tokenKey = ComputeSha256Hash(jwt.RawData);
            var cache    = DotNetNuke.Services.Cache.CachingProvider.Instance();

            if (string.IsNullOrEmpty((string)cache.GetItem($"SyncB2CToken|{tokenKey}")))
            {
                var azureClient = new AzureClient(portalSettings.PortalId, AuthMode.Login)
                {
                    JwtIdToken = jwt
                };
                azureClient.SetAuthTokenInternal(jwt.RawData);
                azureClient.SetAutoMatchExistingUsers(true);
                var userData = azureClient.GetCurrentUserInternal(jwt);
                if (userInfo == null)
                {
                    // If user doesn't exist, create the user
                    userInfo                     = userData.ToUserInfo(usernamePrefixEnabled);
                    userInfo.PortalID            = portalSettings.PortalId;
                    userInfo.Membership.Password = UserController.GeneratePassword();
                    var result = UserController.CreateUser(ref userInfo);
                }

                azureClient.AuthenticateUser(userData, portalSettings, HttpContext.Current.Request["REMOTE_ADDR"], azureClient.AddCustomProperties, azureClient.OnUserAuthenticated);
                azureClient.UpdateUserProfile(jwt, false, false);
                cache.Insert($"SyncB2CToken|{tokenKey}", "OK", null, jwt.ValidTo, TimeSpan.Zero);
            }

            return(userInfo);
        }
예제 #3
0
        private UserInfo TryGetUser(JwtSecurityToken jwt)
        {
            var portalSettings = PortalController.Instance.GetCurrentPortalSettings();
            var azureB2cConfig = new AzureConfig("AzureB2C", portalSettings.PortalId);

            if (portalSettings == null)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Unable to retrieve portal settings");
                }
                return(null);
            }
            if (!azureB2cConfig.Enabled || !azureB2cConfig.JwtAuthEnabled)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug($"Azure B2C JWT auth is not enabled for portal {portalSettings.PortalId}");
                }
                return(null);
            }

            var userClaim = jwt.Claims.FirstOrDefault(x => x.Type == "sub");

            if (userClaim == null)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Can't find 'sub' claim on token");
                }
            }
            var userInfo = UserController.GetUserByName(portalSettings.PortalId, $"azureb2c-{userClaim.Value}");

            if (userInfo == null)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Invalid user");
                }
                return(null);
            }

            var status = UserController.ValidateUser(userInfo, portalSettings.PortalId, false);
            var valid  =
                status == UserValidStatus.VALID ||
                status == UserValidStatus.UPDATEPROFILE ||
                status == UserValidStatus.UPDATEPASSWORD;

            if (!valid && Logger.IsDebugEnabled)
            {
                Logger.Debug("Inactive user status: " + status);
                return(null);
            }

            return(userInfo);
        }
예제 #4
0
 internal static OpenIdConnectConfiguration GetConfig(int portalId, AzureConfig azureB2cConfig)
 {
     if (!Config.ContainsKey(portalId))
     {
         var tokenConfigurationUrl = $"https://{azureB2cConfig.TenantName}.b2clogin.com/{azureB2cConfig.TenantId}/.well-known/openid-configuration?p={azureB2cConfig.SignUpPolicy}";
         var _configManager        = new ConfigurationManager <OpenIdConnectConfiguration>(tokenConfigurationUrl, new OpenIdConnectConfigurationRetriever());
         var _config = _configManager.GetConfigurationAsync().Result;
         Config.Add(portalId, _config);
     }
     return(Config[portalId]);
 }
        public new static AzureConfig GetConfig(string service, int portalId)
        {
            string key    = GetCacheKey(service, portalId);
            var    config = (AzureConfig)DataCache.GetCache(key);

            if (config == null)
            {
                config = new AzureConfig(service, portalId);
                DataCache.SetCache(key, config);
            }
            return(config);
        }
예제 #6
0
 internal static OpenIdConnectConfiguration GetConfig(int portalId, AzureConfig azureB2cConfig)
 {
     if (!Config.ContainsKey(portalId))
     {
         // TODO Set the ROPC policy name in a configuration setting
         var ropcPolicyName        = "B2C_1_ROPC";
         var tokenConfigurationUrl = $"https://{azureB2cConfig.TenantName}.b2clogin.com/{azureB2cConfig.TenantId}/.well-known/openid-configuration?p={ropcPolicyName}";
         var _configManager        = new ConfigurationManager <OpenIdConnectConfiguration>(tokenConfigurationUrl, new OpenIdConnectConfigurationRetriever());
         var _config = _configManager.GetConfigurationAsync().Result;
         Config.Add(portalId, _config);
     }
     return(Config[portalId]);
 }
예제 #7
0
        /// <summary>
        /// This is to check if the current OpenIdConnectConfiguration is still valid. If the value of the ROPC
        /// policy has been changed by the user, this configuration is not valid anymore
        /// </summary>
        public bool IsValid(AzureConfig azureB2cConfig, string defaultRopcPolicy)
        {
            if (RopcPolicyName.ToLower() == azureB2cConfig.RopcPolicy.ToLower())
            {
                return(true);
            }

            if (RopcPolicyName.ToLower() == defaultRopcPolicy.ToLower() && string.IsNullOrEmpty(azureB2cConfig.RopcPolicy))
            {
                return(true);
            }

            return(false);
        }
        private static string UpdateB2CApplicationId(AzureConfig config)
        {
            var b2cApplicationId = "";

            if (!string.IsNullOrEmpty(config.AADApplicationId) &&
                !string.IsNullOrEmpty(config.AADApplicationKey) &&
                !string.IsNullOrEmpty(config.TenantId))
            {
                var graphClient  = new Graph.GraphClient(config.AADApplicationId, config.AADApplicationKey, config.TenantId);
                var extensionApp = graphClient.GetB2CExtensionApplication();
                b2cApplicationId = extensionApp?.AppId;
                if (string.IsNullOrEmpty(b2cApplicationId))
                {
                    throw new ConfigurationErrorsException("Can't find B2C Application on current tenant. Ensure the application 'b2c-extensions-app' exists.");
                }

                /*var extensions = graphClient.GetExtensions(extensionApp?.ObjectId);
                 * var portalIdExtension = extensions.Values.FirstOrDefault(x => x.Name.ToLowerInvariant() == $"extension_{b2cApplicationId.Replace("-", "")}_portalid");
                 * //if (portalIdExtension != null)
                 * //    graphClient.UnregisterExtension(extensionApp?.ObjectId, portalIdExtension.ObjectId);
                 * if (portalIdExtension == null)
                 * {
                 *  portalIdExtension = new Graph.Models.Extension()
                 *  {
                 *      ODataType = "Microsoft.DirectoryServices.ExtensionProperty",
                 *      ObjectType = "ExtensionProperty",
                 *      Name = "portalId",
                 *      DataType = "Integer",
                 *      TargetObjects = new string[] { "User" }
                 *  };
                 *  graphClient.RegisterExtension(extensionApp?.ObjectId, portalIdExtension);
                 *
                 *  var users = graphClient.GetAllUsers("").Values;
                 *  var extensionName = $"extension_{b2cApplicationId.Replace("-", "")}_portalId";
                 *  foreach (var user in users)
                 *  {
                 *      if (!user.AdditionalData.ContainsKey(extensionName))
                 *      {
                 *          user.AdditionalData.Clear();
                 *          user.AdditionalData.Add(extensionName, config.PortalID);
                 *          graphClient.UpdateUser(user);
                 *      }
                 *  }
                 * }    */
            }
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_B2CApplicationId", b2cApplicationId);
            return(b2cApplicationId);
        }
        public static void UpdateConfig(AzureConfig config)
        {
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_ApiKey", config.APIKey, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_ApiSecret", config.APISecret, true, Null.NullString, false); // BUG: DNN 9.3.2 not storing IsSecure column on DB (see UpdatePortalSetting stored procedure) https://github.com/dnnsoftware/Dnn.Platform/issues/2874
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_TenantName", config.TenantName, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_TenantId", config.TenantId, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_AutoRedirect", config.AutoRedirect.ToString(), true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_Enabled", config.Enabled.ToString(), true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_SignUpPolicy", config.SignUpPolicy, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_ProfilePolicy", config.ProfilePolicy, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_PasswordResetPolicy", config.PasswordResetPolicy, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_AADApplicationId", config.AADApplicationId, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_AADApplicationKey", config.AADApplicationKey, true, Null.NullString, false);  // BUG: DNN 9.3.2 not storing IsSecure column on DB (see UpdatePortalSetting stored procedure) https://github.com/dnnsoftware/Dnn.Platform/issues/2874
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_JwtAudiences", config.JwtAudiences, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_RoleSyncEnabled", config.RoleSyncEnabled.ToString(), true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_ProfileSyncEnabled", config.ProfileSyncEnabled.ToString(), true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_JwtAuthEnabled", config.JwtAuthEnabled.ToString(), true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_APIResource", config.APIResource, true, Null.NullString, false);
            PortalController.UpdatePortalSetting(config.PortalID, config.Service + "_Scopes", config.Scopes, true, Null.NullString, false);

            UpdateConfig((OAuthConfigBase)config);
        }
예제 #10
0
        internal static B2CControllerConfiguration GetConfig(int portalId, AzureConfig azureB2cConfig)
        {
            const string DefaultRopcPolicy = "B2C_1_ROPC";

            var currentConfig = Config.ContainsKey(portalId) ? Config[portalId] : null;

            if (currentConfig != null && !currentConfig.IsValid(azureB2cConfig, DefaultRopcPolicy))
            {
                Config.Remove(portalId);
                currentConfig = null;
            }

            if (currentConfig == null)
            {
                var ropcPolicyName        = !string.IsNullOrEmpty(azureB2cConfig.RopcPolicy) ? azureB2cConfig.RopcPolicy : DefaultRopcPolicy;
                var tokenConfigurationUrl = $"https://{azureB2cConfig.TenantName}.b2clogin.com/{azureB2cConfig.TenantId}/.well-known/openid-configuration?p={ropcPolicyName}";
                var _configManager        = new ConfigurationManager <OpenIdConnectConfiguration>(tokenConfigurationUrl, new OpenIdConnectConfigurationRetriever());
                var _config = _configManager.GetConfigurationAsync().Result;
                Config.Add(portalId, new B2CControllerConfiguration(ropcPolicyName, _config));
            }

            return(Config[portalId]);
        }
예제 #11
0
        public static void UpdateConfig(AzureConfig config)
        {
            HostController.Instance.Update(config.Service + "_UseGlobalSettings", config.UseGlobalSettings.ToString(),
                                           true);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_ApiKey", config.APIKey);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_ApiSecret", config.APISecret);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_RedirectUri", config.RedirectUri);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_OnErrorUri", config.OnErrorUri);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_TenantName", config.TenantName);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_TenantId", config.TenantId);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_AutoRedirect", config.AutoRedirect.ToString());
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_Enabled", config.Enabled.ToString());
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_SignUpPolicy", config.SignUpPolicy);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_ProfilePolicy", config.ProfilePolicy);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_PasswordResetPolicy", config.PasswordResetPolicy);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_AADApplicationId", config.AADApplicationId);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_AADApplicationKey", config.AADApplicationKey);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_JwtAudiences", config.JwtAudiences);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_RoleSyncEnabled", config.RoleSyncEnabled.ToString());
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_ProfileSyncEnabled", config.ProfileSyncEnabled.ToString());
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_JwtAuthEnabled", config.JwtAuthEnabled.ToString());
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_APIResource", config.APIResource);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_Scopes", config.Scopes);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_UsernamePrefixEnabled", config.UsernamePrefixEnabled.ToString());
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_GroupNamePrefixEnabled", config.GroupNamePrefixEnabled.ToString());
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_RopcPolicy", config.RopcPolicy);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_ImpersonatePolicy", config.ImpersonatePolicy);
            UpdateScopedSetting(config.UseGlobalSettings, config.PortalID, config.Service + "_AutoAuthorize", config.AutoAuthorize.ToString());

            config.B2cApplicationId = UpdateB2CApplicationId(config);

            UpdateConfig((OAuthConfigBase)config);

            // Clear config after update
            DataCache.RemoveCache(GetCacheKey(config.Service, config.PortalID));
        }
예제 #12
0
        private static JwtSecurityToken GetAndValidateJwt(string rawToken, bool checkExpiry)
        {
            JwtSecurityToken jwt;

            try
            {
                jwt = new JwtSecurityToken(rawToken);
            }
            catch (Exception ex)
            {
                Logger.Error("Unable to construct JWT object from authorization value. " + ex.Message);
                return(null);
            }

            if (checkExpiry)
            {
                var now = DateTime.UtcNow;
                if (now < jwt.ValidFrom || now > jwt.ValidTo)
                {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug("Token is expired");
                    }
                    return(null);
                }
            }

            var portalSettings = PortalController.Instance.GetCurrentPortalSettings();
            var azureB2cConfig = new AzureConfig("AzureB2C", portalSettings.PortalId);

            if (portalSettings == null)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Unable to retrieve portal settings");
                }
                return(null);
            }
            if (!azureB2cConfig.Enabled || !azureB2cConfig.JwtAuthEnabled)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug($"Azure B2C JWT auth is not enabled for portal {portalSettings.PortalId}");
                }
                return(null);
            }

            var _config        = GetConfig(portalSettings.PortalId, azureB2cConfig);
            var validAudiences = azureB2cConfig.JwtAudiences.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();

            if (validAudiences.Length == 0)
            {
                validAudiences = new[] { azureB2cConfig.APIKey };
            }

            try
            {
                // Validate token.
                var _tokenValidator      = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    // App Id URI and AppId of this service application are both valid audiences.
                    ValidAudiences = validAudiences,
                    // Support Azure AD V1 and V2 endpoints.
                    ValidIssuers      = new[] { _config.Issuer, $"{_config.Issuer}v2.0/" },
                    IssuerSigningKeys = _config.SigningKeys
                };

                var claimsPrincipal = _tokenValidator.ValidateToken(rawToken, validationParameters, out SecurityToken _);
            }
            catch (Exception ex)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug($"Error validating token: {ex}");
                }
                return(null);
            }

            return(jwt);
        }
예제 #13
0
        public override void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action <NameValueCollection> addCustomProperties, Action <UserAuthenticatedEventArgs> onAuthenticated)
        {
            var portalSettings = settings;

            if (IsCurrentUserAuthorized() && JwtIdToken != null)
            {
                // Check if portalId profile mapping exists
                var portalUserMapping = UserMappingsRepository.Instance.GetUserMapping("PortalId", GetCalculatedPortalId());
                if (!string.IsNullOrEmpty(portalUserMapping?.B2cClaimName))
                {
                    var claimName = portalUserMapping?.GetB2cCustomClaimName();
                    // Get PortalId from claim
                    var portalIdClaim = JwtIdToken.Claims.FirstOrDefault(x => x.Type.ToLowerInvariant() == claimName.ToLowerInvariant())?.Value;
                    if (string.IsNullOrEmpty(portalIdClaim))
                    {
                        throw new SecurityTokenException("The user has no portalId claim and portalId profile mapping is setup. The B2C user can't login to any portal until the portalId attribute has been setup for the user. Ensure that the PortalId claim has been setup and included on the policy being used.");
                    }
                    if (int.TryParse(portalIdClaim, out int portalId) && portalId != portalSettings.PortalId)
                    {
                        // Redirect to the user portal
                        var request = HttpContext.Current.Request;
                        if (!string.IsNullOrEmpty(request.Headers["Authorization"]) && request.Headers["Authorization"].StartsWith("Bearer"))
                        {
                            throw new SecurityTokenException($"The user portalId claim ({portalId}) is different from current portalId ({portalSettings.PortalId}). Portal redirection flow is not supported on native apps. Please call the API from the corresponding portal URL");
                        }
                        var state = new State(request["state"]);
                        HttpContext.Current.Response.Redirect(Utils.GetLoginUrl(portalId, state.Culture, request));
                        return;
                    }
                }
            }

            var userIdClaim = Utils.GetUserIdClaim(GetCalculatedPortalId());
            var userClaim   = JwtIdToken.Claims.FirstOrDefault(x => x.Type == userIdClaim);

            if (userClaim == null)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Error($"Can't find '{userIdClaim}' claim on token");
                }
                throw new MissingFieldException($"Can't find '{userIdClaim}' claim on token, needed to identify the user");
            }

            var usernamePrefixEnabled = bool.Parse(AzureConfig.GetSetting(AzureConfig.ServiceName, "UsernamePrefixEnabled", portalSettings.PortalId, "true"));
            var usernameToFind        = usernamePrefixEnabled ? $"azureb2c-{userClaim.Value}" : userClaim.Value;
            var userInfo = UserController.GetUserByName(portalSettings.PortalId, usernameToFind);

            // If user doesn't exist on current portal, AuthenticateUser() will create it.
            // Otherwise, AuthenticateUser will perform a Response.Redirect, so we have to sinchronize the roles before that, to avoid the ThreadAbortException caused by the Response.Redirect
            if (userInfo == null)
            {
                base.AuthenticateUser(user, portalSettings, IPAddress, addCustomProperties, onAuthenticated);
                if (IsCurrentUserAuthorized())
                {
                    userInfo = UserController.GetUserByName(portalSettings.PortalId, usernameToFind);
                    if (userInfo == null)
                    {
                        throw new SecurityTokenException($"The logged in user {usernameToFind} does not belong to PortalId {portalSettings.PortalId}");
                    }
                    UpdateUserAndRoles(userInfo);
                    MarkUserAsB2c(userInfo);
                }
            }
            else
            {
                if (IsCurrentUserAuthorized())
                {
                    UpdateUserAndRoles(userInfo);
                    MarkUserAsB2c(userInfo);
                }
                base.AuthenticateUser(user, portalSettings, IPAddress, addCustomProperties, onAuthenticated);
            }
        }
예제 #14
0
        private UserInfo TryGetUser(JwtSecurityToken jwt)
        {
            try
            {
                var portalSettings = PortalController.Instance.GetCurrentPortalSettings();
                var azureB2cConfig = new AzureConfig(AzureConfig.ServiceName, portalSettings.PortalId);
                if (portalSettings == null)
                {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug("Unable to retrieve portal settings");
                    }
                    return(null);
                }
                if (!azureB2cConfig.Enabled || !azureB2cConfig.JwtAuthEnabled)
                {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug($"Azure B2C JWT auth is not enabled for portal {portalSettings.PortalId}");
                    }
                    return(null);
                }

                var userIdClaim = Utils.GetUserIdClaim(azureB2cConfig.UseGlobalSettings ? -1 : portalSettings.PortalId);
                var userClaim   = jwt.Claims.FirstOrDefault(x => x.Type == userIdClaim);
                if (userClaim == null)
                {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug($"Can't find '{userIdClaim}' claim on token");
                    }
                }

                var userInfo = GetOrCreateCachedUserInfo(jwt, portalSettings, userClaim);
                if (userInfo == null)
                {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug("Invalid user");
                    }
                    return(null);
                }

                var status = UserController.ValidateUser(userInfo, portalSettings.PortalId, false);
                var valid  =
                    status == UserValidStatus.VALID ||
                    status == UserValidStatus.UPDATEPROFILE ||
                    status == UserValidStatus.UPDATEPASSWORD;

                if (!valid && Logger.IsDebugEnabled)
                {
                    Logger.Debug("Inactive user status: " + status);
                    return(null);
                }

                return(userInfo);
            }
            catch (Exception ex)
            {
                Logger.Error("Error while login in: " + ex.Message);
            }
            return(null);
        }