public bool HasPermission(PermissionObject obj, Permission permissions) { if (!Claims.Any() || !Authenticated) { return(false); } var result = false; if (obj == PermissionObject.Default) { result = true; } else { if (permissions == Permission.Read && IsAdministrative) { result = true; } else if (IsAdministrative && CanEdit) { result = true; } else { if (PermissionsMap.ContainsKey(obj) && (PermissionsMap[obj] & permissions) == permissions) { result = true; } } } return(result); }
public bool CheckAuth(string policy) { if (string.IsNullOrWhiteSpace(policy)) { return(true); } _ = AuthenticationHeaderValue.TryParse(Request.Headers[HeaderNames.Authorization], out var jwt); return(new JwtSecurityToken(jwt !.Parameter).Claims.Any(x => x.Type == policy)); }
public virtual void ReplaceClaim(Claim existingClaim, Claim newClaim) { var claimExists = Claims .Any(c => c.Type == existingClaim.Type && c.Value == existingClaim.Value); if (!claimExists) { // note: nothing to update, ignore, no need to throw return; } RemoveClaim(existingClaim); AddClaim(newClaim); }
public virtual void ReplaceClaim(Claim claim, Claim newClaim) { var claimExists = Claims .Any(c => c.Type == claim.Type && c.Value == claim.Value); if (!claimExists) { return; } RemoveClaim(claim); AddClaim(newClaim); }
private string BuildComplexToken() { var res = Const.ComplexTokenMarker + Claims .Select(e => Uri.EscapeDataString(e.Key) + '=' + Uri.EscapeDataString(e.Value)) .Aggregate((a, v) => a + '&' + v); if (Claims.Any(e => e.Key != ClaimTypes.NameIdentifier)) { res += '&' + Uri.EscapeDataString(ClaimTypes.NameIdentifier) + '=' + Uri.EscapeDataString(User); } if (Claims.Any(e => e.Key != ClaimTypes.Name)) { res += '&' + Uri.EscapeDataString(ClaimTypes.Name) + '=' + Uri.EscapeDataString(User); } return(res); }
/// <summary> /// In order to ensure that the Web API only accepts tokens from tenants where it has been consented and provisioned, a token that /// has neither Roles nor Scopes claims should be rejected. To enforce that rule, add an event handler to the beginning of the /// <see cref="JwtBearerEvents.OnTokenValidated"/> handler chain that rejects tokens that don't meet the rules. /// </summary> /// <param name="events">The <see cref="JwtBearerEvents"/> object to modify.</param> /// <param name="jwtBearerScheme">The JWT bearer scheme name to be used. By default it uses "Bearer".</param> internal static void ChainOnTokenValidatedEventForClaimsValidation(JwtBearerEvents events, string jwtBearerScheme) { var tokenValidatedHandler = events.OnTokenValidated; events.OnTokenValidated = async context => { if (!context !.Principal !.Claims.Any(x => x.Type == ClaimConstants.Scope || x.Type == ClaimConstants.Scp || x.Type == ClaimConstants.Roles || x.Type == ClaimConstants.Role)) { context.Fail(string.Format(CultureInfo.InvariantCulture, IDWebErrorMessage.NeitherScopeOrRolesClaimFoundInToken, jwtBearerScheme)); } await tokenValidatedHandler(context).ConfigureAwait(false); }; }
protected override void ProcessRecord() { var existing = Scope.Claims.ToList(); foreach (var scopeClaim in Claims) { if (Claims.Any(x => String.Equals(x.Name, scopeClaim.Name, StringComparison.Ordinal) && x != scopeClaim)) { throw new ArgumentException("Claims cannot be specified more than once"); } } var updated = new List <ScopeClaim>(); if (!ReplaceExisting) { updated.AddRange(existing.Where(scopeClaim => !Claims.Any(x => String.Equals(x.Name, scopeClaim.Name, StringComparison.Ordinal)))); } updated.AddRange(Claims); Scope.Claims = updated; WriteObject(Scope); }
public virtual bool HasClaim(string claimType, string claimValue) { return(HasClaims() && Claims.Any(i => i.ClaimType.Equals(claimType, StringComparison.OrdinalIgnoreCase) && i.ClaimValue.Equals(claimValue, StringComparison.OrdinalIgnoreCase))); }
async private void accountSelected(object o) { if (o is Claim) { Claim = o as Claim; // Retrieve the Customer, Property Address, Billing Address, previous Inspection, and Lead information. Customer = Customers.Where(c => c.CustomerID == Claim.CustomerID).Single(); IsExistingCustomer = true; PropertyAddress = Addresses.Where(a => a.AddressID == Claim.PropertyID).Single(); IsExistingAddress = true; // Check if the BillingID is the same as PropertyID if (Claim.BillingID == Claim.PropertyID) { /// BillingSameAsProperty = true; BillingAddress = PropertyAddress; } else // If it's not retrieve the BillingAddress from the server { ///BillingSameAsProperty = false; BillingAddress = Addresses.Where(a => a.AddressID == Claim.BillingID).Single(); } Lead = Leads.Where(l => l.LeadID == Claim.LeadID).Single(); if (Lead.LeadTypeID == 1) { if ((ErrorMessage = await new ServiceLayer().GetKnockerResponseByID(new DTO_KnockerResponse { KnockerResponseID = (int)Lead.KnockerResponseID })) != null) { return; } else { KnockerResponse = new KnockerResponse(ServiceLayer.KnockerResponse); } } else if (Lead.LeadTypeID == 2) { if ((ErrorMessage = await new ServiceLayer().GetReferrerByID(new DTO_Referrer { ReferrerID = (int)Lead.CreditToID })) != null) { return; } else { Referrer = new Referrer(ServiceLayer.Referrer); } } Inspection = Inspections.Where(i => i.ClaimID == Claim.ClaimID).Single(); Claim.InsuranceCompanyName = InsuranceCompanies.Where(i => i.InsuranceCompanyID == Claim.InsuranceCompanyID).Single().CompanyName; } else if (o is Lead) { Lead = o as Lead; // Retrieve the Customer and Property Address Information, and Claim if there is one attached. Customer = Customers.Where(c => c.CustomerID == Lead.CustomerID).Single(); IsExistingCustomer = true; PropertyAddress = Addresses.Where(a => a.AddressID == Lead.AddressID).Single(); IsExistingAddress = true; BillingAddress = null; // Check if any Claims are connected to the Lead if (Claims.Any(c => c.LeadID == Lead.LeadID)) { Claim = Claims.Where(c => c.LeadID == Lead.LeadID).Single(); // Check if BillingID is the same as PropertyID if (Claim.BillingID == Claim.PropertyID) { ///BillingSameAsProperty = true; BillingAddress = PropertyAddress; IsExistingAddressB = true; } else // If it's not retrieve the BillingAddress from the server { ///BillingSameAsProperty = false; BillingAddress = Addresses.Where(a => a.AddressID == Claim.BillingID).Single(); } // Retrieve the Inspection attached to the Claim if ((ErrorMessage = await new ServiceLayer().GetInspectionsByClaimID(Claim.toDTO())) != null) { return; } Inspection = new Inspection(ServiceLayer.InspectionsList.Last()); } else // Instantiate the Claim object { Claim = new Claim { LeadID = Lead.LeadID }; } BillingAddress = new Address(); ///LeadIsAttached = true; } else if (o is Customer) { Customer = o as Customer; } else if (o is Address && code == 4) { PropertyAddress = o as Address; } else if (o is Address && code == 5) { BillingAddress = o as Address; } else if (o is Adjuster && code == 6) { Adjuster = o as Adjuster; } else if (o is Adjustment && code == 7) { Adjustment = o as Adjustment; } else if (o == null) { //AddLead.Execute(o); } CurrentPage = new ClaimHUDView(); //OnRequestClose(this, new EventArgs()); }
public bool HasClaim(string claim) { return(Claims.Any(c => c.Value == claim)); }
public override void Process(TagHelperContext context, TagHelperOutput output) { IUrlHelper urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext); output.TagName = "div"; output.TagMode = TagMode.StartTagAndEndTag; var labelDiv = new TagBuilder("div"); var label = new TagBuilder("label"); label.AddCssClass("claims-label"); label.InnerHtml.Append(Display); labelDiv.InnerHtml.AppendHtml(label); //Add labelDiv output.PostContent.AppendHtml(labelDiv); string type = ""; if (Display.StartsWith("Пользователи")) { type = "users"; } if (Display.StartsWith("Товары")) { type = "items"; } if (Display.StartsWith("Заказы")) { type = "orders"; } var reverseCheckboxHtml = new List <IHtmlContent>(); var actionSplit = Actions.Split(" ").Reverse(); var masterFlag = false; foreach (var action in actionSplit) { var checkboxDiv = new TagBuilder("div"); var input = new TagBuilder("input"); var checkboxLabel = new TagBuilder("label"); var capAction = char.ToUpper(action[0]) + action.Substring(1); var capType = char.ToUpper(type[0]) + type.Substring(1); input.Attributes.Add("type", "checkbox"); input.AddCssClass(type); input.AddCssClass(action); input.Attributes.Add("name", "newClaims"); input.Attributes.Add("value", capAction + capType); checkboxLabel.AddCssClass(type); checkboxLabel.AddCssClass(action); var actionLabel = ""; switch (action) { case "view": actionLabel = "Просмотр"; break; case "edit": actionLabel = "Редактирование"; break; case "create": actionLabel = "Создание"; break; case "delete": actionLabel = "Удаление"; break; } checkboxLabel.InnerHtml.Append(actionLabel); if (ViewOnly || masterFlag) { input.Attributes.Add("disabled", ""); } if (masterFlag || (Claims != null && Claims.Any(x => x.Type == capAction + capType))) { input.Attributes.Add("checked", ""); masterFlag = true; } checkboxDiv.InnerHtml.AppendHtml(input); checkboxDiv.InnerHtml.AppendHtml(checkboxLabel); //Add checkboxDiv reverseCheckboxHtml.Add(checkboxDiv); } reverseCheckboxHtml.Reverse(); foreach (var item in reverseCheckboxHtml) { output.PostContent.AppendHtml(item); } }
public CodeGenerableResult GenerateCode(string varName = null, int space = 0) { var codeResult = new CodeGenerableResult { DeletingCode = $"versionContext.DeleteData<LetPortal.Portal.Entities.Pages.Page>(\"{Id}\");" }; var stringBuilder = new StringBuilder(); varName ??= Name.Replace("-", "", System.StringComparison.OrdinalIgnoreCase) + "Page"; _ = stringBuilder.AppendLine($"var {varName} = new LetPortal.Portal.Entities.Pages.Page"); _ = stringBuilder.AppendLine($"{{"); _ = stringBuilder.AppendLine($" Id = \"{Id}\","); _ = stringBuilder.AppendLine($" Name = \"{Name}\","); _ = stringBuilder.AppendLine($" DisplayName = \"{DisplayName}\","); _ = stringBuilder.AppendLine($" AppId = \"{AppId}\","); _ = stringBuilder.AppendLine($" UrlPath = \"{UrlPath}\","); if (ShellOptions != null && ShellOptions.Any()) { _ = stringBuilder.AppendLine($" ShellOptions = new System.Collections.Generic.List<LetPortal.Portal.Entities.Pages.ShellOption>"); _ = stringBuilder.AppendLine($" {{"); foreach (var option in ShellOptions) { _ = stringBuilder.AppendLine($" new LetPortal.Portal.Entities.Pages.ShellOption"); _ = stringBuilder.AppendLine($" {{"); _ = stringBuilder.AppendLine($" Key = \"{option.Key}\","); _ = stringBuilder.AppendLine($" Value = \"{option.Value}\","); _ = stringBuilder.AppendLine($" Description = \"{option.Description}\""); _ = stringBuilder.AppendLine($" }},"); } _ = stringBuilder.AppendLine($" }},"); } if (Claims != null && Claims.Any()) { _ = stringBuilder.AppendLine($" Claims = new System.Collections.Generic.List<LetPortal.Core.Security.PortalClaim>"); _ = stringBuilder.AppendLine($" {{"); foreach (var claim in Claims) { _ = stringBuilder.AppendLine($" new LetPortal.Core.Security.PortalClaim"); _ = stringBuilder.AppendLine($" {{"); _ = stringBuilder.AppendLine($" Name = \"{claim.Name}\","); _ = stringBuilder.AppendLine($" DisplayName = \"{claim.DisplayName}\","); var claimType = "LetPortal.Core.Security.ClaimValueType." + Enum.GetName(typeof(ClaimValueType), claim.ClaimValueType); _ = stringBuilder.AppendLine($" ClaimValueType = {claimType}"); _ = stringBuilder.AppendLine($" }},"); } _ = stringBuilder.AppendLine($" }},"); } if (Builder != null) { _ = stringBuilder.AppendLine(Builder.GenerateCode().InsertingCode); } if (PageDatasources != null && PageDatasources.Any()) { _ = stringBuilder.AppendLine($" PageDatasources = new System.Collections.Generic.List<LetPortal.Portal.Entities.Pages.PageDatasource>"); _ = stringBuilder.AppendLine($" {{"); foreach (var pageDatasource in PageDatasources) { _ = stringBuilder.AppendLine($" new LetPortal.Portal.Entities.Pages.PageDatasource"); _ = stringBuilder.AppendLine($" {{"); _ = stringBuilder.AppendLine($" Id = \"{pageDatasource.Id}\","); _ = stringBuilder.AppendLine($" Name = \"{pageDatasource.Name}\","); _ = stringBuilder.AppendLine($" TriggerCondition = \"{pageDatasource.TriggerCondition}\","); _ = stringBuilder.AppendLine($" IsActive = {pageDatasource.IsActive.ToString().ToLower()},"); _ = stringBuilder.AppendLine(pageDatasource.Options.GenerateCode("Options", space = 2).InsertingCode); _ = stringBuilder.AppendLine($" }},"); } _ = stringBuilder.AppendLine($" }},"); } if (Commands != null && Commands.Any()) { _ = stringBuilder.AppendLine($" Commands = new System.Collections.Generic.List<LetPortal.Portal.Entities.Pages.PageButton>"); _ = stringBuilder.AppendLine($" {{"); foreach (var command in Commands) { _ = stringBuilder.AppendLine($" new LetPortal.Portal.Entities.Pages.PageButton"); _ = stringBuilder.AppendLine($" {{"); _ = stringBuilder.AppendLine($" Id = \"{command.Id}\","); _ = stringBuilder.AppendLine($" Name = \"{command.Name}\","); _ = stringBuilder.AppendLine($" Icon = \"{command.Icon}\","); _ = stringBuilder.AppendLine($" Color = \"{command.Color}\","); _ = stringBuilder.AppendLine($" AllowHidden = \"{command.AllowHidden}\","); _ = stringBuilder.AppendLine($" PlaceSectionId = \"{command.PlaceSectionId}\","); _ = stringBuilder.AppendLine($" IsRequiredValidation = {command.IsRequiredValidation.ToString().ToLower()},"); _ = stringBuilder.AppendLine(command.ButtonOptions.GenerateCode(space: 3).InsertingCode); _ = stringBuilder.AppendLine($" }},"); } _ = stringBuilder.AppendLine($" }},"); } _ = stringBuilder.AppendLine($"}};"); _ = stringBuilder.AppendLine($"versionContext.InsertData({varName});"); codeResult.InsertingCode = stringBuilder.ToString(); return(codeResult); }
public bool HasClaim(string claim) { return(Claims.Any(x => x.ClaimValue == "Administrator")); }
async private Task <InspectionViewModel> InitializeAsync() { // Retrieve Required Data if (Claim != null && Claim.ClaimID != 0) // If a claim was selected. { //// Retrieve the Customer, Property Address, Billing Address, previous Inspection, and Lead information. //Customer = Customers.Where(c => c.CustomerID == Claim.CustomerID).Single(); //IsExistingCustomer = true; //PropertyAddress = Addresses.Where(a => a.AddressID == Claim.PropertyID).Single(); //IsExistingAddress = true; //// Check if the BillingID is the same as PropertyID //if (Claim.BillingID == Claim.PropertyID) //{ // BillingSameAsProperty = true; // BillingAddress = PropertyAddress; //} //else // If it's not retrieve the BillingAddress from the server //{ // BillingSameAsProperty = false; // BillingAddress = Addresses.Where(a => a.AddressID == Claim.BillingID).Single(); //} // Retrieve the Inspection attached to the Claim if ((ErrorMessage = await new ServiceLayer().GetInspectionsByClaimID(Claim.toDTO())) != null) { return(this); } //// Retrieve the Lead attached to the Claim //if ((ErrorMessage = await new ServiceLayer().GetLeadByLeadID(new DTO_Lead { LeadID = Claim.LeadID })) != null) // return this; //Lead = new Lead(ServiceLayer.Lead); //LeadIsAttached = true; Inspection = new Inspection(ServiceLayer.InspectionsList.Last()); } else if (Lead != null && Lead.LeadID != 0) // (Lead != null) // If a lead was selected { // Retrieve the Customer and Property Address Information, and Claim if there is one attached. Customer = Customers.Where(c => c.CustomerID == Lead.CustomerID).Single(); PropertyAddress = Addresses.Where(a => a.AddressID == Lead.AddressID).Single(); BillingAddress = null; // Check if any Claims are connected to the Lead if (Claims.Any(c => c.LeadID == Lead.LeadID)) { Claim = Claims.Where(c => c.LeadID == Lead.LeadID).Single(); // Check if BillingID is the same as PropertyID if (Claim.BillingID == Claim.PropertyID) { BillingSameAsProperty = true; BillingAddress = PropertyAddress; } else // If it's not retrieve the BillingAddress from the server { BillingSameAsProperty = false; BillingAddress = Addresses.Where(a => a.AddressID == Claim.BillingID).Single(); } // Retrieve the Inspection attached to the Claim if ((ErrorMessage = await new ServiceLayer().GetInspectionsByClaimID(Claim.toDTO())) != null) { return(this); } Inspection = new Inspection(ServiceLayer.InspectionsList.Last()); } else // Instantiate the Claim object { Claim = new Claim { LeadID = Lead.LeadID }; } BillingAddress = new Address(); LeadIsAttached = true; } else { Claim = new Claim(); PropertyAddress = new Address(); BillingAddress = new Address(); LeadIsAttached = false; } if (Inspection == null) { Inspection = new Inspection(); } //if (BillingAddress != null && PropertyAddress.AddressID == BillingAddress.AddressID) //{ // _billingSameAsProperty = true; //} // Set up Commands _saveInspection = new RelayCommand(new Action <object>(saveInspection)); _cancelInspection = new RelayCommand(new Action <object>(cancelInspection)); return(this); }
public virtual bool HasClaims() { return(Claims != null && Claims.Any()); }
private static void AddMicrosoftIdentityWebApiImplementation( AuthenticationBuilder builder, Action <JwtBearerOptions> configureJwtBearerOptions, Action <MicrosoftIdentityOptions> configureMicrosoftIdentityOptions, string jwtBearerScheme, bool subscribeToJwtBearerMiddlewareDiagnosticsEvents) { builder.AddJwtBearer(jwtBearerScheme, configureJwtBearerOptions); builder.Services.Configure(jwtBearerScheme, configureMicrosoftIdentityOptions); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IValidateOptions <MicrosoftIdentityOptions>, MicrosoftIdentityOptionsValidation>()); builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpClient(); builder.Services.TryAddSingleton <MicrosoftIdentityIssuerValidatorFactory>(); builder.Services.AddOptions <AadIssuerValidatorOptions>(); if (subscribeToJwtBearerMiddlewareDiagnosticsEvents) { builder.Services.AddSingleton <IJwtBearerMiddlewareDiagnostics, JwtBearerMiddlewareDiagnostics>(); } // Change the authentication configuration to accommodate the Microsoft identity platform endpoint (v2.0). builder.Services.AddOptions <JwtBearerOptions>(jwtBearerScheme) .Configure <IServiceProvider, IOptionsMonitor <MicrosoftIdentityOptions> >((options, serviceProvider, microsoftIdentityOptionsMonitor) => { var microsoftIdentityOptions = microsoftIdentityOptionsMonitor.Get(jwtBearerScheme); if (string.IsNullOrWhiteSpace(options.Authority)) { options.Authority = AuthorityHelpers.BuildAuthority(microsoftIdentityOptions); } // This is a Microsoft identity platform web API options.Authority = AuthorityHelpers.EnsureAuthorityIsV2(options.Authority); if (options.TokenValidationParameters.AudienceValidator == null && options.TokenValidationParameters.ValidAudience == null && options.TokenValidationParameters.ValidAudiences == null) { RegisterValidAudience registerAudience = new RegisterValidAudience(); registerAudience.RegisterAudienceValidation( options.TokenValidationParameters, microsoftIdentityOptions); } // If the developer registered an IssuerValidator, do not overwrite it if (options.TokenValidationParameters.ValidateIssuer && options.TokenValidationParameters.IssuerValidator == null) { // Instead of using the default validation (validating against a single tenant, as we do in line of business apps), // we inject our own multi-tenant validation logic (which even accepts both v1.0 and v2.0 tokens) MicrosoftIdentityIssuerValidatorFactory microsoftIdentityIssuerValidatorFactory = serviceProvider.GetRequiredService <MicrosoftIdentityIssuerValidatorFactory>(); options.TokenValidationParameters.IssuerValidator = microsoftIdentityIssuerValidatorFactory.GetAadIssuerValidator(options.Authority).Validate; } // If you provide a token decryption certificate, it will be used to decrypt the token if (microsoftIdentityOptions.TokenDecryptionCertificates != null) { IEnumerable <X509Certificate2?> certificates = DefaultCertificateLoader.LoadAllCertificates(microsoftIdentityOptions.TokenDecryptionCertificates); IEnumerable <X509SecurityKey> keys = certificates.Select(c => new X509SecurityKey(c)); options.TokenValidationParameters.TokenDecryptionKeys = keys; } if (options.Events == null) { options.Events = new JwtBearerEvents(); } // When an access token for our own web API is validated, we add it to MSAL.NET's cache so that it can // be used from the controllers. var tokenValidatedHandler = options.Events.OnTokenValidated; options.Events.OnTokenValidated = async context => { if (!microsoftIdentityOptions.AllowWebApiToBeAuthorizedByACL && !context !.Principal !.Claims.Any(x => x.Type == ClaimConstants.Scope || x.Type == ClaimConstants.Scp || x.Type == ClaimConstants.Roles || x.Type == ClaimConstants.Role)) { throw new UnauthorizedAccessException(IDWebErrorMessage.NeitherScopeOrRolesClaimFoundInToken); } await tokenValidatedHandler(context).ConfigureAwait(false); }; if (subscribeToJwtBearerMiddlewareDiagnosticsEvents) { var diagnostics = serviceProvider.GetRequiredService <IJwtBearerMiddlewareDiagnostics>(); diagnostics.Subscribe(options.Events); } }); }
public override bool IsInRole(string role) { return(Identity is BreachIdentity bi ? bi.User.Roles.Any(x => x == role) : Claims.Any(x => x.Type == ClaimTypes.Role && x.Value == role)); }
public override bool IsInRole(string role) { return(Identity.IsAuthenticated && Claims != null && Claims.Any(c => c.Type == "role" && c.Value == role)); }
public bool HasClaim(string claim) => Claims.Any(c => c.Name.EqualsInvariantIgnoreCase(claim));