emonney / QuickApp

ASP.NET Core / Angular startup project template with complete login, user and role management. Plus other useful services for Quick Application Development
https://www.ebenmonney.com/quickapp
MIT License
1.26k stars 594 forks source link

Issue while user log in #98

Closed shans-1983 closed 5 years ago

shans-1983 commented 6 years ago

Stack Trace: [FTL] Error whilst creating and seeding database (944fb156) System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager1[Models.ApplicationUser]' while attempting to activate 'DataAccess.Core.AccountManager'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType, ServiceProvider serviceProvider) at System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd[TKey,TValue,TArg](ConcurrentDictionary2 dictionary, TKey key, Func`3 valueFactory, TArg arg) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at PulseSource.Program.Main(String[] args) in C:\Users\Shankar\source\repos\PulseSource\PulseSource\Program.cs:line 27

shans-1983 commented 6 years ago

Startup.cs using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using DataAccess; using DataAccess.Models; using System.Net; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http; using AutoMapper; using Newtonsoft.Json; using DataAccess.Core; using DataAccess.Core.Interface; using Microsoft.AspNetCore.Authorization; using PulseSource.ViewModels; using HelperLibrary; using PulseSource.Authorization; using AspNet.Security.OpenIdConnect.Primitives; using Microsoft.AspNetCore.Identity; using Swashbuckle.AspNetCore.Swagger; using AppPermissions = DataAccess.Core.ApplicationPermissions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Rewrite; using System.Collections.Generic; using Models; using Repository; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.OAuth;

namespace PulseSource { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"], b => b.MigrationsAssembly("PulseSource"));
            options.UseOpenIddict();
        });

        // add identity
        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Configure Identity options and password complexity here
        services.Configure<IdentityOptions>(options =>
        {
            // User settings
            options.User.RequireUniqueEmail = true;

            //    //// Password settings
            //    //options.Password.RequireDigit = true;
            //    //options.Password.RequiredLength = 8;
            //    //options.Password.RequireNonAlphanumeric = false;
            //    //options.Password.RequireUppercase = true;
            //    //options.Password.RequireLowercase = false;

            //    //// Lockout settings
            //    //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            //    //options.Lockout.MaxFailedAccessAttempts = 10;

            options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
            options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
            options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
        });

        // Register the OpenIddict services.
        services.AddOpenIddict(options =>
        {
            options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
            options.AddMvcBinders();
            options.EnableTokenEndpoint("/connect/token");
            options.AllowPasswordFlow();
            options.AllowRefreshTokenFlow();

            //if (_hostingEnvironment.IsDevelopment()) //Uncomment to only disable Https during development
            options.DisableHttpsRequirement();

            //options.UseRollingTokens(); //Uncomment to renew refresh tokens on every refreshToken request
            //options.AddSigningKey(new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration["STSKey"])));
        });

        //services.AddAuthentication(options =>
        //{
        //    options.DefaultAuthenticateScheme = AuthenticationSchemes.Basic;
        //    options.DefaultChallengeScheme = OAuthValidationDefaults.AuthenticationScheme;
        //}).AddOAuthValidation();

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

        services.AddAuthentication((cfg =>
        {
            cfg.DefaultScheme = IdentityConstants.ApplicationScheme;
            cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })).AddJwtBearer();

        // Add cors
        services.AddCors();

        // Add framework services.
        services.AddMvc();

        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

        // Enforce https during production. To quickly enable ssl during development. Go to: Project Properties->Debug->Enable SSL
        //if (!_hostingEnvironment.IsDevelopment())
        //    services.Configure<MvcOptions>(options => options.Filters.Add(new RequireHttpsAttribute()));

        //Todo: ***Using DataAnnotations for validation until Swashbuckle supports FluentValidation***
        //services.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());

        //.AddJsonOptions(opts =>
        //{
        //    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        //});

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "PulseSource API", Version = "v1" });

            c.AddSecurityDefinition("OpenID Connect", new OAuth2Scheme
            {
                Type = "oauth2",
                Flow = "password",
                TokenUrl = "/connect/token"
            });
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy(Authorization.Policies.ViewAllUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewUsers));
            options.AddPolicy(Authorization.Policies.ManageAllUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageUsers));

            options.AddPolicy(Authorization.Policies.ViewAllRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewRoles));
            options.AddPolicy(Authorization.Policies.ViewRoleByRoleNamePolicy, policy => policy.Requirements.Add(new ViewRoleAuthorizationRequirement()));
            options.AddPolicy(Authorization.Policies.ManageAllRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageRoles));

            options.AddPolicy(Authorization.Policies.AssignAllowedRolesPolicy, policy => policy.Requirements.Add(new AssignRolesAuthorizationRequirement()));
        });

        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<AutoMapperProfile>();
        });

        // Configurations
        services.Configure<SmtpConfig>(Configuration.GetSection("SmtpConfig"));

        // Business Services
        services.AddScoped<IEmailer, Emailer>();

        // Repositories
        services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
        services.AddScoped<IAccountManager, AccountManager>();

        // Auth Handlers
        services.AddSingleton<IAuthorizationHandler, ViewUserAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, ManageUserAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, ViewRoleAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, AssignRolesAuthorizationHandler>();

        // DB Creation and Seeding
        services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug(LogLevel.Warning);
        loggerFactory.AddFile(Configuration.GetSection("Logging"));

        Utilities.ConfigureLogger(loggerFactory);
        EmailTemplates.Initialize(env);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // Enforce https during production
            //var rewriteOptions = new RewriteOptions()
            //    .AddRedirectToHttps();
            //app.UseRewriter(rewriteOptions);

            app.UseExceptionHandler("/Home/Error");
        }

        //Configure Cors
        app.UseCors(builder => builder
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod());

        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseAuthentication();

        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "PulseSource API V1");
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
}

}

shans-1983 commented 6 years ago

Program.cs

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using HelperLibrary; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Repository;

namespace PulseSource { public class Program { public static void Main(string[] args) { var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var databaseInitializer = services.GetRequiredService<IDatabaseInitializer>();
                databaseInitializer.SeedAsync().Wait();
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogCritical(LoggingEvents.INIT_DATABASE, ex, LoggingEvents.INIT_DATABASE.Name);
            }
        }

        host.Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

}

shans-1983 commented 6 years ago

package.json

{ "name": "pulsesource", "private": true, "version": "0.0.0", "scripts": { "start": "node PulseScript.js", "test": "echo \"Error: no test specified\" && exit 1" }, "devDependencies": { "@angular/animations": "4.2.5", "@angular/common": "4.2.5", "@angular/compiler": "4.2.5", "@angular/compiler-cli": "4.2.5", "@angular/core": "4.2.5", "@angular/forms": "4.2.5", "@angular/http": "4.2.5", "@angular/platform-browser": "4.2.5", "@angular/platform-browser-dynamic": "4.2.5", "@angular/platform-server": "4.2.5", "@angular/router": "4.2.5", "@ngtools/webpack": "1.5.0", "@types/chai": "4.0.1", "@types/jasmine": "2.5.53", "@types/webpack-env": "1.13.0", "angular2-router-loader": "0.3.5", "angular2-template-loader": "0.6.2", "aspnet-prerendering": "^3.0.1", "aspnet-webpack": "^2.0.1", "awesome-typescript-loader": "3.2.1", "bootstrap": "3.3.7", "chai": "4.0.2", "css": "2.2.1", "css-loader": "0.28.4", "es6-shim": "0.35.3", "event-source-polyfill": "0.0.9", "expose-loader": "0.7.3", "extract-text-webpack-plugin": "2.1.2", "file-loader": "0.11.2", "html-loader": "0.4.5", "isomorphic-fetch": "2.2.1", "jasmine-core": "2.6.4", "jquery": "3.2.1", "json-loader": "0.5.4", "karma": "1.7.0", "karma-chai": "0.1.0", "karma-chrome-launcher": "2.2.0", "karma-cli": "1.0.1", "karma-jasmine": "1.1.0", "karma-webpack": "2.0.3", "preboot": "4.5.2", "raw-loader": "0.5.1", "reflect-metadata": "0.1.10", "rxjs": "5.4.2", "style-loader": "0.18.2", "to-string-loader": "1.1.5", "typescript": "2.4.1", "url-loader": "0.5.9", "webpack": "2.5.1", "webpack-hot-middleware": "2.18.2", "webpack-merge": "4.1.0", "zone.js": "0.8.12" } }

shans-1983 commented 6 years ago

Getting an issue while logging in as Internal server error in the notification.

liphis commented 6 years ago

Can you check if the database was created? And if your current app has access to it. It is clear that QuickApp failed to insert initial values. I did not yet compare the files you provided with the original ones, but you have to have SQL server according to your code. Take a look at the Logs folder for some hints which is not in the stack trace.

slang123 commented 6 years ago

something you can try.

emonney commented 5 years ago

Closing issue. If this still persists feel free to reopen with more details of the current status