Example #1
0
        public async Task HandleAsync(UserGameCredentialAddedIntegrationEvent integrationEvent)
        {
            var user = await _userService.FindByIdAsync(integrationEvent.Credential.UserId);

            if (user != null)
            {
                var game = integrationEvent.Credential.Game.ToEnumeration <Game>();

                var claim = new Claim(CustomClaimTypes.GetGamePlayerFor(game), integrationEvent.Credential.PlayerId);

                var result = await _userService.AddClaimAsync(user, claim);

                if (result.Succeeded)
                {
                    _logger.LogInformation(""); // FRANCIS: TODO.
                }
                else
                {
                    _logger.LogError(""); // FRANCIS: TODO.
                }
            }
            else
            {
                _logger.LogCritical(""); // FRANCIS: TODO.
            }
        }
        private async Task <bool> AddClaimsToUser(RegistrationViewModel userRegistered)
        {
            // get the claims for the user roles
            ClaimsForRolesStrategy claimsFromStrategy = new ClaimsForRolesStrategy();
            var claimsForUserRole = claimsFromStrategy.getManagerClaims(userRegistered.Role);

            //add the Claims for the User
            CustomClaimTypes myClaims = new CustomClaimTypes();

            try
            {
                // retrieve the user to add claims to
                var user = await _userManager.FindByEmailAsync(userRegistered.Email);

                //List of Claims
                var userClaims = new List <Claim>();
                userClaims.Add(new Claim("Firstname", user.FirstName));
                userClaims.Add(new Claim(myClaims.Lastname, user.LastName));
                userClaims.Add(new Claim(myClaims.CanCreateCustomer, myClaims.CanCreateCustomer = claimsForUserRole.CanCreateCustomer.ToString()));
                userClaims.Add(new Claim(myClaims.CanCreateProduct, myClaims.CanCreateProduct   = claimsForUserRole.CanCreateProduct.ToString()));
                userClaims.Add(new Claim("Role", userRegistered.Role.ToString()));

                // add ListOfClaims for the user
                var isUserClaimsAddedSuccesfully = await _userManager.AddClaimsAsync(user, userClaims);

                return(isUserClaimsAddedSuccesfully.Succeeded == true ? true : false);
            }
            catch
            {
                throw new Exception("The Claims could not be added");
            }
        }
Example #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Inject my UnitOf Service
            services.AddTransient <UnitOfWork, UnitOfWork>(); // donde declaran UnitOfWork

            //Inject my Repositories (Ascopped: creates just one instance of the repository, for every htttp request we create jst one instance)
            services.AddScoped(typeof(IRepository <>), typeof(Repository <>));
            services.AddScoped <ICustomerRepository, CustomerRepository>();

            //Register EF Core Context with dependency injection
            services.AddDbContext <DummyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                                                                                 options2 => options2.MigrationsAssembly("CustomerManagerAPI")));

            services.AddDbContext <AspNetUserContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                                                                                      options2 => options2.MigrationsAssembly("CustomerManagerAPI")));


            // Inject my Managers Service
            services.AddTransient <RegisterManager, RegisterManager>();  // donde usan RegisterManager ---> invoke instance of RegisterManager
            services.AddTransient <AccountManager, AccountManager>();
            services.AddTransient <CustomerManager, CustomerManager>();
            services.AddTransient <AccountManager, AccountManager>();
            services.AddTransient <OrderManager, OrderManager>();
            services.AddTransient <ProductManager, ProductManager>();
            services.AddTransient <StoredProcedureRepository, StoredProcedureRepository>();
            services.AddTransient <IHttpContextService, HttpContextService>();
            services.AddTransient <BasePerson, BasePerson>();


            // Inject IJwtFactory Service
            services.AddSingleton <IJWFactory, JWTFactory>(); // donde acceden/llaman/usan IJWTFactory ---> invoke instance of JWTFactory

            services.AddIdentity <AppUser, IdentityRole>
                (options =>
            {
                // configure identity options
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredLength         = 6;
            })
            .AddEntityFrameworkStores <AspNetUserContext>();    /* if not added this error shows up:
                                                                 *  Microsoft.AspNetCore.Identity.IUserStore`1[netCoreWepApiAuthJWT.Model.AppUser]' while attempting
                                                                 *  to activate 'Microsoft.AspNetCore.Identity.UserManager`1[netCoreWepApiAuthJWT.Model.AppUser]'. */

            /*Read the JwtIssuerOptions settings from the config file to configure the JwtIssuerOptions and set it up for injection. */
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JWTIssuerOptions));

            // Configure JwtIssuerOptions for some properties of JWTIssuerOptions class.
            services.Configure <JWTIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JWTIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JWTIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            /* tell the ASP.NET Core middleware that we want to use JWT authentication on incoming requests with JWTs */
            // var jwtAppSettingOptions = Configuration.GetSection(nameof(JWTIssuerOptions));

            // sets up the validation parameters that we’re going to pass to ASP.NET’s JWT bearer authentication middleware.
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions[nameof(JWTIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions[nameof(JWTIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = _signingKey,

                RequireExpirationTime = false,
                ValidateLifetime      = false,
                ClockSkew             = TimeSpan.Zero
            };

            // tells the application that we expect JWT tokens as part of the authentication
            // and authorisation processes and to automatically challenge and authenticate.
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = tokenValidationParameters;
            });


            // api user claim policy: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims
            services.AddAuthorization(options =>
            {
                CustomClaimTypes c = new CustomClaimTypes();
                options.AddPolicy("GeneralManager", policy => policy.RequireClaim("Role", "GeneralManager"));
                options.AddPolicy("SectionManager", policy => policy.RequireClaim("Role", "SectionManager"));
                options.AddPolicy("ProductsManager", policy => policy.RequireClaim("Role", "ProductsManager"));
            }); /* Adds a policy named 'GeneralManager', GeneralManager policy checks for the presence of an "GeneralManager" claimType,
                 * and claimValue  on the incoming token payload  with value of "GeneralManager".
                 * We then apply the policy using the Policy property on the AuthorizeAttribute attribute in our Controller to specify the policy name;
                 * Only Identity with the stated claims will be Authorise to access the Controller, Action we apply this Policy.
                 */

            // Inject HttpContextAccessor , to access the HttpContext, manipulate http request response etc
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Add service and create Policy with options
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAngular", //Policy == AllowAngular, Enable policy in Controller: [EnableCors("AllowAngular")]
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyHeader()
                                  .AllowAnyMethod());
            });

            // https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
            // Register the Swagger generator, defining one or more Swagger documents
            /*a Swagger generator that builds SwaggerDocument objects directly from your routes, controllers, and models. */
            services.AddSwaggerGen(config =>
            {
                // Creates a Swagger doc named v1
                config.SwaggerDoc("v1", new Info {
                    Title = "CustomerManagerAPI", Version = "v1"
                });
            });

            // https://stackoverflow.com/questions/13510204/json-net-self-referencing-loop-detected
            // Prevents web api from return jst only the first element of a list or IEnumerable
            services.AddMvc().AddJsonOptions(options => {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });


            services.AddMvc();
        }
 public PermissionFilter(string permission, CustomClaimTypes customClaimTypes)
 {
     _permission       = permission;
     _customClaimTypes = customClaimTypes;
 }