protected async Task <IActionResult> RefreshUserToken(Guid userId)
        {
            // Look up the user by its refresh token
            var user = _userService.GetUserById(userId);

            if (user == null)
            {
                return(Ok(new { Errors = new[] { "UserNotExist" } }));
            }

            // Reject if user has been locked out
            if (user.LockoutEnd >= DateTimeOffset.UtcNow)
            {
                return(Ok(new { Errors = new[] { "UserLockedOut" } }));
            }

            // Get roles of current user
            var roles = await _userManager.GetRolesAsync(user);

            // Generate claims and JWT token
            var langs  = Utils.GetAllLanguages();
            var claims = ClaimHelper.GetClaims(user, roles, langs);

            // Generate token
            var token = TokenGenerator.Generate(claims, roles, _config, user.SecurityStamp);

            return(Ok(token));
        }
Exemplo n.º 2
0
        public async Task AddPermissionsToRole(List <string> controllers, string roleName)
        {
            var role = await _roleManager.FindByNameAsync(roleName);

            var claims = _claimHelper.GetClaims();

            foreach (var item in controllers)
            {
                claims = claims.Where(x => x.Contains(item)).ToList();
            }

            foreach (var claim in claims)
            {
                await _roleManager.AddClaimAsync(role, new Claim(claim, role.Id));
            }
        }
        private async Task <IActionResult> GenerateTokenWithRoles(User user, GenerateTokenViewModel model, List <string> requiredRoles)
        {
            if (user == null)
            {
                return(Ok(new { Errors = new[] { "IncorrectLogin" } }));
            }

            //// Verify the password provided
            var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true);

            if (result.IsLockedOut)
            {
                return(Ok(user.LockoutEnd == DateTimeOffset.MaxValue
                    ? new { Errors = new[] { "UserDeactivated" } }
                    : new { Errors = new[] { "UserLockedOut" } }));
            }
            if (result.IsNotAllowed)
            {
                return(Ok(new { Errors = new[] { "EmailNotConfirmed" } }));
            }
            if (!result.Succeeded)
            {
                await _userManager.AccessFailedAsync(user);

                return(Ok(new { Errors = new[] { "IncorrectLogin" } }));
            }

            var activePlanId = string.Empty;

            // Get roles of current user
            var roles = await _userManager.GetRolesAsync(user);

            if (!requiredRoles.Any(requiredRole => roles.Contains(requiredRole)))
            {
                return(Ok(new { Errors = new[] { "UnauthorizedRole" } }));
            }

            // Generate claims and JWT token
            var langs  = Utils.GetAllLanguages();
            var claims = ClaimHelper.GetClaims(user, roles, langs);

            _userService.UpdateLastLogin(user.Id);
            // Generate token
            var token = TokenGenerator.Generate(claims, roles, _config, user.SecurityStamp);

            return(Ok(token));
        }
Exemplo n.º 4
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthorization(option =>
            {
                ClaimHelper claimHelper = new ClaimHelper();

                var claims = claimHelper.GetClaims();

                foreach (var item in claims)
                {
                    option.AddPolicy(item, policy => policy.RequireClaim(item));
                }
            });

            services.Configure <IdentityOptions>(options =>
            {
                // Default User settings.
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@";
                options.User.RequireUniqueEmail = true;

                // Default Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // Default Password settings.
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 4;
                options.Password.RequiredUniqueChars    = 0;

                // Default SignIn settings.
                options.SignIn.RequireConfirmedEmail       = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;
            });

            services.AddSingleton <IEmailSender, EmailSender>();
            services.AddTransient <SeedData>();
            services.AddTransient <IImagePath, ImagePath>();
            services.AddScoped <IUnitOfWork, UnitOfWork.UnitOfWork>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath        = $"/Identity/Account/Login";
                options.LogoutPath       = $"/Identity/Account/Logout";
                options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
                options.Cookie.Name      = "Alphasoft";
            });

            services.Configure <SecurityStampValidatorOptions>(options =>
            {
                // enables immediate logout, after updating the user's state.
                options.ValidationInterval = TimeSpan.Zero;
            });
        }