public IEnumerable <Claim> Get(ClaimStore store) { var claims = default(IList <Claim>); if (!this.Store.TryGetValue(store, out claims)) { return(Enumerable.Empty <Claim>()); } return(claims); }
public static string GetClaim(ClaimStore key, string token) { var val = GetPrincipal(token).Claims.Where(s => s.Type == key.ToString()).FirstOrDefault(); if (val == null) { return(""); } return(val.Value); }
private async Task Rollback(CancellationToken cancellationToken, params StoreTypes[] rollback) { if (rollback == null) { throw new ArgumentNullException(nameof(rollback)); } foreach (var i in rollback) { switch (i) { case StoreTypes.UserStore: await UserStore.RollbackAsync(cancellationToken); break; case StoreTypes.EmailStore: await EmailStore.RollbackAsync(cancellationToken); break; case StoreTypes.LockoutStore: await LockoutStore.RollbackAsync(cancellationToken); break; case StoreTypes.NameStore: await NameStore.RollbackAsync(cancellationToken); break; case StoreTypes.PasswordStore: await PasswordStore.RollbackAsync(cancellationToken); break; case StoreTypes.TokenStore: await TokenStore.RollbackAsync(cancellationToken); break; case StoreTypes.ClaimStore: await ClaimStore.RollbackAsync(cancellationToken); break; default: throw new ArgumentOutOfRangeException(); } } }
public async Task <AuthenticationResult> RemoveUser(TUser user, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } Handle(cancellationToken); var stores = new List <StoreTypes>(); var result = await EmailStore.DeleteUserAsync(user, cancellationToken); stores.Add(StoreTypes.EmailStore); await AssertSingle(user, result, cancellationToken, stores); result = await ClaimStore.DeleteUserAsync(user, cancellationToken); stores.Add(StoreTypes.ClaimStore); await AssertSingle(user, result, cancellationToken, stores); await LoginStore.DeleteUser(user, cancellationToken); stores.Add(StoreTypes.LoginStore); await TokenStore.RemoveUserAsync(user, cancellationToken); stores.Add(StoreTypes.TokenStore); result = await LockoutStore.DeleteUserAsync(user, cancellationToken); stores.Add(StoreTypes.NameStore); await AssertSingle(user, result, cancellationToken, stores); result = await NameStore.DeleteUserAsync(user, cancellationToken); stores.Add(StoreTypes.NameStore); await AssertSingle(user, result, cancellationToken, stores); result = await PasswordStore.DeleteUserAsync(user, cancellationToken); stores.Add(StoreTypes.PasswordStore); await AssertSingle(user, result, cancellationToken, stores); result = await UserStore.DeleteUserAsync(user, cancellationToken); stores.Add(StoreTypes.UserStore); await AssertSingle(user, result, cancellationToken, stores); return(AuthenticationResult.Success()); }
public void Dispose() { if (IsDiposed) { return; } UserStore.Dispose(); PasswordStore.Dispose(); EmailStore.Dispose(); TokenStore.Dispose(); LockoutStore.Dispose(); NameStore.Dispose(); ClaimStore.Dispose(); IsDiposed = true; }
public RoleDto() { Claims = new List <ClaimDto>(); foreach (var claimGroup in ClaimStore.ClaimGroups()) { foreach (var claim in claimGroup.Claims.OrderBy(c => c.Name)) { Claims.Add(new ClaimDto() { Group = claimGroup.Name, Type = claim.Type, Name = claim.Name, Enabled = false }); } } }
public async Task <IActionResult> Register(RegisterViewModel registerViweModel) { if (ModelState.IsValid) { var user = new AppUser { UserName = registerViweModel.UserName, Email = registerViweModel.Email, PhoneNumber = registerViweModel.phoneNumber, Gender = registerViweModel.position, MiddleName = registerViweModel.middle_name, FamilyName = registerViweModel.family_name, address = registerViweModel.addres, }; ClaimStore claimStore = new ClaimStore(registerViweModel.family_name, registerViweModel.position, registerViweModel.addres, registerViweModel.given_name, registerViweModel.middle_name); claimStore.SetClaims(); var result = _userManager.CreateAsync(user, registerViweModel.Password); if (result.Result.Succeeded) { foreach (var c in claimStore) { var res = _userManager.AddClaimAsync(user, (Claim)c); } if (_signInManager.IsSignedIn(User) && User.IsInRole("Admin")) { return(RedirectToAction("ListUsers", "Admin")); } await _signInManager.SignInAsync(user, isPersistent : false); return(RedirectToAction("Admin", "Admin")); } foreach (var er in result.Result.Errors) { ModelState.AddModelError(string.Empty, er.Description); } } return(View(registerViweModel)); }
public async Task <ActionResult <bool> > CreateRoleClaims([FromServices] RoleManager <IdentityRole> RoleManager) { string[] roleNames = { "TC", "Employee", "Finance", "Operation" }; IdentityResult roleResult; List <Claim> AllClaim = ClaimStore.GetClaims(); foreach (var roleName in roleNames) { var roleExist = await RoleManager.RoleExistsAsync(roleName); if (!roleExist) { IdentityRole identityRole = new IdentityRole(roleName); //create the roles and seed them to the database: Question 1 roleResult = await RoleManager.CreateAsync(identityRole); if (roleResult.Succeeded) { } } } var identityRoleTc = RoleManager.Roles.Where(p => p.Name == "TC").FirstOrDefault(); var AlreadyClaims = (await RoleManager.GetClaimsAsync(identityRoleTc)).Select(p => p.Type).ToList(); var toBeInserted = AllClaim.Where(p => !AlreadyClaims.Contains(p.Type) && p.Type.IndexOf("Gateway_") >= -1).ToList(); foreach (var t in toBeInserted) { var result = await RoleManager.AddClaimAsync(identityRoleTc, t); } var identityRoleEmployee = RoleManager.Roles.Where(p => p.Name == "Employee").FirstOrDefault(); var toBeInsertedEmp = AllClaim.Where(p => !AlreadyClaims.Contains(p.Type) && p.Type.IndexOf("Emp_") >= -1).ToList(); foreach (var t in toBeInsertedEmp) { var result = await RoleManager.AddClaimAsync(identityRoleEmployee, t); } return(true); }
public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, Action <AzureAdOptions> configureOptions) { builder.Services.Configure(configureOptions); builder.Services.AddSingleton <IConfigureOptions <OpenIdConnectOptions>, ConfigureAzureOptions>(); builder.AddOpenIdConnect(options => { options.Events = new OpenIdConnectEvents { OnTokenValidated = async context => { await Task.Run(() => { var claimStore = new ClaimStore(); var claims = claimStore.GetClaimsForUser(context.Principal?.FindFirstValue("name")); var identity = new ClaimsIdentity(claims); context.Principal.AddIdentity(identity); }); } }; }); return(builder); }
protected override async Task <ClaimsIdentity> GenerateClaimsAsync(User user) { var identity = await base.GenerateClaimsAsync(user); // Add the claims to the user foreach (var claim in user.Claims) { identity.AddClaim(new Claim(claim.ClaimType, claim.ClaimName)); } // If the user is an Employee if (user.Master) { identity.AddClaim(ClaimStore.MasterClaim); foreach (var claim in ClaimStore.ClaimList() .Where(claim => !identity.HasClaim(c => c.Value == claim.Value))) { identity.AddClaim(claim); } } return(identity); }
private static ResultSet ExecuteSmartTargetQuery(SmartTargetPageModel smartTargetPageModel, Localization localization) { using (new Tracer(smartTargetPageModel, localization)) { TcmUri pageUri = new TcmUri(String.Format("tcm:{0}-{1}-64", localization.LocalizationId, smartTargetPageModel.Id)); TcmUri publicationUri = new TcmUri(0, pageUri.PublicationId, 1); ClaimStore claimStore = AmbientDataContext.CurrentClaimStore; string triggers = AmbientDataHelper.GetTriggers(claimStore); QueryBuilder queryBuilder = new QueryBuilder(); queryBuilder.Parse(triggers); queryBuilder.AddCriteria(new PublicationCriteria(publicationUri)); queryBuilder.AddCriteria(new PageCriteria(pageUri)); // Adding all the page regions to the query for having only 1 query a page foreach (SmartTargetRegion region in smartTargetPageModel.Regions.OfType <SmartTargetRegion>()) { queryBuilder.AddCriteria(new RegionCriteria(region.Name)); } return(queryBuilder.Execute()); } }
public JWTServerClaimManager(ClaimStore <IdentityClaim> claimStore) : base(claimStore) { }
public async Task <AuthenticationResult <string> > CreateUserAsync(TUser user, string name, string username, string password, string email, CancellationToken cancellationToken) { // Handle any cancellation Handle(cancellationToken); // Quick validation of the parameters supplied. Validation of empty strings should be done above as well. if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (string.IsNullOrEmpty(nameof(password))) { throw new ArgumentNullException(nameof(password)); } if (string.IsNullOrEmpty(nameof(email))) { throw new ArgumentNullException(nameof(email)); } // Validates the parameters var validation = await ValidationConfiguration.EmailValidator.ValidateAsync(email, cancellationToken); if (!validation.Succeeded) { return(AuthenticationResult <string> .Invalidate(validation)); } validation = await ValidationConfiguration.UserNameValidator.ValidateAsync(username, cancellationToken); if (!validation.Succeeded) { return(AuthenticationResult <string> .Invalidate(validation)); } validation = await ValidationConfiguration.NameValidator.ValidateAsync(name, cancellationToken); if (!validation.Succeeded) { return(AuthenticationResult <string> .Invalidate(validation)); } validation = await ValidationConfiguration.PasswordValidator.ValidateAsync(password, cancellationToken); if (!validation.Succeeded) { return(AuthenticationResult <string> .Invalidate(validation)); } validation = await ValidationConfiguration.UserValidator.ValidateAsync(user, cancellationToken); if (!validation.Succeeded) { return(AuthenticationResult <string> .Invalidate(validation)); } // Create the id of the new user var id = Guid.NewGuid().ToString(); // All stores that have been modified var a = new List <StoreTypes>(); // Add user in database and retrieve the resulting user var queryResult = await UserStore.CreateUserAsync(user, id, username, DateTime.Now, cancellationToken); a.Add(StoreTypes.UserStore); if (!queryResult.Succeeded || queryResult.RowsModified != 1) { await Rollback(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .ServerFault()); } var qUser = queryResult.Result; // Add user to email store var result = await EmailStore.CreateUserAsync(qUser, email, cancellationToken); a.Add(StoreTypes.EmailStore); if (!result.Succeeded || result.RowsModified != 1) { await Rollback(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .ServerFault()); } //Add user to password store var salt = await SecurityConfiguration.RandomProvider.GenerateRandomAsync(cancellationToken); var hashed = await SecurityConfiguration.PasswordHasher.HashPassword(password, salt, cancellationToken); result = await PasswordStore.CreateUserAsync(qUser, hashed, salt, cancellationToken); a.Add(StoreTypes.PasswordStore); if (!result.Succeeded || result.RowsModified != 1) { await Rollback(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .ServerFault()); } // Start adding the email and configure it to be activated with a link. var guid = Guid.NewGuid().ToString(); var token = Convert.ToBase64String( SecurityConfiguration.TokenProvider.CreateToken(qUser, guid, Security.TokenField.Activation)); result = await EmailStore.CreateUserAsync(qUser, email, cancellationToken); a.Add(StoreTypes.EmailStore); if (!result.Succeeded || result.RowsModified != 1) { await Rollback(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .ServerFault()); } result = await TokenStore.CreateTokenAsync(qUser, token, cancellationToken); a.Add(StoreTypes.TokenStore); if (!result.Succeeded || result.RowsModified != 1) { await Rollback(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .ServerFault()); } // Email the user with the result await EmailConfiguration.AccountVerificationTemplate.LoadAsync(new { Email = email, Token = id }); await EmailConfiguration.EmailProvider.Email(EmailConfiguration.AccountVerificationTemplate, email, cancellationToken); // Add a lockout field result = await LockoutStore.CreateUserAsync(qUser, cancellationToken); a.Add(StoreTypes.LockoutStore); if (!result.Succeeded || result.RowsModified != 1) { await Rollback(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .ServerFault()); } // Add a potential claims field result = await ClaimStore.CreateClaimsAsync(qUser, SecurityConfiguration.DefaultClaims, cancellationToken); a.Add(StoreTypes.ClaimStore); if (!result.Succeeded || result.RowsModified != SecurityConfiguration.DefaultClaims.Count()) { await Rollback(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .ServerFault()); } result = await NameStore.CreateUserAsync(qUser, name, cancellationToken); a.Add(StoreTypes.NameStore); if (!result.Succeeded || result.RowsModified != SecurityConfiguration.DefaultClaims.Count()) { await Rollback(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .ServerFault()); } await Commit(cancellationToken, a.ToArray()); return(AuthenticationResult <string> .Success(id)); }
/// <summary> /// Renders each Smart Target region into a list which can be traversed by the caller. /// </summary> /// <param name="helper">The helper to extend</param> /// <param name="regionName">the name of the region to render</param> /// <param name="viewName">the name of the component view</param> /// <param name="maxItems">the number to limit on</param> /// <param name="startIndex">the item index at which to start rendering</param> /// <returns>a list of rendered items for a given region across all promotions</returns> /// public static List <MvcHtmlString> RenderSmartTargetRegionItemsUsingView(this HtmlHelper helper, string regionName, string viewName, int maxItems = 0, int startIndex = 0) { string publicationId = ConfigurationManager.AppSettings["PublicationId"]; LOG.Info(string.Format("Calling RenderSmartTargetRegionItemsUsingView")); // First query Fredhopper for the targeted component IDs ClaimStore claimStore = AmbientDataContext.CurrentClaimStore; string query = AmbientDataHelper.GetTriggers(claimStore); var queryBuilder = new QueryBuilder(); queryBuilder.Parse(query); if (maxItems > 0) { LOG.Info(string.Format("Maxitems ", maxItems)); queryBuilder.MaxItems = maxItems; } LOG.Info("maxItems Value: " + maxItems.ToString()); queryBuilder.StartIndex = startIndex; //Add Publication Info var pubIdUri = new SM.Utils.TcmUri(publicationId); SM.Query.Builder.PublicationCriteria pubCriteria = new SM.Query.Builder.PublicationCriteria(pubIdUri); queryBuilder.AddCriteria(pubCriteria); //Add Region Info RegionCriteria regionCriteria = new RegionCriteria(regionName); queryBuilder.AddCriteria(regionCriteria); ResultSet fredHopperResultset = queryBuilder.Execute(); List <string> componentIds = new List <string>(); foreach (Promotion p in fredHopperResultset.Promotions) { LOG.Info("Promotion ID " + p.PromotionId.ToString()); LOG.Info("Promotion ID " + p.Items.Count().ToString()); foreach (Item i in p.Items) { LOG.Info("Component ID " + i.ComponentUri.ToString()); LOG.Info("Template ID " + i.TemplateUri.ToString()); componentIds.Add(i.ComponentUriAsString + "|" + i.TemplateUriAsString); } } // Next, query the standard Tridion Broker to get the components out. // This is because we should use the master source of published content. // Using the CP source that has been published to Fredhopper (see API or service response). // is not recommended, so we use the master source of published content, i.e. the Tridion Broker. var renderedRegionItemsList = new List <MvcHtmlString>(); foreach (string s in componentIds) { string[] compPresIds = s.Split(new char[] { '|' }); string compId = compPresIds[0], templateId = compPresIds[1]; // We now have the Model (i.e. the Component), but we need to call the View, which is the title of the CT. // The issue is that the Broker API does not expose (nor store) the title of CTs. So the only way to get this // is to grab it from DD4T's rendered Component Presentation XML. IComponent comp = null; ComponentFactory cf = new ComponentFactory(); cf.TryGetComponent(compId, out comp, templateId); try { var renderedCp = helper.Partial(viewName, comp); renderedRegionItemsList.Add(renderedCp); } catch (Exception ex) { LOG.Info("ex : " + ex.Message); } } return(renderedRegionItemsList); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton(Configuration); var cookieTime = TimeSpan.FromMinutes(Configuration.GetSection("Configurations").GetValue <int>("LoginTime")); var cookieSecure = Configuration.GetSection("Configurations").GetValue <bool>("RedirectHttps") ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest; // Register the EF application database context using proxies for lazy loading services.AddDbContext <ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")).UseLazyLoadingProxies() ); // Token expiration (ie. recover password token, confirm email token...) services.Configure <DataProtectionTokenProviderOptions>(opt => opt.TokenLifespan = TimeSpan.FromHours(24)); // Identity services.AddAuthentication(); // Rewrite urls as lowercase services.AddRouting(options => options.LowercaseUrls = true); // Service for configurations services.AddTransient <ConfigurationsService>(); services.AddHttpClient(); services.AddHttpContextAccessor(); services.AddScoped <RedirectService>(); services.AddAutoMapper(typeof(Startup)); // Adds flash session messages (ie. success, error, info messages to the user) services.AddTransient <IFlashMessage, FlashMessage>(); services.AddTransient <IFlashMessageSerializer, JsonFlashMessageSerializer>(); // Lifecycle events services.AddScoped <EntityChangeTracker>(); // Cors services.AddCors(o => o.AddPolicy("Travian", builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); })); // Adds Identity services.AddDefaultIdentity <User>(options => { options.SignIn.RequireConfirmedAccount = true; options.User.RequireUniqueEmail = true; }).AddRoles <Role>() // Uses the Role class for authorization .AddEntityFrameworkStores <ApplicationDbContext>() // Tells Identity to fetch the users from this database .AddClaimsPrincipalFactory <AwareClaimsPrincipalFactory>(); // Services for DDD events // https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation // Register the event dispatcher services.AddTransient <IEventDispatcher, EventDispatcher>(); var serviceHandlers = typeof(Startup).Assembly.DefinedTypes.Where(x => x.GetInterfaces().Contains(typeof(IEventHandler))); // Registers all the event handlers foreach (var serviceHandler in serviceHandlers) { services.Add(new ServiceDescriptor(typeof(IEventHandler), serviceHandler, ServiceLifetime.Transient)); } // Cron jobs related services services.AddTransient <ICronJobManager, CronJobManager>(); var cronJobSubscribers = typeof(Startup).Assembly.DefinedTypes.Where(x => x.GetInterfaces().Contains(typeof(ICronJobSubscriber))); // Registers all the cron job subscribers foreach (var cronJobSubscriber in cronJobSubscribers) { services.Add(new ServiceDescriptor(typeof(ICronJobSubscriber), cronJobSubscriber, ServiceLifetime.Transient)); } // Adds session for storage services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = "SessionCookie"; options.Cookie.SecurePolicy = cookieSecure; options.IdleTimeout = cookieTime; //options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); // Adds controllers if (_isProduction) { services.AddControllersWithViews().AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); } else { services.AddControllersWithViews().AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }).AddRazorRuntimeCompilation(); } // Anti forgery settings services.AddAntiforgery(options => { options.FormFieldName = "AntiForgery"; options.HeaderName = "X-CSRF-TOKEN"; options.SuppressXFrameOptionsHeader = false; options.Cookie.Name = "AntiForgeryCookie"; options.Cookie.Expiration = cookieTime; options.Cookie.SecurePolicy = cookieSecure; }); // Cookie for temp data services.Configure <CookieTempDataProviderOptions>(options => { options.Cookie.Name = "TempDataCookie"; options.Cookie.Expiration = cookieTime; options.Cookie.SecurePolicy = cookieSecure; }); // Configures the Identity by cookie services.ConfigureApplicationCookie(options => { options.ExpireTimeSpan = cookieTime; options.Cookie.Name = "AuthCookie"; options.Cookie.SecurePolicy = cookieSecure; options.Events = new CookieAuthenticationEvents { OnRedirectToLogin = ctx => { var requestPath = ctx.Request.Path; ctx.Response.Redirect("/auth/login"); return(Task.CompletedTask); }, OnRedirectToAccessDenied = ctx => { var requestPath = ctx.Request.Path; ctx.Response.Redirect("/auth/accessdenied"); return(Task.CompletedTask); }, }; }); // Password security services.Configure <IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 1; options.Password.RequiredUniqueChars = 1; }); // Create an access policy for each claim services.AddAuthorization(options => { // Creates one policy for each claim foreach (var claimGroup in ClaimStore.ClaimGroups()) { foreach (var claim in claimGroup.Claims) { options.AddPolicy(claim.Type, policy => { policy.RequireClaim(claim.Type); //Enforce the policy }); } } }); //MVC Grid services.AddMvcGrid(filters => { filters.BooleanFalseOptionText = () => "Não"; filters.BooleanTrueOptionText = () => "Sim"; filters.BooleanEmptyOptionText = () => ""; }); services.AddMvc(options => { options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => "O valor inserido é inválido."); options.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor((x) => "O valor inserido é inválido."); options.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor(x => "Campo obrigatório."); options.ModelBindingMessageProvider.SetMissingRequestBodyRequiredValueAccessor(() => "Campo obrigatório."); options.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() => "Campo obrigatório."); options.ModelBindingMessageProvider.SetNonPropertyUnknownValueIsInvalidAccessor(() => "O valor inserido é inválido."); options.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) => "O valor inserido é inválido."); options.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) => "O valor inserido é inválido."); options.ModelBindingMessageProvider.SetNonPropertyValueMustBeANumberAccessor(() => "O valor inserido tem de ser numérico."); options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor(x => "O valor inserido deve ser numérico."); options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(x => "O valor não pode ser vazio."); }).AddDataAnnotationsLocalization().AddViewLocalization(); // Routes services.AddRouting(); }
public void Add(ClaimStore store, IEnumerable <Claim> claims) { this.Store[store] = this.Get(store) .Concat(claims) .ToArray(); }